context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.IO;
using System.Net;
namespace Box.V2.Config
{
/// <summary>
/// Builder used to instantiate new BoxConfig. It follows FluentBuilder pattern and can be used by chaining methods.
/// </summary>
public class BoxConfigBuilder
{
/// <summary>
/// Instantiates a BoxConfigBuilder with all of the standard defaults
/// </summary>
/// <param name="clientId"></param>
/// <param name="clientSecret"></param>
/// <param name="redirectUri"></param>
/// <returns>BoxConfigBuilder instance.</returns>
public BoxConfigBuilder(string clientId, string clientSecret, Uri redirectUri)
{
ClientId = clientId;
ClientSecret = clientSecret;
RedirectUri = redirectUri;
UserAgent = BoxConfig.DefaultUserAgent;
}
/// <summary>
/// Instantiates a BoxConfigBuilder for use with JWT authentication
/// </summary>
/// <param name="clientId"></param>
/// <param name="clientSecret"></param>
/// <param name="enterpriseId"></param>
/// <param name="jwtPrivateKey"></param>
/// <param name="jwtPrivateKeyPassword"></param>
/// <param name="jwtPublicKeyId"></param>
/// <returns>BoxConfigBuilder instance.</returns>
public BoxConfigBuilder(string clientId, string clientSecret, string enterpriseId,
string jwtPrivateKey, string jwtPrivateKeyPassword, string jwtPublicKeyId)
{
ClientId = clientId;
ClientSecret = clientSecret;
EnterpriseId = enterpriseId;
JWTPrivateKey = jwtPrivateKey;
JWTPrivateKeyPassword = jwtPrivateKeyPassword;
JWTPublicKeyId = jwtPublicKeyId;
UserAgent = BoxConfig.DefaultUserAgent;
}
/// <summary>
/// Instantiates a BoxConfigBuilder for use with CCG authentication
/// </summary>
/// <param name="clientId"></param>
/// <param name="clientSecret"></param>
/// <returns>BoxConfigBuilder instance.</returns>
public BoxConfigBuilder(string clientId, string clientSecret)
{
ClientId = clientId;
ClientSecret = clientSecret;
UserAgent = BoxConfig.DefaultUserAgent;
}
/// <summary>
/// Create BoxConfigBuilder from json file.
/// </summary>
/// <param name="jsonFile">json file stream.</param>
/// <returns>BoxConfigBuilder instance.</returns>
public static BoxConfigBuilder CreateFromJsonFile(Stream jsonFile)
{
var config = BoxConfig.CreateFromJsonFile(jsonFile);
var configBuilder = new BoxConfigBuilder();
RewritePropertiesToBuilder(configBuilder, config);
return configBuilder;
}
/// <summary>
/// Create BoxConfigBuilder from json string
/// </summary>
/// <param name="jsonString">json string.</param>
/// <returns>BoxConfigBuilder instance.</returns>
public static BoxConfigBuilder CreateFromJsonString(string jsonString)
{
var config = BoxConfig.CreateFromJsonString(jsonString);
var configBuilder = new BoxConfigBuilder();
RewritePropertiesToBuilder(configBuilder, config);
return configBuilder;
}
private static void RewritePropertiesToBuilder(BoxConfigBuilder configBuilder, IBoxConfig config)
{
configBuilder.ClientId = config.ClientId;
configBuilder.ClientSecret = config.ClientSecret;
configBuilder.JWTPrivateKey = config.JWTPrivateKey;
configBuilder.JWTPrivateKeyPassword = config.JWTPrivateKeyPassword;
configBuilder.JWTPublicKeyId = config.JWTPublicKeyId;
configBuilder.EnterpriseId = config.EnterpriseId;
}
private BoxConfigBuilder() { }
/// <summary>
/// Create IBoxConfig from the builder.
/// </summary>
/// <returns>IBoxConfig instance.</returns>
public IBoxConfig Build()
{
return new BoxConfig(this);
}
/// <summary>
/// Sets user agent.
/// </summary>
/// <param name="userAgent">User agent.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetUserAgent(string userAgent)
{
UserAgent = userAgent;
return this;
}
/// <summary>
/// Sets BoxAPI host uri.
/// </summary>
/// <param name="boxApiHostUri">BoxAPI host uri.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetBoxApiHostUri(Uri boxApiHostUri)
{
BoxApiHostUri = boxApiHostUri;
return this;
}
/// <summary>
/// Sets BoxAPI account host uri.
/// </summary>
/// <param name="boxAccountApiHostUri">BoxAPI account host uri.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetBoxAccountApiHostUri(Uri boxAccountApiHostUri)
{
BoxAccountApiHostUri = boxAccountApiHostUri;
return this;
}
/// <summary>
/// Sets BoxAPI uri.
/// </summary>
/// <param name="boxApiUri">BoxAPI uri.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetBoxApiUri(Uri boxApiUri)
{
BoxApiUri = boxApiUri;
return this;
}
/// <summary>
/// Sets BoxAPI upload uri.
/// </summary>
/// <param name="boxUploadApiUri">BoxAPI upload uri.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetBoxUploadApiUri(Uri boxUploadApiUri)
{
BoxUploadApiUri = boxUploadApiUri;
return this;
}
/// <summary>
/// Sets BoxAPI auth token uri.
/// </summary>
/// <param name="boxAuthTokenApiUri">BoxAPI auth token uri.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetBoxTokenApiUri(Uri boxAuthTokenApiUri)
{
BoxAuthTokenApiUri = boxAuthTokenApiUri;
return this;
}
/// <summary>
/// Sets redirect uri.
/// </summary>
/// <param name="redirectUri">Redirect uri.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetRedirectUri(Uri redirectUri)
{
RedirectUri = redirectUri;
return this;
}
/// <summary>
/// Sets device id.
/// </summary>
/// <param name="deviceId">Device id.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetDeviceId(string deviceId)
{
DeviceId = deviceId;
return this;
}
/// <summary>
/// Sets device name.
/// </summary>
/// <param name="deviceName">Device name.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetDeviceName(string deviceName)
{
DeviceName = deviceName;
return this;
}
/// <summary>
/// Sets acceptEncoding.
/// </summary>
/// <param name="acceptEncoding">AcceptEncoding.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetAcceptEncoding(CompressionType? acceptEncoding)
{
AcceptEncoding = acceptEncoding;
return this;
}
/// <summary>
/// Sets web proxy for HttpRequestHandler.
/// </summary>
/// <param name="webProxy">Web proxy for HttpRequestHandler.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetWebProxy(IWebProxy webProxy)
{
WebProxy = webProxy;
return this;
}
/// <summary>
/// Sets connection timeout for HttpRequestHandler.
/// </summary>
/// <param name="timeout">Connection timeout for HttpRequestHandler.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetTimeout(TimeSpan timeout)
{
Timeout = timeout;
return this;
}
/// <summary>
/// Sets enterprise id.
/// </summary>
/// <param name="enterpriseId">Enteprise id.</param>
/// <returns>this BoxConfigBuilder object for chaining</returns>
public BoxConfigBuilder SetEnterpriseId(string enterpriseId)
{
EnterpriseId = enterpriseId;
return this;
}
public string ClientId { get; private set; }
public string ClientSecret { get; private set; }
public string EnterpriseId { get; private set; }
public string JWTPrivateKey { get; private set; }
public string JWTPrivateKeyPassword { get; private set; }
public string JWTPublicKeyId { get; private set; }
public string UserAgent { get; private set; }
public Uri BoxApiHostUri { get; private set; } = new Uri(Constants.BoxApiHostUriString);
public Uri BoxAccountApiHostUri { get; private set; } = new Uri(Constants.BoxAccountApiHostUriString);
public Uri BoxApiUri { get; private set; } = new Uri(Constants.BoxApiUriString);
public Uri BoxUploadApiUri { get; private set; } = new Uri(Constants.BoxUploadApiUriString);
public Uri BoxAuthTokenApiUri { get; private set; } = new Uri(Constants.BoxAuthTokenApiUriString);
public Uri RedirectUri { get; private set; }
public string DeviceId { get; private set; }
public string DeviceName { get; private set; }
/// <summary>
/// Sends compressed responses from Box for faster response times
/// </summary>
public CompressionType? AcceptEncoding { get; private set; }
/// <summary>
/// The web proxy for HttpRequestHandler
/// </summary>
public IWebProxy WebProxy { get; private set; }
/// <summary>
/// Timeout for the connection
/// </summary>
public TimeSpan? Timeout { get; private set; }
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Runtime.TypeSystem
{
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
[WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_VTable" )]
public sealed class VTable
{
[AllowCompileTimeIntrospection]
[Flags]
public enum Shape : byte
{
Invalid = 0x00,
Scalar = ValueType | 0x01,
Struct = ValueType | 0x02,
Interface = Reference | 0x03,
Class = Reference | 0x04,
ArrayRoot = Reference | Array | 0x05,
SzArray = Reference | Array | 0x06,
MultiArray = Reference | Array | 0x07,
ValueType = 0x20,
Reference = 0x40,
Array = 0x80,
}
public struct InterfaceMap
{
public static readonly InterfaceMap[] SharedEmptyArray = new InterfaceMap[0];
//
// State
//
public VTable Interface;
public CodePointer[] MethodPointers;
}
//
// State
//
//
// The two size fields, BaseSize and ElementSize, are only copy of the corresponding values from TypeInfo.
// They are here for performance reasons (copying the values here removes one indirection).
// During heap walking, we need to compute the size of a block, to skip over it.
//
// This is done treating each object as if it were an array and computing the quantity:
//
// <size> = Vt.BaseSize + Vt.ElementSize * <array length>
//
// This works because arrays have an extra uint field at the start, holding the number of elements in the array.
// However, instances of non-array types will have random data at the offset of the Length field.
// This is not a problem, as long as we ensure that ElementSize is set to zero.
// Whatever the value of array length, the multiplication by zero will make it irrelevant.
//
[WellKnownField( "VTable_BaseSize" )] public uint BaseSize;
[WellKnownField( "VTable_ElementSize" )] public uint ElementSize;
[WellKnownField( "VTable_TypeInfo" )] public TypeRepresentation TypeInfo;
[WellKnownField( "VTable_GCInfo" )] public GCInfo GCInfo;
[WellKnownField( "VTable_Type" )] public Type Type;
[WellKnownField( "VTable_ShapeCategory" )] public Shape ShapeCategory;
//
// TODO: We need to embed these pointers in the VTable object itself.
// TODO: This way we can assume a fixed offset between MethodPointers and VTable and hardcode it in the method lookup code.
//
[WellKnownField( "VTable_MethodPointers" )] public CodePointer[] MethodPointers;
[WellKnownField( "VTable_InterfaceMap" )] public InterfaceMap[] InterfaceMethodPointers;
//
// Constructor Methods
//
public VTable( TypeRepresentation owner )
{
this.TypeInfo = owner;
this.InterfaceMethodPointers = InterfaceMap.SharedEmptyArray;
}
//--//
//
// Helper Methods
//
public static bool SameType( object a ,
object b )
{
return Get( a ) == Get( b );
}
//--//
public void ApplyTransformation( TransformationContext context )
{
context.Push( this );
context.Transform( ref this.BaseSize );
context.Transform( ref this.ElementSize );
context.Transform( ref this.TypeInfo );
context.Transform( ref this.GCInfo );
context.Transform( ref this.MethodPointers );
context.Pop();
}
//--//
//
// Access Methods
//
[WellKnownMethod( "VTable_Get" )]
[MethodImpl( MethodImplOptions.InternalCall )]
public extern static VTable Get( object a );
[WellKnownMethod( "VTable_GetInterface" )]
public static CodePointer[] GetInterface( object a ,
VTable vtblInterface )
{
VTable vtbl = Get( a );
InterfaceMap[] array = vtbl.InterfaceMethodPointers;
for(int i = 0; i < array.Length; i++)
{
if(Object.ReferenceEquals( array[i].Interface, vtblInterface ))
{
return array[i].MethodPointers;
}
}
return null;
}
[Inline]
public static VTable GetFromType( Type t )
{
return GetFromTypeHandle( t.TypeHandle );
}
[MethodImpl( MethodImplOptions.InternalCall )]
public extern static VTable GetFromTypeHandle( RuntimeTypeHandle hnd );
//--//
[Inline]
public bool CanBeAssignedFrom( VTable target )
{
if(this == target)
{
return true;
}
return CanBeAssignedFrom_Slow( target );
}
[NoInline]
private bool CanBeAssignedFrom_Slow( VTable source )
{
if(source.IsSubclassOf( this ))
{
return true;
}
if(this.IsArray && source.IsArray)
{
CHECKS.ASSERT( this.ShapeCategory == Shape.SzArray || this.ShapeCategory == Shape.MultiArray, "Found array that does not inherit from System.Array" );
if(this.ShapeCategory == source.ShapeCategory)
{
ArrayReferenceTypeRepresentation tdThis = (ArrayReferenceTypeRepresentation)this .TypeInfo;
ArrayReferenceTypeRepresentation tdSource = (ArrayReferenceTypeRepresentation)source.TypeInfo;
if(tdThis.SameShape( tdSource ))
{
TypeRepresentation subThis = tdThis .ContainedType.UnderlyingType;
TypeRepresentation subSource = tdSource.ContainedType.UnderlyingType;
VTable subVTableThis = subThis .VirtualTable;
VTable subVTableSource = subSource.VirtualTable;
if(subVTableThis == subVTableSource)
{
return true;
}
if(subVTableSource.IsValueType)
{
//
// We require exact matching for value types.
//
return false;
}
if(subVTableThis.IsInterface)
{
return subVTableSource.ImplementsInterface( subVTableThis );
}
return subVTableThis.CanBeAssignedFrom_Slow( subVTableSource );
}
}
}
return false;
}
[NoInline]
public bool IsSubclassOf( VTable target )
{
TypeRepresentation td = this.TypeInfo;
while(td != null)
{
if(target == td.VirtualTable)
{
return true;
}
td = td.Extends;
}
return false;
}
[NoInline]
public bool ImplementsInterface( VTable expectedItf )
{
VTable.InterfaceMap[] itfs = this.InterfaceMethodPointers;
for(int i = itfs.Length; --i >= 0; )
{
if(Object.ReferenceEquals( itfs[i].Interface, expectedItf ))
{
return true;
}
}
return false;
}
//
// Access Methods
//
public bool IsArray
{
[Inline]
get
{
return (this.ShapeCategory & Shape.Array) != 0;
}
}
public bool IsValueType
{
[Inline]
get
{
return (this.ShapeCategory & Shape.ValueType) != 0;
}
}
public bool IsInterface
{
[Inline]
get
{
return this.ShapeCategory == Shape.Interface;
}
}
//
// Debug Methods
//
public override string ToString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat( "VTable({0})", this.TypeInfo );
return sb.ToString();
}
}
}
| |
using System;
using System.Linq;
using System.Text.RegularExpressions;
using CM3D2.YATranslator.Plugin.Translation;
using CM3D2.YATranslator.Plugin.Utils;
using UnityEngine;
using Logger = CM3D2.YATranslator.Plugin.Utils.Logger;
namespace CM3D2.YATranslator.Plugin
{
[ConfigSection("Clipboard")]
public class ClipboardConfiguration
{
public bool Enable = false;
public float WaitTime = 0.5f;
public int[] AllowedLevels { get; internal set; } = {-1};
public string Levels
{
get => "-1";
set => AllowedLevels = value.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
}
}
[ConfigSection("Subtitles")]
public class SubtitleConfiguration
{
private static readonly Regex RgbaPattern =
new Regex(@"RGBA\(\s*(?<r>\d\.\d+)\s*,\s*(?<g>\d\.\d+)\s*,\s*(?<b>\d\.\d+)\s*,\s*(?<a>\d\.\d+)\s*\)");
private static readonly Regex Vec2Pattern = new Regex(@"\(\s*(?<x>-?\d+\.\d+)\s*,\s*(?<y>-?\d+\.\d+)\s*\)");
public bool Enable = true;
public int FontSize = 20;
public int FontSizeVR = 40;
public bool HideWhenClipStops = true;
public bool Outline = true;
public float OutlineThickness = 1.0f;
public bool ShowUntranslatedText = false;
public TextAnchor Alignment { get; private set; } = TextAnchor.UpperCenter;
public Color Color { get; private set; } = Color.white;
public string FontColor
{
get => Color.ToString();
set => Color = ParseColor(value);
}
public string FontStyle
{
get => Style.ToString();
set => Style = Extensions.ParseEnum<FontStyle>(value, true);
}
public Vector2 Offset { get; private set; } = Vector2.zero;
public Vector2 OffsetVR { get; private set; } = Vector2.zero;
public string OutlineColor
{
get => TextOutlineColor.ToString();
set => TextOutlineColor = ParseColor(value);
}
public FontStyle Style { get; private set; } = UnityEngine.FontStyle.Bold;
public string TextAlignment
{
get => Alignment.ToString();
set => Alignment = Extensions.ParseEnum<TextAnchor>(value, true);
}
public string TextOffset
{
get => Offset.ToString();
set => Offset = ParseVec2(value);
}
public string TextOffsetVR
{
get => OffsetVR.ToString();
set => OffsetVR = ParseVec2(value);
}
public Color TextOutlineColor { get; private set; } = Color.black;
private static Vector2 ParseVec2(string value)
{
var m = Vec2Pattern.Match(value);
if (!m.Success)
throw new FormatException("Invalid Vec2 format");
float x = float.Parse(m.Groups["x"].Value);
float y = float.Parse(m.Groups["y"].Value);
return new Vector2(x, y);
}
private static Color ParseColor(string value)
{
var m = RgbaPattern.Match(value);
if (!m.Success)
throw new FormatException("Invalid RGBA format");
float r = float.Parse(m.Groups["r"].Value);
float g = float.Parse(m.Groups["g"].Value);
float b = float.Parse(m.Groups["b"].Value);
float a = float.Parse(m.Groups["a"].Value);
return new Color(r, g, b, a);
}
}
[ConfigSection("Config")]
public class PluginConfiguration
{
public bool EnableTranslationReload = false;
private readonly Regex parameterReplacementRegex = new Regex("{([^}]*)}");
private readonly string[] texTemplateVariables = {"NAME", "HASH", "METADATA", "LEVEL"};
public int[] AllowedDumpLevels { get; private set; } = {-1};
public ClipboardConfiguration Clipboard { get; set; } = new ClipboardConfiguration();
public string Dump
{
get => "None";
set
{
var parts = value.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
DumpTypes = parts.Select(str => (DumpType) Enum.Parse(typeof(DumpType), str.Trim(), true)).ToArray();
Logger.DumpTypes = DumpTypes;
}
}
public string DumpLevels
{
get => "-1";
set
{
AllowedDumpLevels = value.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
Logger.DumpLevels = AllowedDumpLevels;
}
}
public DumpType[] DumpTypes { get; private set; } = new DumpType[0];
public string Load
{
get => ResourceType.All.ToString();
set
{
var parts = value.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
LoadResourceTypes = parts.Aggregate(ResourceType.None,
(current, part) =>
current | (ResourceType) Enum.Parse(typeof(ResourceType), part.Trim(), true));
}
}
public ResourceType LoadResourceTypes { get; private set; } = ResourceType.All;
public KeyCode ReloadTranslationsKeyCode { get; private set; } = KeyCode.F12;
public string ReloadTranslationsKey
{
get => ReloadTranslationsKeyCode.ToString();
set => ReloadTranslationsKeyCode = (KeyCode) Enum.Parse(typeof(KeyCode), value, true);
}
public string MemoryOptimizations
{
get => OptimizationFlags.ToString();
set => OptimizationFlags = (MemoryOptimizations)Enum.Parse(typeof(MemoryOptimizations), value, true);
}
public MemoryOptimizations OptimizationFlags { get; private set; } = Translation.MemoryOptimizations.None;
public SubtitleConfiguration Subtitles { get; set; } = new SubtitleConfiguration();
public string TextureNameTemplate
{
get => "{NAME}";
set
{
string name = value.Trim();
if (string.IsNullOrEmpty(name) || !FileUtils.IsValidFilename(name))
throw new ArgumentException("Invalid file name");
name = parameterReplacementRegex.Replace(name,
m =>
{
string template = m.Groups[1].Value;
int i = Array.IndexOf(texTemplateVariables, template.Trim().ToUpper());
return i < 0 ? m.Value : $"{{{i.ToString()}}}";
});
Logger.TextureNameTemplate = name;
}
}
public string Verbosity
{
get => ResourceType.None.ToString();
set
{
var parts = value.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
VerbosityLevel = parts.Aggregate(ResourceType.None,
(current, part) =>
current | (ResourceType) Enum.Parse(typeof(ResourceType), part.Trim(), true));
Logger.Verbosity = VerbosityLevel;
}
}
public ResourceType VerbosityLevel { get; private set; } = ResourceType.None;
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>AccountBudget</c> resource.</summary>
public sealed partial class AccountBudgetName : gax::IResourceName, sys::IEquatable<AccountBudgetName>
{
/// <summary>The possible contents of <see cref="AccountBudgetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>.
/// </summary>
CustomerAccountBudget = 1,
}
private static gax::PathTemplate s_customerAccountBudget = new gax::PathTemplate("customers/{customer_id}/accountBudgets/{account_budget_id}");
/// <summary>Creates a <see cref="AccountBudgetName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AccountBudgetName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AccountBudgetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AccountBudgetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AccountBudgetName"/> with the pattern
/// <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="accountBudgetId">The <c>AccountBudget</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AccountBudgetName"/> constructed from the provided ids.</returns>
public static AccountBudgetName FromCustomerAccountBudget(string customerId, string accountBudgetId) =>
new AccountBudgetName(ResourceNameType.CustomerAccountBudget, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), accountBudgetId: gax::GaxPreconditions.CheckNotNullOrEmpty(accountBudgetId, nameof(accountBudgetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AccountBudgetName"/> with pattern
/// <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="accountBudgetId">The <c>AccountBudget</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AccountBudgetName"/> with pattern
/// <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>.
/// </returns>
public static string Format(string customerId, string accountBudgetId) =>
FormatCustomerAccountBudget(customerId, accountBudgetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AccountBudgetName"/> with pattern
/// <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="accountBudgetId">The <c>AccountBudget</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AccountBudgetName"/> with pattern
/// <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>.
/// </returns>
public static string FormatCustomerAccountBudget(string customerId, string accountBudgetId) =>
s_customerAccountBudget.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(accountBudgetId, nameof(accountBudgetId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="AccountBudgetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/accountBudgets/{account_budget_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="accountBudgetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AccountBudgetName"/> if successful.</returns>
public static AccountBudgetName Parse(string accountBudgetName) => Parse(accountBudgetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AccountBudgetName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/accountBudgets/{account_budget_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="accountBudgetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AccountBudgetName"/> if successful.</returns>
public static AccountBudgetName Parse(string accountBudgetName, bool allowUnparsed) =>
TryParse(accountBudgetName, allowUnparsed, out AccountBudgetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AccountBudgetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/accountBudgets/{account_budget_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="accountBudgetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AccountBudgetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string accountBudgetName, out AccountBudgetName result) =>
TryParse(accountBudgetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AccountBudgetName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/accountBudgets/{account_budget_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="accountBudgetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AccountBudgetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string accountBudgetName, bool allowUnparsed, out AccountBudgetName result)
{
gax::GaxPreconditions.CheckNotNull(accountBudgetName, nameof(accountBudgetName));
gax::TemplatedResourceName resourceName;
if (s_customerAccountBudget.TryParseName(accountBudgetName, out resourceName))
{
result = FromCustomerAccountBudget(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(accountBudgetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AccountBudgetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string accountBudgetId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AccountBudgetId = accountBudgetId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AccountBudgetName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="accountBudgetId">The <c>AccountBudget</c> ID. Must not be <c>null</c> or empty.</param>
public AccountBudgetName(string customerId, string accountBudgetId) : this(ResourceNameType.CustomerAccountBudget, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), accountBudgetId: gax::GaxPreconditions.CheckNotNullOrEmpty(accountBudgetId, nameof(accountBudgetId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AccountBudget</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string AccountBudgetId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerAccountBudget: return s_customerAccountBudget.Expand(CustomerId, AccountBudgetId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AccountBudgetName);
/// <inheritdoc/>
public bool Equals(AccountBudgetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AccountBudgetName a, AccountBudgetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AccountBudgetName a, AccountBudgetName b) => !(a == b);
}
public partial class AccountBudget
{
/// <summary>
/// <see cref="gagvr::AccountBudgetName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal AccountBudgetName ResourceNameAsAccountBudgetName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::AccountBudgetName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="BillingSetupName"/>-typed view over the <see cref="BillingSetup"/> resource name property.
/// </summary>
internal BillingSetupName BillingSetupAsBillingSetupName
{
get => string.IsNullOrEmpty(BillingSetup) ? null : BillingSetupName.Parse(BillingSetup, allowUnparsed: true);
set => BillingSetup = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::AccountBudgetName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal AccountBudgetName AccountBudgetName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::AccountBudgetName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using Helpers;
using Types;
using System.Threading.Tasks;
using System.Linq.Expressions;
namespace Modeling
{
public class NetworkModel
{
public string Name { get; private set;}
#region PARAMETERS
private Matrix<double> RoutingMatrix;
public List<Vector<double>> Lambda { get; private set; }
public List<Vector<double>> Mu { get; private set; }
public Vector<double> Lambda0 { get; private set; }
public int StreamsCount { get; private set; }
public int NodesCount { get; private set; }
public List<Vector<double>> InputProbability{ get; private set; }
public List<Vector<double>> E { get; private set; }
public List<Vector<double>> LambdaBar { get; private set; }
public List<Vector<double>> Ro { get; private set; }
public List<Vector<double>> RoBar { get; private set; }
public Vector<double> RoTotal { get; private set; }
public double AveragePaths { get; private set; }
public Vector<int> MinPath { get; private set; }
public Vector<int> MaxPath { get; private set; }
public List<Vector<int>> Paths { get; private set; }
public List<double> TransitionProbabilities { get; private set; }
public int StartNode { get; private set; }
public int TargetNode { get; private set; }
#endregion
#region PROBABILITY-TIME CHARACTERISTICS
public Vector<double> Ws { get; private set; }
public List<Vector<double>> Us { get; private set; }
public List<Vector<double>> Ls { get; private set; }
public List<Vector<double>> Ns { get; private set; }
public double Wi { get; private set; }
public List<double> Ui { get; private set; }
public List<double> Li { get; private set; }
public List<double> Ni { get; private set; }
#endregion
private NetworkModel(int startNode, int targetNode)
{
StartNode = startNode;
TargetNode = targetNode;
Lambda = new List<Vector<double>>();
Mu = new List<Vector<double>>();
Lambda0 = new Vector<double>();
InputProbability = new List<Vector<double>>();
E = new List<Vector<double>>();
LambdaBar = new List<Vector<double>>();
Ro = new List<Vector<double>>();
RoBar = new List<Vector<double>>();
RoTotal = new Vector<double>();
AveragePaths = 0;
Ws = new Vector<double>();
Us = new List<Vector<double>>();
Ls = new List<Vector<double>>();
Ns = new List<Vector<double>>();
Ui = new List<double>();
Li = new List<double>();
Ni = new List<double>();
}
public NetworkModel(String path, int startNode, int targetNode) : this(startNode, targetNode)
{
ParseConfig(path);
ComputeParameters();
ComputeStationaryPTC();
ComputeIntegratedPTC();
}
public Matrix<double> GetRoutingMatrix(int streamIndex)
{
if (streamIndex > StreamsCount)
throw new ArgumentException();
var streamRoutingMatrix = RoutingMatrix.Clone();
streamRoutingMatrix.InsertRow(0, InputProbability[streamIndex]);
return streamRoutingMatrix;
}
private void ComputeParameters()
{
Lambda.ForEach(lambdas => Lambda0.AddElement(lambdas.Sum()));
RoTotal = new Vector<double>(NodesCount);
for (int stream = 0; stream < StreamsCount; stream++)
{
// input intensity
InputProbability.Add(Lambda[stream].Clone().InsertElement(0, 0).Divide(Lambda0[stream]));
// E
E.Add(GaussMethod.Solve(GetExtendedMatrix(stream)));
// lambda'
LambdaBar.Add(E[stream].Multiply(Lambda0[stream]));
// ro' & ro total
RoBar.Add(LambdaBar[stream].DivideElementWise(Mu[stream]));
RoTotal = RoTotal.AddElementWise(RoBar.Last());
if(RoBar[stream].Any(roBar => roBar > 1))
throw new ArgumentOutOfRangeException(string.Format("RoBar, stream {0}", stream), "Some Ro' is greater than zero.");
}
if (RoTotal.Any(roTotal => roTotal > 1))
throw new ArgumentOutOfRangeException("RoTotal", "Some RoTotal is greater than zero.");
FindPaths();
}
public void FindPaths()
{
var matrix = RoutingMatrix.Clone().RemoveColumn(0);
var pathsCount = 0;
var pairsCount = 0;
for (int startNode = 0; startNode < matrix.RowsCount; startNode++)
for (int targetNode = 0; targetNode < matrix.RowsCount; targetNode++)
if (startNode != targetNode)
{
var paths = GraphHelper.GetPathsBetween(matrix.Clone(), startNode, targetNode);
if (paths.Count == 0)
continue;
if(startNode == StartNode && targetNode == TargetNode)
Paths = paths;
pathsCount += paths.Count();
pairsCount++;
if (MinPath == null || paths.Min().Length < MinPath.Length)
MinPath = paths.Min();
if (MaxPath == null || paths.Max().Length > MaxPath.Length)
MaxPath = paths.Max();
}
Paths.Sort();
AveragePaths = (double)pathsCount / pairsCount;
}
private Matrix<double> GetExtendedMatrix(int streamIndex)
{
var matrix = GetRoutingMatrix(streamIndex);
matrix.Transpose();
matrix.RemoveRow(0);
matrix.AddColumn(matrix.GetColumn(0).Negate());
matrix.RemoveColumn(0);
matrix.ReplaceDiagonalElements(-1);
return matrix;
}
#region COMPUTE PROBABILITY-TIME CHARACTERISTICS
private void ComputeStationaryPTC()
{
for (int i = 0; i < NodesCount; i++)
{
double sum = 0.0;
for (int stream = 0; stream < StreamsCount; stream++)
sum += RoBar[stream][i] / Mu[stream][i];
Ws.AddElement(sum / (1 - RoTotal[i]));
}
for (int stream = 0; stream < StreamsCount; stream++)
{
Us.Add( Ws.AddElementWise(Mu[stream].Pow( -1 )) );
Ls.Add( LambdaBar[stream].MultiplyElementWise( Ws ) );
Ns.Add( LambdaBar[stream].MultiplyElementWise( Us[stream]) );
}
}
private void ComputeIntegratedPTC()
{
ComputeTransitionProbabilities();
Wi = ComputeIntegralChar(Ws);
for (int stream = 0; stream < StreamsCount; stream++)
{
Ui.Add(ComputeIntegralChar(Us[stream]));
Li.Add(ComputeIntegralChar(Ls[stream]));
Ni.Add(ComputeIntegralChar(Ns[stream]));
}
}
private double ComputeIntegralChar(Vector<double> staticChar)
{
var integralChar = staticChar[StartNode] + staticChar[TargetNode];
for (int i = 0; i < Paths.Count(); i++)
{
var temp = 0.0;
for (int j = 1; j < Paths.ElementAt(i).Count() - 1; j++)
temp += staticChar[j];
integralChar += TransitionProbabilities[i] * temp;
}
return integralChar;
}
private void ComputeTransitionProbabilities()
{
var matrix = RoutingMatrix.Clone().RemoveColumn(0);
var pathsProbabilities =
Paths.Select(path =>
path.Where((item, index) => index < path.Length - 1).Select((item, index) => new {item, index})
.Aggregate(1.0, (accumulate, anon) => accumulate *= matrix[anon.item, path[anon.index + 1]]));
var s = pathsProbabilities.Sum();
TransitionProbabilities = pathsProbabilities.Select(prob => prob / s).ToList();
}
#endregion
#region COMPUTE PROBABILITY DENSITY
public IEnumerable<double> ComputeDensity(Vector<int> path, int stream, IEnumerable<double> t)
{
for (int i = 0; i < t.Count(); i++)
{
var result = 0.0;
foreach (var node in path)
result += ComputeHi(path, node, stream) *
(Mu[stream][node] - LambdaBar[stream][node]) *
Math.Pow(Math.E, -(Mu[stream][node] - LambdaBar[stream][node]) * t.ElementAt(i));
yield return result;
}
}
private double ComputeHi(Vector<int> path, int i, int stream)
{
var Hi = 1.0;
foreach (var node in path)
if (node != i)
Hi *= (Mu[stream][node] - LambdaBar[stream][node]) /
(Mu[stream][node] - Mu[stream][i] - LambdaBar[stream][node] + LambdaBar[stream][i]);
return Hi;
}
#endregion
#region PARSE XML
private void ParseConfig(String path)
{
var root = XDocument.Load(path).Root;
Name = root.Attribute("Name").Value;
ParseRoutingMatrix(root);
ParseNodes(root);
}
// TODO: don't touch
private void ParseRoutingMatrix(XContainer root)
{
var rows = GetElements(root, "Row").Skip(1).Select(row => row.Value).ToList();
NodesCount = rows.Count;
for (int i = 0; i < rows.Count(); i++)
{
var elements = rows[i].Split(';').Select(element => element.Trim()).ToList();
var dashesCount = elements.Count(element => element.Contains("-"));
var value = 0.0;
if(dashesCount != 0)
{
if (dashesCount == elements.Count)
value = 1 / dashesCount;
else
value = (1 - elements.Where(element => !element.Contains("-")).Sum(prob => double.Parse(prob)))
/ dashesCount;
}
var row = elements.Select(element => element.Contains("-") ?
value :
double.Parse(element));
if (i == 0)
RoutingMatrix = new Matrix<double>(new[] { row });
else
RoutingMatrix.AddRow(row);
}
var wrongRowsIndeces = RoutingMatrix.Select((row, index) => new {row, index})
.Where(anon => !((float)anon.row.Sum()).Equals(1.0f))
.Aggregate(string.Empty,
(accumulate, anon) => string.Format("{0} ,", anon.index));
if(wrongRowsIndeces != string.Empty)
throw new ArgumentOutOfRangeException(String.Format("RoutingMatrix, rows {0}", wrongRowsIndeces),
"The sum of the row must be equal to 1");
}
private void ParseNodes(XContainer root)
{
var streamElements = GetElements(root, "Stream");
StreamsCount = streamElements.Count == 0 ? 1:
streamElements.Max(element => int.Parse(element.Attribute("Index").Value)) + 1;
for (int stream = 0; stream < StreamsCount; stream++)
{
Mu.Add(new Vector<double>(
ParseMu( StreamsCount == 1? GetElement(root, "Mu") : GetElements(root, "Mu")
.Single(element => GetAttributeValue<int>(element.Parent, "Index") == stream))));
Lambda.Add(new Vector<double>(
ParseLambda( StreamsCount == 1 ? GetElement(root, "Lambda") : GetElements(root, "Lambda")
.Single(element => GetAttributeValue<int>(element.Parent, "Index") == stream), stream)));
Ro.Add(Lambda.Last().DivideElementWise(Mu.Last()));
}
}
private static Random random = new Random();
private IEnumerable<double> ParseLambda(XElement element, int stream)
{
return element.Value.ToLower().Contains("rand") ?
Enumerable.Range(0, NodesCount).Select(index => (double)random.Next(1, (int)Math.Floor(Mu[stream][index]))) :
element.Value.Contains(";") ?
element.Value.Split(';').Select(lambda => double.Parse(lambda.Trim())) :
element.Value.Contains("%") ? Mu[stream].Multiply( double.Parse( element.Value.Trim().TrimEnd(new[] { '%' }) ) / 100 ) :
Enumerable.Repeat(double.Parse(element.Value), NodesCount);
}
private IEnumerable<double> ParseMu(XElement element)
{
var ethernetElements = GetElements(element, "Ethernet");
return ethernetElements.Count == 1 ?
Enumerable.Repeat(ParseEthernet(ethernetElements.First()), NodesCount) :
ethernetElements.Select(ethernet => ParseEthernet(ethernet));
}
private double ParseEthernet(XElement element)
{
var ethernetType = (ProtocolHelper.EthernetType)Enum.Parse(typeof(ProtocolHelper.EthernetType),
element.Attribute("Type").Value);
int frameLength;
try
{
frameLength = int.Parse(element.Attribute("FrameLength").Value);
}
catch (FormatException)
{
frameLength = (int)Enum.Parse(typeof(ProtocolHelper.FrameLength), element.Attribute("FrameLength").Value);
}
return ProtocolHelper.GetCapacity(ethernetType, frameLength);
}
private List<XElement> GetElements(XContainer element, String elementName)
{
return element.Descendants(elementName).ToList();
}
private XElement GetElement(XContainer element, string elementName)
{
return GetElements(element, elementName).SingleOrDefault();
}
private T GetElementValue<T>(XContainer element, string elementName)
{
return GetElement(element, elementName).Value.CastObject<T>();
}
private T GetAttributeValue<T>(XElement element, string attributeName)
{
return element.Attribute(attributeName).Value.CastObject<T>();
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace DjvuNet.Graphics
{
/// <summary>
/// Represents bitonal and gray scale images
/// </summary>
public class Bitmap : Map
{
#region Private Variables
/// <summary>end of the buffer </summary>
private int _maxRowOffset;
private Pixel[] _rampData;
#endregion Private Variables
#region Protected Variables
#endregion Protected Variables
#region Variables
private static readonly Object[] RampRefArray = new Object[256];
#endregion Variables
#region Private Properties
/// <summary>
/// Gets or sets Set the number of rows.
/// </summary>
private int Rows
{
set
{
if (value != ImageHeight)
{
ImageHeight = value;
_maxRowOffset = RowOffset(ImageHeight);
}
}
get { return ImageHeight; }
}
#endregion Private Properties
#region Public Properties
#region Grays
private int _grays;
/// <summary>
/// Gets or sets the depth of colors
/// </summary>
public int Grays
{
get { return _grays; }
set
{
if (Grays != value)
{
if ((value < 2) || (value > 256))
{
throw new ArgumentException("(Bitmap::set_grays) Illegal number of gray levels");
}
_grays = value;
_rampData = null;
}
}
}
#endregion Grays
#region Border
private int _border;
/// <summary>
/// Gets or sets the number of border pixels
/// </summary>
public int Border
{
get { return _border; }
set
{
if (Border != value)
{
_border = value;
_maxRowOffset = RowOffset(ImageHeight);
}
}
}
#endregion Border
public virtual Pixel[] Ramp
{
get
{
Pixel[] retval = _rampData;
if (retval == null)
{
int grays = this.Grays;
retval = (Pixel[])RampRefArray[grays];
if (retval == null)
{
retval = new Pixel[256];
retval[0] = Pixel.WhitePixel;
int color = 0xff0000;
int gmax = (grays > 1) ? (grays - 1) : 1;
int i = 1;
if (gmax > 1)
{
int delta = color / gmax;
do
{
color -= delta;
sbyte c = (sbyte)(color >> 16);
retval[i++] = new Pixel(c, c, c);
} while (i < gmax);
}
while (i < retval.Length)
{
retval[i++] = Pixel.BlackPixel;
}
RampRefArray[grays] = retval;
}
_rampData = retval;
}
return retval;
}
}
#region BytesPerRow
private int _bytesPerRow;
/// <summary>
/// Gets or sets the number of bytes per row
/// </summary>
public int BytesPerRow
{
get { return _bytesPerRow; }
private set
{
if (BytesPerRow != value)
{
_bytesPerRow = value;
_maxRowOffset = RowOffset(ImageHeight);
}
}
}
#endregion BytesPerRow
/// <summary>
/// Set the minimum border needed
/// </summary>
/// <param name="minimum">the minumum border needed
/// </param>
public virtual int MinimumBorder
{
set
{
if (Border < value)
{
if (Data != null)
{
Bitmap tmp = new Bitmap().Init(this, value);
BytesPerRow = tmp.GetRowSize();
Data = tmp.Data;
tmp.Data = null;
GC.Collect();
}
Border = value;
}
}
}
#endregion Public Properties
#region Constructors
static Bitmap()
{
{
for (int i = 0; i < RampRefArray.Length; )
{
RampRefArray[i++] = null;
}
}
}
/// <summary>
/// Creates a new Bitmap object.
/// </summary>
public Bitmap()
: base(1, 0, 0, 0, true)
{
IsRampNeeded = true;
}
#endregion Constructors
#region Public Methods
public Bitmap Duplicate()
{
return new Bitmap
{
BlueOffset = BlueOffset,
Border = Border,
Data = Data,
Grays = Grays,
GreenOffset = GreenOffset,
_maxRowOffset = _maxRowOffset,
BytesPerPixel = BytesPerPixel,
ImageWidth = ImageWidth,
IsRampNeeded = IsRampNeeded,
ImageHeight = ImageHeight,
Properties = Properties,
_rampData = _rampData,
RedOffset = RedOffset,
BytesPerRow = BytesPerRow
};
}
/// <summary> Query a pixel as boolean
///
/// </summary>
/// <param name="offset">position to query
///
/// </param>
/// <returns> true if zero
/// </returns>
public bool GetBooleanAt(int offset)
{
return (offset < Border) || (offset >= _maxRowOffset) || (Data[offset] == 0);
}
/// <summary> Set the pixel value.
///
/// </summary>
/// <param name="offset">position of the pixel to set
/// </param>
/// <param name="value">gray scale value to set
/// </param>
public void SetByteAt(int offset, int value)
{
if ((offset >= Border) || (offset < _maxRowOffset))
{
Data[offset] = (sbyte)value;
}
}
/// <summary> Query the pixel at a particular location
///
/// </summary>
/// <param name="offset">the pixel location
///
/// </param>
/// <returns> the gray scale value
/// </returns>
public unsafe int GetByteAt(int offset)
{
fixed (sbyte* dataLocation = Data)
{
return ((offset < Border) || (offset >= _maxRowOffset)) ? 0 : (0xff & dataLocation[offset]);
}
}
/// <summary> Insert another bitmap at the specified location. Note that both bitmaps
/// need to have the same number of grays.
///
/// </summary>
/// <param name="bm">bitmap to insert
/// </param>
/// <param name="xh">horizontal location to insert at
/// </param>
/// <param name="yh">vertical location to insert at
/// </param>
/// <param name="subsample">rate to subsample at
///
/// </param>
/// <returns> true if the blit intersected this bitmap
/// </returns>
public virtual bool Blit(Bitmap bm, int xh, int yh, int subsample)
{
int pidx = 0;
int qidx = 0;
if (subsample == 1)
{
return InsertMap(bm, xh, yh, true);
}
if ((xh >= (ImageWidth * subsample)) || (yh >= (ImageHeight * subsample)) || ((xh + bm.ImageWidth) < 0) ||
((yh + bm.ImageHeight) < 0))
{
return false;
}
if (bm.Data != null)
{
int dr = yh / subsample;
int dr1 = yh - (subsample * dr);
if (dr1 < 0)
{
dr--;
dr1 += subsample;
}
int zdc = xh / subsample;
int zdc1 = xh - (subsample * zdc);
if (zdc1 < 0)
{
zdc--;
zdc1 += subsample;
}
int sr = 0;
int idx = 0;
for (; sr < bm.ImageHeight; sr++)
{
if ((dr >= 0) && (dr < ImageHeight))
{
int dc = zdc;
int dc1 = zdc1;
qidx = bm.RowOffset(sr);
pidx = RowOffset(dr);
for (int sc = 0; sc < bm.ImageWidth; sc++)
{
if ((dc >= 0) && (dc < ImageWidth))
{
Data[pidx + dc] = (sbyte)(Data[pidx + dc] + bm.Data[qidx + sc]);
}
if (++dc1 >= subsample)
{
dc1 = 0;
dc++;
}
}
}
if (++dr1 >= subsample)
{
dr1 = 0;
dr++;
idx++;
}
}
}
return true;
}
/// <summary> Query the start offset of a row.
///
/// </summary>
/// <param name="row">the row to query
///
/// </param>
/// <returns> the offset to the pixel data
/// </returns>
public override int RowOffset(int row)
{
return (row * BytesPerRow) + Border;
}
/// <summary> Query the number of bytes per row.
///
/// </summary>
/// <returns> bytes per row
/// </returns>
public override int GetRowSize()
{
return BytesPerRow;
}
/// <summary> Set the value of all pixels.
///
/// </summary>
/// <param name="value">gray scale value to assign to all pixels
/// </param>
public virtual void Fill(short value_Renamed)
{
int idx = 0;
sbyte v = (sbyte)value_Renamed;
for (int y = 0; y < ImageHeight; y++)
{
idx = RowOffset(y);
for (int x = 0; x < ImageWidth; x++)
{
Data[idx + x] = v;
}
}
}
/// <summary> Insert the reference map at the specified location.
///
/// </summary>
/// <param name="ref">map to insert
/// </param>
/// <param name="dx">horizontal position to insert at
/// </param>
/// <param name="dy">vertical position to insert at
/// </param>
public override void Fill(Map ref_Renamed, int dx, int dy)
{
InsertMap((Bitmap)ref_Renamed, dx, dy, false);
}
/// <summary> Insert the reference map at the specified location.
///
/// </summary>
/// <param name="bit">map to insert
/// </param>
/// <param name="dx">horizontal position to insert at
/// </param>
/// <param name="dy">vertical position to insert at
/// </param>
/// <param name="doBlit">true if the gray scale values should be added
///
/// </param>
/// <returns> true if pixels are inserted
/// </returns>
public unsafe virtual bool InsertMap(Bitmap bit, int dx, int dy, bool doBlit)
{
int x0 = (dx > 0) ? dx : 0;
int y0 = (dy > 0) ? dy : 0;
int x1 = (dx < 0) ? (-dx) : 0;
int y1 = (dy < 0) ? (-dy) : 0;
int w0 = ImageWidth - x0;
int w1 = bit.ImageWidth - x1;
int w = (w0 < w1) ? w0 : w1;
int h0 = ImageHeight - y0;
int h1 = bit.ImageHeight - y1;
int h = (h0 < h1) ? h0 : h1;
if ((w > 0) && (h > 0))
{
sbyte gmax = (sbyte)(Grays - 1);
do
{
int offset = RowOffset(y0++) + x0;
int refOffset = bit.RowOffset(y1++) + x1;
int i = w;
if (doBlit)
{
fixed (sbyte* dataLocation = Data, bitDataLocation = bit.Data)
{
// This is not really correct. We should reduce the original level by the
// amount of the new level. But since we are normally dealing with non-overlapping
// or bitonal blits it really doesn't matter.
do
{
int g = dataLocation[offset] + bitDataLocation[refOffset++];
dataLocation[offset++] = (g < Grays) ? (sbyte)g : gmax;
} while (--i > 0);
}
//// This is not really correct. We should reduce the original level by the
//// amount of the new level. But since we are normally dealing with non-overlapping
//// or bitonal blits it really doesn't matter.
//do
//{
// int g = Data[offset] + bit.Data[refOffset++];
// Data[offset++] = (g < Grays) ? (sbyte)g : gmax;
//} while (--i > 0);
}
else
{
fixed (sbyte* dataLocation = Data, bitDataLocation = bit.Data)
{
do
{
dataLocation[offset++] = bitDataLocation[refOffset++];
} while (--i > 0);
}
//do
//{
// Data[offset++] = bit.Data[refOffset++];
//} while (--i > 0);
}
} while (--h > 0);
return true;
}
return false;
}
/// <summary> Initialize this image with the specified values.
///
/// </summary>
/// <param name="arows">number of rows
/// </param>
/// <param name="acolumns">number of columns
/// </param>
/// <param name="aborder">width of the border
///
/// </param>
/// <returns> the initialized image map
/// </returns>
public virtual Bitmap Init(int arows, int acolumns, int aborder)
{
Data = null;
Grays = 2;
Rows = arows;
ImageWidth = acolumns;
Border = aborder;
BytesPerRow = (ImageWidth + Border);
int npixels = RowOffset(ImageHeight);
if (npixels > 0)
{
Data = new sbyte[npixels];
//for (int i = 0; i < npixels; i++)
//{
// Data[i] = 0;
//}
}
return this;
}
/// <summary> Initialize this map by copying a reference map
///
/// </summary>
/// <param name="ref">map to copy
///
/// </param>
/// <returns> the initialized map
/// </returns>
public Bitmap Init(Bitmap ref_Renamed)
{
return Init(ref_Renamed, 0);
}
/// <summary>
/// Initialize this map by copying a reference map
/// </summary>
/// <param name="ref">map to copy
/// </param>
/// <param name="aborder">number of border pixels
///
/// </param>
/// <returns> the initialized map
/// </returns>
public virtual Bitmap Init(Bitmap ref_Renamed, int aborder)
{
if (this != ref_Renamed)
{
Init(ref_Renamed.ImageHeight, ref_Renamed.ImageWidth, aborder);
Grays = ref_Renamed.Grays;
for (int i = 0; i < ImageHeight; i++)
{
for (int j = ImageWidth, k = RowOffset(i), kr = ref_Renamed.RowOffset(i); j-- > 0; )
{
Data[k++] = ref_Renamed.Data[kr++];
}
}
}
else if (aborder > Border)
{
MinimumBorder = aborder;
}
return this;
}
/// <summary>
/// Initialize this map by copying a reference map
/// </summary>
/// <param name="ref">map to copy
/// </param>
/// <param name="rect">area to copy
/// </param>
/// <param name="border">number of border pixels
///
/// </param>
/// <returns> the initialized map
/// </returns>
public virtual Bitmap Init(Bitmap ref_Renamed, Rectangle rect, int border)
{
if (this == ref_Renamed)
{
Bitmap tmp = new Bitmap();
tmp.Grays = (Grays);
tmp.Border = ((short)border);
tmp.BytesPerRow = (BytesPerRow);
tmp.ImageWidth = ImageWidth;
tmp.Rows = ImageHeight;
tmp.Data = Data;
Data = null;
Init(tmp, rect, border);
}
else
{
Init(rect.Height, rect.Width, border);
Grays = ref_Renamed.Grays;
Rectangle rect2 = new Rectangle(0, 0, ref_Renamed.ImageWidth, ref_Renamed.ImageHeight);
rect2.Intersect(rect2, rect);
rect2.Translate(-rect.Right, -rect.Bottom);
if (!rect2.Empty)
{
int dstIdx = 0;
int srcIdx = 0;
for (int y = rect2.Bottom; y < rect2.Top; y++)
{
dstIdx = RowOffset(y);
srcIdx = ref_Renamed.RowOffset(y + rect.Bottom);
for (int x = rect2.Right; x < rect2.Top; x++)
{
Data[dstIdx + x] = ref_Renamed.Data[srcIdx + x];
}
}
}
}
return this;
}
/// <summary>
/// Shift the origin of the image by coping the pixel data.
/// </summary>
/// <param name="dx">amount to shift the origin of the x-axis
/// </param>
/// <param name="dy">amount to shift the origin of the y-axis
/// </param>
/// <param name="retval">the image to copy the data into
///
/// </param>
/// <returns> the translated image
/// </returns>
public override Map Translate(int dx, int dy, Map retval)
{
if (!(retval is Bitmap) || (retval.ImageWidth != ImageWidth) || (retval.ImageHeight != ImageHeight))
{
Bitmap r = new Bitmap().Init(ImageHeight, ImageWidth, 0);
if ((Grays >= 2) && (Grays <= 256))
{
r.Grays = (Grays);
}
retval = r;
}
retval.Fill(this, -dx, -dy);
return retval;
}
/// <summary>
/// Convert the pixel to 24 bit color.
/// </summary>
public override Pixel PixelRamp(PixelReference ref_Renamed)
{
return Ramp[ref_Renamed.Blue];
}
/// <summary>
/// Find the bounding box for non-white pixels.
/// </summary>
/// <returns> bounding rectangle
/// </returns>
public virtual Rectangle ComputeBoundingBox()
{
lock (this)
{
int w = ImageWidth;
int h = ImageHeight;
int s = GetRowSize();
int xmin, xmax, ymin, ymax;
for (xmax = w - 1; xmax >= 0; xmax--)
{
int p = RowOffset(0) + xmax;
int pe = p + (s * h);
while ((p < pe) && GetBooleanAt(p))
{
p += s;
}
if (p < pe)
{
break;
}
}
for (ymax = h - 1; ymax >= 0; ymax--)
{
int p = RowOffset(ymax);
int pe = p + w;
while ((p < pe) && GetBooleanAt(p))
{
++p;
}
if (p < pe)
{
break;
}
}
for (xmin = 0; xmin <= xmax; xmin++)
{
int p = RowOffset(0) + xmin;
int pe = p + (s * h);
while ((p < pe) && GetBooleanAt(p))
{
p += s;
}
if (p < pe)
{
break;
}
}
for (ymin = 0; ymin <= ymax; ymin++)
{
int p = RowOffset(ymin);
int pe = p + w;
while ((p < pe) && GetBooleanAt(p))
{
++p;
}
if (p < pe)
{
break;
}
}
Rectangle retval = new Rectangle();
retval.Right = xmin;
retval.Left = xmax;
retval.Bottom = ymin;
retval.Top = ymax;
return retval;
}
}
#endregion Public Methods
#region Private Methods
#endregion Private Methods
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Reflection;
using Newtonsoft.Json.Utilities;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Maps a JSON property to a .NET member or constructor parameter.
/// </summary>
public class JsonProperty
{
internal Required? _required;
internal bool _hasExplicitDefaultValue;
private object? _defaultValue;
private bool _hasGeneratedDefaultValue;
private string? _propertyName;
internal bool _skipPropertyNameEscape;
private Type? _propertyType;
// use to cache contract during deserialization
internal JsonContract? PropertyContract { get; set; }
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
/// <value>The name of the property.</value>
public string? PropertyName
{
get => _propertyName;
set
{
_propertyName = value;
_skipPropertyNameEscape = !JavaScriptUtils.ShouldEscapeJavaScriptString(_propertyName, JavaScriptUtils.HtmlCharEscapeFlags);
}
}
/// <summary>
/// Gets or sets the type that declared this property.
/// </summary>
/// <value>The type that declared this property.</value>
public Type? DeclaringType { get; set; }
/// <summary>
/// Gets or sets the order of serialization of a member.
/// </summary>
/// <value>The numeric order of serialization.</value>
public int? Order { get; set; }
/// <summary>
/// Gets or sets the name of the underlying member or parameter.
/// </summary>
/// <value>The name of the underlying member or parameter.</value>
public string? UnderlyingName { get; set; }
/// <summary>
/// Gets the <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.
/// </summary>
/// <value>The <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.</value>
public IValueProvider? ValueProvider { get; set; }
/// <summary>
/// Gets or sets the <see cref="IAttributeProvider"/> for this property.
/// </summary>
/// <value>The <see cref="IAttributeProvider"/> for this property.</value>
public IAttributeProvider? AttributeProvider { get; set; }
/// <summary>
/// Gets or sets the type of the property.
/// </summary>
/// <value>The type of the property.</value>
public Type? PropertyType
{
get => _propertyType;
set
{
if (_propertyType != value)
{
_propertyType = value;
_hasGeneratedDefaultValue = false;
}
}
}
/// <summary>
/// Gets or sets the <see cref="JsonConverter" /> for the property.
/// If set this converter takes precedence over the contract converter for the property type.
/// </summary>
/// <value>The converter.</value>
public JsonConverter? Converter { get; set; }
/// <summary>
/// Gets or sets the member converter.
/// </summary>
/// <value>The member converter.</value>
[Obsolete("MemberConverter is obsolete. Use Converter instead.")]
public JsonConverter? MemberConverter
{
get => Converter;
set => Converter = value;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is ignored.
/// </summary>
/// <value><c>true</c> if ignored; otherwise, <c>false</c>.</value>
public bool Ignored { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is readable.
/// </summary>
/// <value><c>true</c> if readable; otherwise, <c>false</c>.</value>
public bool Readable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is writable.
/// </summary>
/// <value><c>true</c> if writable; otherwise, <c>false</c>.</value>
public bool Writable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> has a member attribute.
/// </summary>
/// <value><c>true</c> if has a member attribute; otherwise, <c>false</c>.</value>
public bool HasMemberAttribute { get; set; }
/// <summary>
/// Gets the default value.
/// </summary>
/// <value>The default value.</value>
public object? DefaultValue
{
get
{
if (!_hasExplicitDefaultValue)
{
return null;
}
return _defaultValue;
}
set
{
_hasExplicitDefaultValue = true;
_defaultValue = value;
}
}
internal object? GetResolvedDefaultValue()
{
if (_propertyType == null)
{
return null;
}
if (!_hasExplicitDefaultValue && !_hasGeneratedDefaultValue)
{
_defaultValue = ReflectionUtils.GetDefaultValue(_propertyType);
_hasGeneratedDefaultValue = true;
}
return _defaultValue;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is required.
/// </summary>
/// <value>A value indicating whether this <see cref="JsonProperty"/> is required.</value>
public Required Required
{
get => _required ?? Required.Default;
set => _required = value;
}
/// <summary>
/// Gets a value indicating whether <see cref="Required"/> has a value specified.
/// </summary>
public bool IsRequiredSpecified => _required != null;
/// <summary>
/// Gets or sets a value indicating whether this property preserves object references.
/// </summary>
/// <value>
/// <c>true</c> if this instance is reference; otherwise, <c>false</c>.
/// </value>
public bool? IsReference { get; set; }
/// <summary>
/// Gets or sets the property null value handling.
/// </summary>
/// <value>The null value handling.</value>
public NullValueHandling? NullValueHandling { get; set; }
/// <summary>
/// Gets or sets the property default value handling.
/// </summary>
/// <value>The default value handling.</value>
public DefaultValueHandling? DefaultValueHandling { get; set; }
/// <summary>
/// Gets or sets the property reference loop handling.
/// </summary>
/// <value>The reference loop handling.</value>
public ReferenceLoopHandling? ReferenceLoopHandling { get; set; }
/// <summary>
/// Gets or sets the property object creation handling.
/// </summary>
/// <value>The object creation handling.</value>
public ObjectCreationHandling? ObjectCreationHandling { get; set; }
/// <summary>
/// Gets or sets or sets the type name handling.
/// </summary>
/// <value>The type name handling.</value>
public TypeNameHandling? TypeNameHandling { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be serialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be serialized.</value>
public Predicate<object>? ShouldSerialize { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be deserialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be deserialized.</value>
public Predicate<object>? ShouldDeserialize { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be serialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be serialized.</value>
public Predicate<object>? GetIsSpecified { get; set; }
/// <summary>
/// Gets or sets an action used to set whether the property has been deserialized.
/// </summary>
/// <value>An action used to set whether the property has been deserialized.</value>
public Action<object, object?>? SetIsSpecified { get; set; }
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public override string ToString()
{
return PropertyName ?? string.Empty;
}
/// <summary>
/// Gets or sets the converter used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items converter.</value>
public JsonConverter? ItemConverter { get; set; }
/// <summary>
/// Gets or sets whether this property's collection items are serialized as a reference.
/// </summary>
/// <value>Whether this property's collection items are serialized as a reference.</value>
public bool? ItemIsReference { get; set; }
/// <summary>
/// Gets or sets the type name handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items type name handling.</value>
public TypeNameHandling? ItemTypeNameHandling { get; set; }
/// <summary>
/// Gets or sets the reference loop handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items reference loop handling.</value>
public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; }
internal void WritePropertyName(JsonWriter writer)
{
string? propertyName = PropertyName;
MiscellaneousUtils.Assert(propertyName != null);
if (_skipPropertyNameEscape)
{
writer.WritePropertyName(propertyName, false);
}
else
{
writer.WritePropertyName(propertyName);
}
}
}
}
| |
//
// https://github.com/mythz/ServiceStack.Redis
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot ([email protected])
//
// Copyright 2013 ServiceStack.
//
// Licensed under the same terms of Redis and ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Linq;
using ServiceStack.DesignPatterns.Model;
namespace ServiceStack.Redis.Generic
{
public partial class RedisTypedClient<T>
{
const int FirstElement = 0;
const int LastElement = -1;
public IHasNamed<IRedisList<T>> Lists { get; set; }
internal class RedisClientLists
: IHasNamed<IRedisList<T>>
{
private readonly RedisTypedClient<T> client;
public RedisClientLists(RedisTypedClient<T> client)
{
this.client = client;
}
public IRedisList<T> this[string listId]
{
get
{
return new RedisClientList<T>(client, listId);
}
set
{
var list = this[listId];
list.Clear();
list.CopyTo(value.ToArray(), 0);
}
}
}
private List<T> CreateList(byte[][] multiDataList)
{
if (multiDataList == null) return new List<T>();
var results = new List<T>();
foreach (var multiData in multiDataList)
{
results.Add(DeserializeValue(multiData));
}
return results;
}
public List<T> GetAllItemsFromList(IRedisList<T> fromList)
{
var multiDataList = client.LRange(fromList.Id, FirstElement, LastElement);
return CreateList(multiDataList);
}
public List<T> GetRangeFromList(IRedisList<T> fromList, int startingFrom, int endingAt)
{
var multiDataList = client.LRange(fromList.Id, startingFrom, endingAt);
return CreateList(multiDataList);
}
public List<T> SortList(IRedisList<T> fromList, int startingFrom, int endingAt)
{
var sortOptions = new SortOptions { Skip = startingFrom, Take = endingAt, };
var multiDataList = client.Sort(fromList.Id, sortOptions);
return CreateList(multiDataList);
}
public void AddItemToList(IRedisList<T> fromList, T value)
{
client.RPush(fromList.Id, SerializeValue(value));
}
//TODO: replace it with a pipeline implementation ala AddRangeToSet
public void AddRangeToList(IRedisList<T> fromList, IEnumerable<T> values)
{
foreach (var value in values)
{
AddItemToList(fromList, value);
}
}
public void PrependItemToList(IRedisList<T> fromList, T value)
{
client.LPush(fromList.Id, SerializeValue(value));
}
public T RemoveStartFromList(IRedisList<T> fromList)
{
return DeserializeValue(client.LPop(fromList.Id));
}
public T BlockingRemoveStartFromList(IRedisList<T> fromList, TimeSpan? timeOut)
{
var unblockingKeyAndValue = client.BLPop(fromList.Id, (int)timeOut.GetValueOrDefault().TotalSeconds);
return unblockingKeyAndValue.Length == 0
? default(T)
: DeserializeValue(unblockingKeyAndValue[1]);
}
public T RemoveEndFromList(IRedisList<T> fromList)
{
return DeserializeValue(client.RPop(fromList.Id));
}
public void RemoveAllFromList(IRedisList<T> fromList)
{
client.LTrim(fromList.Id, int.MaxValue, FirstElement);
}
public void TrimList(IRedisList<T> fromList, int keepStartingFrom, int keepEndingAt)
{
client.LTrim(fromList.Id, keepStartingFrom, keepEndingAt);
}
public long RemoveItemFromList(IRedisList<T> fromList, T value)
{
const int removeAll = 0;
return client.LRem(fromList.Id, removeAll, SerializeValue(value));
}
public long RemoveItemFromList(IRedisList<T> fromList, T value, int noOfMatches)
{
return client.LRem(fromList.Id, noOfMatches, SerializeValue(value));
}
public long GetListCount(IRedisList<T> fromList)
{
return client.LLen(fromList.Id);
}
public T GetItemFromList(IRedisList<T> fromList, int listIndex)
{
return DeserializeValue(client.LIndex(fromList.Id, listIndex));
}
public void SetItemInList(IRedisList<T> toList, int listIndex, T value)
{
client.LSet(toList.Id, listIndex, SerializeValue(value));
}
public void InsertBeforeItemInList(IRedisList<T> toList, T pivot, T value)
{
client.LInsert(toList.Id, insertBefore: true, pivot: SerializeValue(pivot), value: SerializeValue(value));
}
public void InsertAfterItemInList(IRedisList<T> toList, T pivot, T value)
{
client.LInsert(toList.Id, insertBefore: false, pivot: SerializeValue(pivot), value: SerializeValue(value));
}
public void EnqueueItemOnList(IRedisList<T> fromList, T item)
{
client.LPush(fromList.Id, SerializeValue(item));
}
public T DequeueItemFromList(IRedisList<T> fromList)
{
return DeserializeValue(client.RPop(fromList.Id));
}
public T BlockingDequeueItemFromList(IRedisList<T> fromList, TimeSpan? timeOut)
{
var unblockingKeyAndValue = client.BRPop(fromList.Id, (int)timeOut.GetValueOrDefault().TotalSeconds);
return unblockingKeyAndValue.Length == 0
? default(T)
: DeserializeValue(unblockingKeyAndValue[1]);
}
public void PushItemToList(IRedisList<T> fromList, T item)
{
client.RPush(fromList.Id, SerializeValue(item));
}
public T PopItemFromList(IRedisList<T> fromList)
{
return DeserializeValue(client.RPop(fromList.Id));
}
public T BlockingPopItemFromList(IRedisList<T> fromList, TimeSpan? timeOut)
{
var unblockingKeyAndValue = client.BRPop(fromList.Id, (int)timeOut.GetValueOrDefault().TotalSeconds);
return unblockingKeyAndValue.Length == 0
? default(T)
: DeserializeValue(unblockingKeyAndValue[1]);
}
public T PopAndPushItemBetweenLists(IRedisList<T> fromList, IRedisList<T> toList)
{
return DeserializeValue(client.RPopLPush(fromList.Id, toList.Id));
}
public T BlockingPopAndPushItemBetweenLists(IRedisList<T> fromList, IRedisList<T> toList, TimeSpan? timeOut)
{
return DeserializeValue(client.BRPopLPush(fromList.Id, toList.Id, (int)timeOut.GetValueOrDefault().TotalSeconds));
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
namespace Microsoft.Azure.Management.WebSites
{
/// <summary>
/// In addition to standard HTTP status codes, the Windows Azure Web Sites
/// Management REST API returns extended error codes and error messages.
/// The extended codes do not replace the standard HTTP status codes, but
/// provide additional, actionable information that can be used in
/// conjunction with the standard HTTP status codes. For example, an HTTP
/// 404 error can occur for numerous reasons, so having the additional
/// information in the extended message can assist with problem
/// resolution. (For more information on the standard HTTP codes returned
/// by the REST API, see Service Management Status and Error Codes.) (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn166968.aspx for
/// more information)
/// </summary>
public static partial class WebSiteExtendedErrorCodes
{
/// <summary>
/// Access is denied.
/// </summary>
public const string AccessDenied = "01001";
/// <summary>
/// Command resource object is not present in the request body.
/// </summary>
public const string CommandResourceNotPresent = "01002";
/// <summary>
/// Invalid name {0}.
/// </summary>
public const string InvalidName = "01003";
/// <summary>
/// Cannot understand command verb {0}.
/// </summary>
public const string UnknownCommandVerb = "01004";
/// <summary>
/// The service is currently in read only mode.
/// </summary>
public const string IsInReadOnlyMode = "01005";
/// <summary>
/// The {0} parameter is not specified.
/// </summary>
public const string ParameterIsNotSpecified = "01006";
/// <summary>
/// Parameter {0} has invalid value.
/// </summary>
public const string InvalidParameterValue = "01007";
/// <summary>
/// {0} object is not present in the request body.
/// </summary>
public const string InvalidRequest = "01008";
/// <summary>
/// The from value in the query string is bigger than or equal to the
/// to value.
/// </summary>
public const string IncorrectDateTimeRange = "01009";
/// <summary>
/// Required parameter {0} is missing.
/// </summary>
public const string RequiredParameterMissing = "01010";
/// <summary>
/// Name of the web quota cannot change.
/// </summary>
public const string ResourceNameCannotChange = "01011";
/// <summary>
/// The value of the query string parameter cannot be converted to
/// Boolean.
/// </summary>
public const string FailedToConvertParameterValue = "01012";
/// <summary>
/// Parameter with name {0} already exists in the request.
/// </summary>
public const string ParameterNameAlreadyExists = "01013";
/// <summary>
/// Parameter name cannot be empty.
/// </summary>
public const string ParameterNameIsEmpty = "01014";
/// <summary>
/// Not ready.
/// </summary>
public const string NotReady = "01015";
/// <summary>
/// Ready.
/// </summary>
public const string Ready = "01016";
/// <summary>
/// Update is not allowed for the {0} field.
/// </summary>
public const string UpdateForFieldNotAllowed = "01017";
/// <summary>
/// Web Service does not support Command {0}. Only supported command(s)
/// is {1}.
/// </summary>
public const string NotSupportedCommand = "01018";
/// <summary>
/// Invalid data ({0}).
/// </summary>
public const string InvalidData = "01019";
/// <summary>
/// There was a conflict. {0}
/// </summary>
public const string GenericConflict = "01020";
/// <summary>
/// Internal server error occurred. {0}
/// </summary>
public const string InternalServerError = "01021";
/// <summary>
/// Number of sites exceeds the maximum allowed.
/// </summary>
public const string NumberOfSitesLimit = "03001";
/// <summary>
/// NumberOfWorkers exceeds the maximum allowed.
/// </summary>
public const string NumberOfWorkersLimit = "03002";
/// <summary>
/// There is not enough space on the disk.
/// </summary>
public const string NoStorageVolumeAvailable = "03003";
/// <summary>
/// WebSpace with name {0} already exists for subscription {1}.
/// </summary>
public const string WebSpaceAlreadyExists = "03004";
/// <summary>
/// Cannot find webspace {0} for subscription {1}
/// </summary>
public const string WebSpaceNotFound = "03005";
/// <summary>
/// Web space contains resources.
/// </summary>
public const string WebSpaceContainsResources = "03006";
/// <summary>
/// The file storage capacity exceeds the limit.
/// </summary>
public const string FileStorageLimit = "03007";
/// <summary>
/// Failed to delete web space {0}: {1}
/// </summary>
public const string WebSpaceDeleteError = "03008";
/// <summary>
/// Not enough available Standard Instance servers to satisfy this
/// request.
/// </summary>
public const string NoWorkersAvailable = "03009";
/// <summary>
/// Failed to create web space {0} on storage volume {1}: {2}
/// </summary>
public const string WebSpaceCreateError = "03010";
/// <summary>
/// Directory already exists for site {0}.
/// </summary>
public const string DirectoryAlreadyExists = "04001";
/// <summary>
/// Failed to delete directory {0}.
/// </summary>
public const string DirectoryDeleteError = "04002";
/// <summary>
/// Invalid host name {0}.
/// </summary>
public const string InvalidHostName = "04003";
/// <summary>
/// NumberOfWorkers value must be more than zero.
/// </summary>
public const string InvalidNumberOfWorkers = "04004";
/// <summary>
/// Hostname '{0}' already exists.
/// </summary>
public const string HostNameAlreadyExists = "04005";
/// <summary>
/// No CNAME pointing from {0} to a site in a default DNS zone (or too
/// many).
/// </summary>
public const string InvalidCustomHostNameValidation = "04006";
/// <summary>
/// There are no hostnames which could be used for validation.
/// </summary>
public const string InvalidCustomHostNameValidationNoBaseHostName = "04007";
/// <summary>
/// Site with name {0} already exists.
/// </summary>
public const string SiteAlreadyExists = "04008";
/// <summary>
/// Cannot find site {0}.
/// </summary>
public const string SiteNotFound = "04009";
/// <summary>
/// The external URL "{0}" specified on request header "{1}" is invalid.
/// </summary>
public const string InvalidExternalUriHeader = "04010";
/// <summary>
/// Failed to delete file {0}.
/// </summary>
public const string FileDeleteError = "04011";
/// <summary>
/// Number of workers for this site exceeds the maximum allowed.
/// </summary>
public const string NumberOfWorkersPerSiteLimit = "04012";
/// <summary>
/// WebSiteManager.CreateWebSite: Creating Site using storageVolume {0}.
/// </summary>
public const string TraceWebSiteStorageVolume = "04013";
/// <summary>
/// Cannot delete repository with name {0}.
/// </summary>
public const string RepositoryDeleteError = "05001";
/// <summary>
/// Development site already exists in the repository for site {0}.
/// </summary>
public const string RepositoryDevSiteAlreadyExists = "05002";
/// <summary>
/// Development site does not exist in the repository for site {0}.
/// </summary>
public const string RepositoryDevSiteNotExist = "05003";
/// <summary>
/// Site {0} already has repository created for it.
/// </summary>
public const string RepositorySiteAlreadyExists = "05004";
/// <summary>
/// Repository does not exist for site {0}.
/// </summary>
public const string RepositorySiteNotExist = "05005";
/// <summary>
/// Failed to create a development site.
/// </summary>
public const string TraceFailedToCreateDevSite = "05006";
/// <summary>
/// User {0} has been rejected.
/// </summary>
public const string AuthenticatedFailed = "06001";
/// <summary>
/// User {0} has been successfully authenticated.
/// </summary>
public const string AuthenticatedPassed = "06002";
/// <summary>
/// User {0} has been rejected.
/// </summary>
public const string AuthorizationFailed = "06003";
/// <summary>
/// User {0} has been authorized.
/// </summary>
public const string AuthorizationPassed = "06004";
/// <summary>
/// Publishing credentials have to be trimmed from white characters.
/// </summary>
public const string PublishingCredentialsNotTrimmed = "06005";
/// <summary>
/// Publishing password cannot be empty.
/// </summary>
public const string PublishingPasswordIsEmpty = "06006";
/// <summary>
/// Publishing password must be specified.
/// </summary>
public const string PublishingPasswordNotSpecified = "06007";
/// <summary>
/// Publishing username {0} is already used. Specify a different
/// publishing username.
/// </summary>
public const string PublishingUserNameAlreadyExists = "06008";
/// <summary>
/// Publishing user name cannot be empty.
/// </summary>
public const string PublishingUserNameIsEmpty = "06009";
/// <summary>
/// An error occurred when adding the {0} entry: {1}
/// </summary>
public const string ErrorAdding = "51001";
/// <summary>
/// An error occurred when deleting the {0} entry: {1}
/// </summary>
public const string ErrorDeleting = "51002";
/// <summary>
/// An error occurred when updating the {0} entry: {1}
/// </summary>
public const string ErrorUpdating = "51003";
/// <summary>
/// Cannot find {0} with name {1}.
/// </summary>
public const string CannotFindEntity = "51004";
/// <summary>
/// Subscription with specified name already exists.
/// </summary>
public const string SubscriptionConflict = "52001";
/// <summary>
/// Subscripton Name cannot be null or empty.
/// </summary>
public const string SubscriptionNonEmpty = "52002";
/// <summary>
/// Subscription {0} not found.
/// </summary>
public const string SubscriptionNotFound = "52003";
/// <summary>
/// Subscription {0} is Suspended.
/// </summary>
public const string SubscriptionSuspended = "52004";
/// <summary>
/// Subscription contains WebSpaces.
/// </summary>
public const string NonEmptySubscription = "52005";
/// <summary>
/// WebSpace with specified name already exists.
/// </summary>
public const string WebSpaceConflict = "53001";
/// <summary>
/// WebSpace Name cannot be null or empty.
/// </summary>
public const string WebSpaceNonEmpty = "53002";
/// <summary>
/// WebSpace contains web sites.
/// </summary>
public const string NonEmptyWebSpace = "53003";
/// <summary>
/// An Error occurred when picking Stamp for WebSpace {0}.
/// </summary>
public const string ErrorPickingStamp = "53004";
/// <summary>
/// Web site with given name {0} already exists in the specified
/// Subscription and Webspace.
/// </summary>
public const string WebSiteConflict = "54001";
/// <summary>
/// WebSiteName cannot be null or empty.
/// </summary>
public const string WebSiteNonEmpty = "54002";
/// <summary>
/// Specified Host Name {0} is already taken by another site.
/// </summary>
public const string HostNameConflict = "54003";
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Irony.Parsing;
using YesSql;
namespace OrchardCore.Queries.Sql
{
public class SqlParser
{
private StringBuilder _builder;
private IDictionary<string, object> _parameters;
private ISqlDialect _dialect;
private string _tablePrefix;
private HashSet<string> _aliases;
private ParseTree _tree;
private static LanguageData language = new LanguageData(new SqlGrammar());
private Stack<FormattingModes> _modes;
private string _limit;
private string _offset;
private string _select;
private string _from;
private string _where;
private string _having;
private string _groupBy;
private string _orderBy;
private SqlParser(ParseTree tree, ISqlDialect dialect, string tablePrefix, IDictionary<string, object> parameters)
{
_tree = tree;
_dialect = dialect;
_tablePrefix = tablePrefix;
_parameters = parameters;
_builder = new StringBuilder(tree.SourceText.Length);
_modes = new Stack<FormattingModes>();
}
public static bool TryParse(string sql, ISqlDialect dialect, string tablePrefix, IDictionary<string, object> parameters, out string query, out IEnumerable<string> messages)
{
try
{
var tree = new Parser(language).Parse(sql);
if (tree.HasErrors())
{
query = null;
messages = tree
.ParserMessages
.Select(x => $"{x.Message} at line:{x.Location.Line}, col:{x.Location.Column}")
.ToArray();
return false;
}
var sqlParser = new SqlParser(tree, dialect, tablePrefix, parameters);
query = sqlParser.Evaluate();
messages = Array.Empty<string>();
return true;
}
catch (SqlParserException se)
{
query = null;
messages = new string[] { se.Message };
}
catch (Exception e)
{
query = null;
messages = new string[] { "Unexpected error: " + e.Message };
}
return false;
}
private string Evaluate()
{
PopulateAliases(_tree);
var statementList = _tree.Root;
var statementsBuilder = new StringBuilder();
foreach (var selectStatement in statementList.ChildNodes)
{
statementsBuilder.Append(EvaluateSelectStatement(selectStatement)).Append(';');
}
return statementsBuilder.ToString();
}
private void PopulateAliases(ParseTree tree)
{
// In order to determine if an Id is a table name or an alias, we
// analyze every Alias and store the value.
_aliases = new HashSet<string>();
for (var i = 0; i < tree.Tokens.Count; i++)
{
if (tree.Tokens[i].Terminal.Name == "AS")
{
_aliases.Add(tree.Tokens[i + 1].ValueString);
}
}
}
private string EvaluateSelectStatement(ParseTreeNode selectStatement)
{
_limit = null;
_offset = null;
_select = null;
_from = null;
_where = null;
_having = null;
_groupBy = null;
_orderBy = null;
var previousContent = _builder.Length > 0 ? _builder.ToString() : null;
_builder.Clear();
var sqlBuilder = _dialect.CreateBuilder(_tablePrefix);
EvaluateSelectRestriction(selectStatement.ChildNodes[1]);
EvaluateSelectorList(selectStatement.ChildNodes[2]);
sqlBuilder.Select();
sqlBuilder.Selector(_select);
EvaluateFromClause(selectStatement.ChildNodes[3]);
if (!String.IsNullOrEmpty(_from))
{
sqlBuilder.From(_from);
}
EvaluateWhereClause(selectStatement.ChildNodes[4]);
if (!String.IsNullOrEmpty(_where))
{
sqlBuilder.WhereAlso(_where);
}
EvaluateGroupClause(selectStatement.ChildNodes[5]);
if (!String.IsNullOrEmpty(_groupBy))
{
sqlBuilder.GroupBy(_groupBy);
}
EvaluateHavingClause(selectStatement.ChildNodes[6]);
if (!String.IsNullOrEmpty(_having))
{
sqlBuilder.Having(_having);
}
EvaluateOrderClause(selectStatement.ChildNodes[7]);
if (!String.IsNullOrEmpty(_orderBy))
{
sqlBuilder.OrderBy(_orderBy);
}
EvaluateLimitClause(selectStatement.ChildNodes[8]);
if (!String.IsNullOrEmpty(_limit))
{
sqlBuilder.Take(_limit);
}
EvaluateOffsetClause(selectStatement.ChildNodes[9]);
if (!String.IsNullOrEmpty(_offset))
{
sqlBuilder.Skip(_offset);
}
if (previousContent != null)
{
_builder.Clear();
_builder.Append(new StringBuilder(previousContent));
}
return sqlBuilder.ToSqlString();
}
private void EvaluateLimitClause(ParseTreeNode parseTreeNode)
{
if (parseTreeNode.ChildNodes.Count == 0)
{
return;
}
_builder.Clear();
// Evaluating so that the value can be transformed as a parameter
EvaluateExpression(parseTreeNode.ChildNodes[1]);
_limit = _builder.ToString();
}
private void EvaluateOffsetClause(ParseTreeNode parseTreeNode)
{
if (parseTreeNode.ChildNodes.Count == 0)
{
return;
}
_builder.Clear();
// Evaluating so that the value can be transformed as a parameter
EvaluateExpression(parseTreeNode.ChildNodes[1]);
_offset = _builder.ToString();
}
private void EvaluateOrderClause(ParseTreeNode parseTreeNode)
{
if (parseTreeNode.ChildNodes.Count == 0)
{
return;
}
_builder.Clear();
var idList = parseTreeNode.ChildNodes[2];
_modes.Push(FormattingModes.SelectClause);
for (var i = 0; i < idList.ChildNodes.Count; i++)
{
var id = idList.ChildNodes[i].ChildNodes[0];
if (i > 0)
{
_builder.Append(", ");
}
EvaluateId(id);
if (idList.ChildNodes[i].ChildNodes[1].ChildNodes.Count > 0)
{
_builder.Append(" ").Append(idList.ChildNodes[i].ChildNodes[1].ChildNodes[0].Term.Name);
}
}
_orderBy = _builder.ToString();
_modes.Pop();
}
private void EvaluateHavingClause(ParseTreeNode parseTreeNode)
{
if (parseTreeNode.ChildNodes.Count == 0)
{
return;
}
_builder.Clear();
_modes.Push(FormattingModes.SelectClause);
EvaluateExpression(parseTreeNode.ChildNodes[1]);
_having = _builder.ToString();
_modes.Pop();
}
private void EvaluateGroupClause(ParseTreeNode parseTreeNode)
{
if (parseTreeNode.ChildNodes.Count == 0)
{
return;
}
_builder.Clear();
var idList = parseTreeNode.ChildNodes[2];
_modes.Push(FormattingModes.SelectClause);
for (var i = 0; i < idList.ChildNodes.Count; i++)
{
var columnSource = idList.ChildNodes[i];
if (i > 0)
{
_builder.Append(", ");
}
if (columnSource.ChildNodes[0].Term.Name == "Id")
{
EvaluateId(columnSource.ChildNodes[0]);
}
else
{
EvaluateFunCall(columnSource.ChildNodes[0]);
}
}
_groupBy = _builder.ToString();
_modes.Pop();
}
private void EvaluateWhereClause(ParseTreeNode parseTreeNode)
{
if (parseTreeNode.ChildNodes.Count == 0)
{
// EMPTY
return;
}
_builder.Clear();
_modes.Push(FormattingModes.SelectClause);
EvaluateExpression(parseTreeNode.ChildNodes[1]);
_where = _builder.ToString();
_modes.Pop();
}
private void EvaluateExpression(ParseTreeNode parseTreeNode)
{
switch (parseTreeNode.Term.Name)
{
case "unExpr":
_builder.Append(parseTreeNode.ChildNodes[0].Term.Name);
EvaluateExpression(parseTreeNode.ChildNodes[1]);
break;
case "binExpr":
EvaluateExpression(parseTreeNode.ChildNodes[0]);
_builder.Append(" ");
_builder.Append(parseTreeNode.ChildNodes[1].ChildNodes[0].Term.Name).Append(" ");
EvaluateExpression(parseTreeNode.ChildNodes[2]);
break;
case "betweenExpr":
EvaluateExpression(parseTreeNode.ChildNodes[0]);
_builder.Append(" ");
if (parseTreeNode.ChildNodes[1].ChildNodes.Count > 0)
{
_builder.Append("NOT ");
}
_builder.Append("BETWEEN ");
EvaluateExpression(parseTreeNode.ChildNodes[3]);
_builder.Append(" ");
_builder.Append("AND ");
EvaluateExpression(parseTreeNode.ChildNodes[5]);
break;
case "inExpr":
EvaluateExpression(parseTreeNode.ChildNodes[0]);
_builder.Append(" ");
if (parseTreeNode.ChildNodes[1].ChildNodes.Count > 0)
{
_builder.Append("NOT ");
}
_builder.Append("IN (");
EvaluateInArgs(parseTreeNode.ChildNodes[3]);
_builder.Append(")");
break;
// Term and Tuple are transient, to they appear directly
case "Id":
EvaluateId(parseTreeNode);
break;
case "boolean":
_builder.Append(_dialect.GetSqlValue(parseTreeNode.ChildNodes[0].Term.Name == "TRUE"));
break;
case "string":
_builder.Append(_dialect.GetSqlValue(parseTreeNode.Token.ValueString));
break;
case "number":
_builder.Append(_dialect.GetSqlValue(parseTreeNode.Token.Value));
break;
case "funCall":
EvaluateFunCall(parseTreeNode);
break;
case "exprList":
_builder.Append("(");
EvaluateExpression(parseTreeNode.ChildNodes[0]);
_builder.Append(")");
break;
case "parSelectStmt":
_builder.Append("(");
_builder.Append(EvaluateSelectStatement(parseTreeNode.ChildNodes[0]));
_builder.Append(")");
break;
case "parameter":
var name = parseTreeNode.ChildNodes[1].ChildNodes[0].Token.ValueString;
_builder.Append("@" + name);
if (_parameters != null && !_parameters.ContainsKey(name))
{
// If a parameter is not set and there is no default value, report it
if (parseTreeNode.ChildNodes.Count < 3)
{
throw new SqlParserException("Missing parameters: " + name);
}
else
{
if (parseTreeNode.ChildNodes[3].Token != null)
{
_parameters[name] = parseTreeNode.ChildNodes[3].Token.Value;
}
else
{
// example: true
if (parseTreeNode.ChildNodes[3].ChildNodes[0].Token != null)
{
_parameters[name] = parseTreeNode.ChildNodes[3].ChildNodes[0].Token.Value;
}
else
{
throw new SqlParserException("Unsupported syntax for parameter: " + name);
}
}
}
}
break;
case "*":
_builder.Append("*");
break;
}
}
private void EvaluateInArgs(ParseTreeNode inArgs)
{
if (inArgs.ChildNodes[0].Term.Name == "selectStatement")
{
// selectStatement
_builder.Append(EvaluateSelectStatement(inArgs.ChildNodes[0]));
}
else
{
// expressionList
EvaluateExpressionList(inArgs.ChildNodes[0]);
}
}
private void EvaluateFunCall(ParseTreeNode funCall)
{
var funcName = funCall.ChildNodes[0].ChildNodes[0].Token.ValueString;
IList<string> arguments;
var tempBuilder = _builder;
if (funCall.ChildNodes[1].ChildNodes[0].Term.Name == "selectStatement")
{
// selectStatement
_builder = new StringBuilder();
_builder.Append(EvaluateSelectStatement(funCall.ChildNodes[1].ChildNodes[0]));
arguments = new string[] { _builder.ToString() };
_builder = tempBuilder;
}
else if (funCall.ChildNodes[1].ChildNodes[0].Term.Name == "*")
{
arguments = new string[] { "*" };
}
else
{
// expressionList
arguments = new List<string>();
for (var i = 0; i < funCall.ChildNodes[1].ChildNodes[0].ChildNodes.Count; i++)
{
_builder = new StringBuilder();
EvaluateExpression(funCall.ChildNodes[1].ChildNodes[0].ChildNodes[i]);
arguments.Add(_builder.ToString());
_builder = tempBuilder;
}
}
_builder.Append(_dialect.RenderMethod(funcName, arguments.ToArray()));
}
private void EvaluateExpressionList(ParseTreeNode expressionList)
{
for (var i = 0; i < expressionList.ChildNodes.Count; i++)
{
if (i > 0)
{
_builder.Append(", ");
}
EvaluateExpression(expressionList.ChildNodes[i]);
}
}
private void EvaluateFromClause(ParseTreeNode parseTreeNode)
{
if (parseTreeNode.ChildNodes.Count == 0)
{
// EMPTY
return;
}
_builder.Clear();
var aliasList = parseTreeNode.ChildNodes[1];
_modes.Push(FormattingModes.FromClause);
EvaluateAliasList(aliasList);
_modes.Pop();
var joins = parseTreeNode.ChildNodes[2];
// process join statements
if (joins.ChildNodes.Count != 0)
{
foreach (var joinStatement in joins.ChildNodes)
{
_modes.Push(FormattingModes.FromClause);
var jointKindOpt = joinStatement.ChildNodes[0];
if (jointKindOpt.ChildNodes.Count > 0)
{
_builder.Append(" ").Append(jointKindOpt.ChildNodes[0].Term.Name);
}
_builder.Append(" JOIN ");
EvaluateAliasList(joinStatement.ChildNodes[2]);
_builder.Append(" ON ");
_modes.Push(FormattingModes.SelectClause);
EvaluateId(joinStatement.ChildNodes[4]);
_builder.Append(" = ");
EvaluateId(joinStatement.ChildNodes[6]);
_modes.Pop();
}
}
_from = _builder.ToString();
}
private void EvaluateAliasList(ParseTreeNode aliasList)
{
for (var i = 0; i < aliasList.ChildNodes.Count; i++)
{
var aliasItem = aliasList.ChildNodes[i];
if (i > 0)
{
_builder.Append(", ");
}
EvaluateId(aliasItem.ChildNodes[0]);
if (aliasItem.ChildNodes.Count > 1)
{
EvaluateAliasOptional(aliasItem.ChildNodes[1]);
}
}
}
private void EvaluateSelectorList(ParseTreeNode parseTreeNode)
{
var selectorList = parseTreeNode.ChildNodes[0];
if (selectorList.Term.Name == "*")
{
_builder.Append("*");
}
else
{
_modes.Push(FormattingModes.SelectClause);
// columnItemList
for (var i = 0; i < selectorList.ChildNodes.Count; i++)
{
if (i > 0)
{
_builder.Append(", ");
}
var columnItem = selectorList.ChildNodes[i];
// columnItem
var columnSource = columnItem.ChildNodes[0];
var funCallOrId = columnSource.ChildNodes[0];
if (funCallOrId.Term.Name == "Id")
{
EvaluateId(funCallOrId);
}
else
{
EvaluateFunCall(funCallOrId);
}
if (columnItem.ChildNodes.Count > 1)
{
// AS
EvaluateAliasOptional(columnItem.ChildNodes[1]);
}
}
_modes.Pop();
}
_select = _builder.ToString();
}
private void EvaluateId(ParseTreeNode id)
{
switch (_modes.Peek())
{
case FormattingModes.SelectClause:
EvaluateSelectId(id);
break;
case FormattingModes.FromClause:
EvaluateFromId(id);
break;
}
}
private void EvaluateSelectId(ParseTreeNode id)
{
for (var i = 0; i < id.ChildNodes.Count; i++)
{
if (i == 0 && id.ChildNodes.Count > 1 && !_aliases.Contains(id.ChildNodes[i].Token.ValueString))
{
_builder.Append(_dialect.QuoteForTableName(_tablePrefix + id.ChildNodes[i].Token.ValueString));
}
else
{
if (i > 0)
{
_builder.Append(".");
}
if (_aliases.Contains(id.ChildNodes[i].Token.ValueString))
{
_builder.Append(id.ChildNodes[i].Token.ValueString);
}
else
{
_builder.Append(_dialect.QuoteForColumnName(id.ChildNodes[i].Token.ValueString));
}
}
}
}
private void EvaluateFromId(ParseTreeNode id)
{
for (var i = 0; i < id.ChildNodes.Count; i++)
{
if (i == 0 && !_aliases.Contains(id.ChildNodes[i].Token.ValueString))
{
_builder.Append(_dialect.QuoteForTableName(_tablePrefix + id.ChildNodes[i].Token.ValueString));
}
else
{
_builder.Append(_dialect.QuoteForColumnName(id.ChildNodes[i].Token.ValueString));
}
}
}
private void EvaluateAliasOptional(ParseTreeNode parseTreeNode)
{
if (parseTreeNode.ChildNodes.Count > 0)
{
_builder.Append(" AS ");
_builder.Append(parseTreeNode.ChildNodes[0].Token.ValueString);
}
}
private void EvaluateSelectRestriction(ParseTreeNode parseTreeNode)
{
_builder.Clear();
if (parseTreeNode.ChildNodes.Count > 0)
{
_builder.Append(parseTreeNode.ChildNodes[0].Term.Name).Append(" ");
}
}
private enum FormattingModes
{
SelectClause,
FromClause
}
}
}
| |
using System;
using System.IO;
using System.Drawing;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace IDE {
[Serializable]
public class FileProject {
public Project Project;
public int Frequency = 1;
public string Code;
public byte[] Instructions;
public Wire_Project[] Wires;
public Component_Project[] Components;
public static bool Save(string dir) {
var project = new FileProject();
if (UiStatics.Simulador != null) {
project.Frequency = UiStatics.Simulador.Frequency;
}
project.Code = UiStatics.Codigo.scintilla.Text;
project.Instructions = new byte[5];
project.Instructions[0] = 13;
project.Instructions[1] = 45;
project.Instructions[2] = 55;
project.Instructions[3] = 67;
project.Instructions[4] = 154;
project.Components = new Component_Project[UiStatics.Circuito.Components.Count];
project.Wires = new Wire_Project[UiStatics.Circuito.Wires.Count];
for (var i = 0; i < project.Components.Length; i++) {
project.Components[i] = new Component_Project(UiStatics.Circuito.Components[i]);
}
for (var i = 0; i < project.Wires.Length; i++) {
project.Wires[i] = new Wire_Project(UiStatics.Circuito.Wires[i], project);
}
return SerializeObject(project, UiStatics.FilePath);
}
public static bool Load(string dir) {
var project = DeSerializeObject(dir);
if (project == null) return false;
UiStatics.Depurador.SetText("");
UiStatics.Simulador = null;
if (project.Code != null && project.Code != "") {
UiStatics.Codigo.scintilla.Text = project.Code;
} else {
}
UiStatics.Circuito.Wires.Clear();
UiStatics.Circuito.Components.Clear();
for (var i = 0; i < project.Components.Length; i++) {
UiStatics.Circuito.Components.Add(project.Components[i]);
}
for (var i = 0; i < project.Wires.Length; i++) {
UiStatics.Circuito.Wires.Add(project.Wires[i].ToWire(project));
}
return true;
}
/// <summary>
/// Serializes an object.
/// http://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializableObject"></param>
/// <param name="fileName"></param>
private static bool SerializeObject(FileProject serializableObject, string fileName) {
try {
if (serializableObject == null) { return false; }
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(fileName,
FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, serializableObject);
stream.Close();
return true;
} catch (Exception) {
return false;
}
}
/// <summary>
/// Deserializes an xml file into an object list
/// http://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
private static FileProject DeSerializeObject(string fileName) {
if (string.IsNullOrEmpty(fileName)) { return null; }
FileProject objectOut = null;
try {
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(fileName,
FileMode.Open,
FileAccess.Read, FileShare.None);
objectOut = (FileProject) formatter.Deserialize(stream);
stream.Close();
return objectOut;
} catch (Exception) {
return null;
}
}
}
[Serializable]
public class Point_Project {
public float X, Y;
public Point_Project(PointF point) {
X = point.X;
Y = point.Y;
}
public Point_Project(float X, float Y) {
this.X = X;
this.Y = Y;
}
public static implicit operator PointF(Point_Project p) {
return new PointF(p.X, p.Y);
}
public static implicit operator Point_Project(PointF p) {
return new Point_Project(p);
}
}
[Serializable]
public class Component_Project {
public Point_Project Center;
public float Rotation;
public ComponentType Type;
public int RootComponent;
public Component_Project(Component c) {
Center = c.Center;
Rotation = c.Rotation;
Type = c.Type;
RootComponent = UiStatics.Circuito.Components.IndexOf(c.RootComponent);
}
public static implicit operator Component(Component_Project c) {
ComponentDraw draw = null;
switch (c.Type) {
case ComponentType.None:
break;
case ComponentType.Input:
draw = Draws.Input[0];
break;
case ComponentType.Output:
draw = Draws.Output[0];
break;
case ComponentType.Disable:
draw = Draws.Disable[0];
break;
case ComponentType.Not:
draw = Draws.Not[0];
break;
case ComponentType.And:
draw = Draws.And[0];
break;
case ComponentType.Nand:
draw = Draws.Nand[0];
break;
case ComponentType.Or:
draw = Draws.Or[0];
break;
case ComponentType.Nor:
draw = Draws.Nor[0];
break;
case ComponentType.Xor:
draw = Draws.Xor[0];
break;
case ComponentType.Xnor:
draw = Draws.Xnor[0];
break;
case ComponentType.Keyboard:
draw = Draws.Keyboard;
break;
case ComponentType.Display7Seg:
draw = Draws.Display7SegBase;
break;
case ComponentType.Circuit:
break;
case ComponentType.Microcontroller:
draw = Draws.Microcontroller;
break;
case ComponentType.Osciloscope:
draw = Draws.Osciloscope;
break;
case ComponentType.BlackTerminal:
break;
case ComponentType.JkFlipFlop:
draw = Draws.JkFlipFlop;
break;
case ComponentType.RsFlipFlop:
draw = Draws.RsFlipFlop;
break;
case ComponentType.DFlipFlop:
draw = Draws.DFlipFlop;
break;
case ComponentType.FlipFlop:
draw = Draws.FlipFlop;
break;
case ComponentType.ControlModule:
draw = Draws.ControlModule;
break;
case ComponentType.PortBank:
draw = Draws.PortBank;
break;
case ComponentType.RamMemory:
draw = Draws.RamMemory;
break;
case ComponentType.RomMemory:
draw = Draws.RomMemory;
break;
case ComponentType.Stack:
break;
case ComponentType.Tristate:
draw = Draws.Disable[0];
break;
case ComponentType.Ula:
draw = Draws.Ula;
break;
case ComponentType.Registrer8Bit:
draw = Draws.Registrer8Bit;
break;
case ComponentType.Registrer8BitSg:
draw = Draws.Registrer8BitSg;
break;
case ComponentType.Registrers:
draw = Draws.Registrers;
break;
case ComponentType.Disable8Bit:
draw = Draws.Disable8Bit;
break;
case ComponentType.BinTo7Seg:
draw = Draws.BinTo7Seg;
break;
case ComponentType.Registrer8BitCBuffer:
draw = Draws.Registrer8BitCBuffer;
break;
case ComponentType.Counter8Bit:
draw = Draws.Counter8Bit;
break;
case ComponentType.RomAddresser:
draw = Draws.RomAddresser;
break;
case ComponentType.Clock:
draw = Draws.Clock;
break;
default:
break;
}
var component = new Component(draw, c.Center);
component.Rotation = c.Rotation;
component.Type = c.Type;
if(c.RootComponent != -1)
component.RootComponent = UiStatics.Circuito.Components[c.RootComponent];
return component;
}
}
[Serializable]
public class Wire_Project {
public Point_Project From;
public int FromComponent;
public int FromIndex;
public Point_Project To;
public int ToComponent;
public int ToIndex;
public int RootComponent;
public Wire_Project(Wire wire, FileProject project) {
From = wire.From;
RootComponent = UiStatics.Circuito.Components.IndexOf(wire.RootComponent);
if (wire.FromComponent != null) {
FromComponent = UiStatics.Circuito.Components.IndexOf(wire.FromComponent);
FromIndex = wire.FromIndex;
} else {
FromIndex = -1;
FromComponent = -1;
}
To = wire.To;
if (wire.ToComponent != null) {
ToComponent = UiStatics.Circuito.Components.IndexOf(wire.ToComponent);
ToIndex = wire.ToIndex;
} else {
ToIndex = -1;
ToComponent = -1;
}
}
public Wire ToWire(FileProject project) {
var wire = new Wire(From, To);
if (RootComponent != -1)
wire.RootComponent = UiStatics.Circuito.Components[RootComponent];
if (FromComponent != -1) {
wire.FromComponent = UiStatics.Circuito.Components[FromComponent];
wire.FromIndex = FromIndex;
} else {
FromIndex = -1;
}
if (ToComponent != -1) {
wire.ToComponent = UiStatics.Circuito.Components[ToComponent];
wire.ToIndex = ToIndex;
} else {
FromIndex = -1;
}
return wire;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) 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.
*
* 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;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// Represents a host crash dump
/// First published in XenServer 4.0.
/// </summary>
public partial class Host_crashdump : XenObject<Host_crashdump>
{
public Host_crashdump()
{
}
public Host_crashdump(string uuid,
XenRef<Host> host,
DateTime timestamp,
long size,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.host = host;
this.timestamp = timestamp;
this.size = size;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Host_crashdump from a Proxy_Host_crashdump.
/// </summary>
/// <param name="proxy"></param>
public Host_crashdump(Proxy_Host_crashdump proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(Host_crashdump update)
{
uuid = update.uuid;
host = update.host;
timestamp = update.timestamp;
size = update.size;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_Host_crashdump proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
timestamp = proxy.timestamp;
size = proxy.size == null ? 0 : long.Parse((string)proxy.size);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_Host_crashdump ToProxy()
{
Proxy_Host_crashdump result_ = new Proxy_Host_crashdump();
result_.uuid = (uuid != null) ? uuid : "";
result_.host = (host != null) ? host : "";
result_.timestamp = timestamp;
result_.size = size.ToString();
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new Host_crashdump from a Hashtable.
/// </summary>
/// <param name="table"></param>
public Host_crashdump(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
host = Marshalling.ParseRef<Host>(table, "host");
timestamp = Marshalling.ParseDateTime(table, "timestamp");
size = Marshalling.ParseLong(table, "size");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(Host_crashdump other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._timestamp, other._timestamp) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, Host_crashdump server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Host_crashdump.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given host_crashdump.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static Host_crashdump get_record(Session session, string _host_crashdump)
{
return new Host_crashdump((Proxy_Host_crashdump)session.proxy.host_crashdump_get_record(session.uuid, (_host_crashdump != null) ? _host_crashdump : "").parse());
}
/// <summary>
/// Get a reference to the host_crashdump instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Host_crashdump> get_by_uuid(Session session, string _uuid)
{
return XenRef<Host_crashdump>.Create(session.proxy.host_crashdump_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Get the uuid field of the given host_crashdump.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static string get_uuid(Session session, string _host_crashdump)
{
return (string)session.proxy.host_crashdump_get_uuid(session.uuid, (_host_crashdump != null) ? _host_crashdump : "").parse();
}
/// <summary>
/// Get the host field of the given host_crashdump.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static XenRef<Host> get_host(Session session, string _host_crashdump)
{
return XenRef<Host>.Create(session.proxy.host_crashdump_get_host(session.uuid, (_host_crashdump != null) ? _host_crashdump : "").parse());
}
/// <summary>
/// Get the timestamp field of the given host_crashdump.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static DateTime get_timestamp(Session session, string _host_crashdump)
{
return session.proxy.host_crashdump_get_timestamp(session.uuid, (_host_crashdump != null) ? _host_crashdump : "").parse();
}
/// <summary>
/// Get the size field of the given host_crashdump.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static long get_size(Session session, string _host_crashdump)
{
return long.Parse((string)session.proxy.host_crashdump_get_size(session.uuid, (_host_crashdump != null) ? _host_crashdump : "").parse());
}
/// <summary>
/// Get the other_config field of the given host_crashdump.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static Dictionary<string, string> get_other_config(Session session, string _host_crashdump)
{
return Maps.convert_from_proxy_string_string(session.proxy.host_crashdump_get_other_config(session.uuid, (_host_crashdump != null) ? _host_crashdump : "").parse());
}
/// <summary>
/// Set the other_config field of the given host_crashdump.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _host_crashdump, Dictionary<string, string> _other_config)
{
session.proxy.host_crashdump_set_other_config(session.uuid, (_host_crashdump != null) ? _host_crashdump : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given host_crashdump.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _host_crashdump, string _key, string _value)
{
session.proxy.host_crashdump_add_to_other_config(session.uuid, (_host_crashdump != null) ? _host_crashdump : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given host_crashdump. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _host_crashdump, string _key)
{
session.proxy.host_crashdump_remove_from_other_config(session.uuid, (_host_crashdump != null) ? _host_crashdump : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Destroy specified host crash dump, removing it from the disk.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static void destroy(Session session, string _host_crashdump)
{
session.proxy.host_crashdump_destroy(session.uuid, (_host_crashdump != null) ? _host_crashdump : "").parse();
}
/// <summary>
/// Destroy specified host crash dump, removing it from the disk.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static XenRef<Task> async_destroy(Session session, string _host_crashdump)
{
return XenRef<Task>.Create(session.proxy.async_host_crashdump_destroy(session.uuid, (_host_crashdump != null) ? _host_crashdump : "").parse());
}
/// <summary>
/// Upload the specified host crash dump to a specified URL
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
/// <param name="_url">The URL to upload to</param>
/// <param name="_options">Extra configuration operations</param>
public static void upload(Session session, string _host_crashdump, string _url, Dictionary<string, string> _options)
{
session.proxy.host_crashdump_upload(session.uuid, (_host_crashdump != null) ? _host_crashdump : "", (_url != null) ? _url : "", Maps.convert_to_proxy_string_string(_options)).parse();
}
/// <summary>
/// Upload the specified host crash dump to a specified URL
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
/// <param name="_url">The URL to upload to</param>
/// <param name="_options">Extra configuration operations</param>
public static XenRef<Task> async_upload(Session session, string _host_crashdump, string _url, Dictionary<string, string> _options)
{
return XenRef<Task>.Create(session.proxy.async_host_crashdump_upload(session.uuid, (_host_crashdump != null) ? _host_crashdump : "", (_url != null) ? _url : "", Maps.convert_to_proxy_string_string(_options)).parse());
}
/// <summary>
/// Return a list of all the host_crashdumps known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Host_crashdump>> get_all(Session session)
{
return XenRef<Host_crashdump>.Create(session.proxy.host_crashdump_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the host_crashdump Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Host_crashdump>, Host_crashdump> get_all_records(Session session)
{
return XenRef<Host_crashdump>.Create<Proxy_Host_crashdump>(session.proxy.host_crashdump_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// Host the crashdump relates to
/// </summary>
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host;
/// <summary>
/// Time the crash happened
/// </summary>
public virtual DateTime timestamp
{
get { return _timestamp; }
set
{
if (!Helper.AreEqual(value, _timestamp))
{
_timestamp = value;
Changed = true;
NotifyPropertyChanged("timestamp");
}
}
}
private DateTime _timestamp;
/// <summary>
/// Size of the crashdump
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
Changed = true;
NotifyPropertyChanged("size");
}
}
}
private long _size;
/// <summary>
/// additional configuration
/// First published in XenServer 4.1.
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
}
}
| |
// Copyright 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.
// Original code by Nora
// http://stereoarts.jp
//
// Retrieved from:
// https://developer.oculusvr.com/forums/viewtopic.php?f=37&t=844#p28982
//
// Modified by Google:
// Combined the 6 separate meshes into a single mesh with submeshes.
//
// Usage:
// Attach to a camera object, and it meshifies the camera's skybox at runtime.
// The skybox is automatically scaled to fit just inside the far clipping
// plane and is kept centered on the camera.
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class SkyboxMesh : MonoBehaviour {
#if UNITY_5
void Awake() {
Debug.Log("SkyboxMesh is not needed in Unity 5");
Component.Destroy(this);
}
#else
public enum Shape {
Sphere,
Cube,
}
public Shape shape = Shape.Sphere;
public int segments = 32;
public int layer = 0;
private GameObject skybox;
void Awake() {
var sky = GetComponent<Skybox>();
Material skymat = sky != null ? sky.material : RenderSettings.skybox;
if (skymat == null) {
enabled = false;
return;
}
skybox = new GameObject(skymat.name + "SkyMesh");
skybox.transform.parent = transform;
skybox.transform.localPosition = Vector3.zero;
skybox.layer = layer;
var filter = skybox.AddComponent<MeshFilter>();
filter.mesh = _CreateSkyboxMesh();
Material mat = new Material(Shader.Find("Cardboard/SkyboxMesh"));
var render = skybox.AddComponent<MeshRenderer>();
render.sharedMaterials = new Material[] {
new Material(mat) { mainTexture = skymat.GetTexture("_FrontTex") },
new Material(mat) { mainTexture = skymat.GetTexture("_LeftTex") },
new Material(mat) { mainTexture = skymat.GetTexture("_BackTex") },
new Material(mat) { mainTexture = skymat.GetTexture("_RightTex") },
new Material(mat) { mainTexture = skymat.GetTexture("_UpTex") },
new Material(mat) { mainTexture = skymat.GetTexture("_DownTex") }
};
render.castShadows = false;
render.receiveShadows = false;
}
void LateUpdate() {
var camera = GetComponent<Camera>();
// Only visible if the owning camera needs it.
skybox.GetComponent<Renderer>().enabled =
camera.enabled && (camera.clearFlags == CameraClearFlags.Skybox);
// Scale up to just fit inside the far clip plane.
Vector3 scale = transform.lossyScale;
float far = camera.farClipPlane * 0.95f;
if (shape == Shape.Cube) {
far /= Mathf.Sqrt(3); // Corners need to fit inside the frustum.
}
scale.x = far / scale.x;
scale.y = far / scale.y;
scale.z = far / scale.z;
// Center on the camera.
skybox.transform.localPosition = Vector3.zero;
skybox.transform.localScale = scale;
// Keep orientation fixed in the world.
skybox.transform.rotation = Quaternion.identity;
}
Mesh _CreateMesh() {
Mesh mesh = new Mesh();
int hvCount2 = this.segments + 1;
int hvCount2Half = hvCount2 / 2;
int numVertices = hvCount2 * hvCount2;
int numTriangles = this.segments * this.segments * 6;
Vector3[] vertices = new Vector3[numVertices];
Vector2[] uvs = new Vector2[numVertices];
int[] triangles = new int[numTriangles];
float scaleFactor = 2.0f / (float)this.segments;
float uvFactor = 1.0f / (float)this.segments;
if (this.segments <= 1 || this.shape == Shape.Cube) {
float ty = 0.0f, py = -1.0f;
int index = 0;
for (int y = 0; y < hvCount2; ++y, ty += uvFactor, py += scaleFactor) {
float tx = 0.0f, px = -1.0f;
for (int x = 0; x < hvCount2; ++x, ++index, tx += uvFactor, px += scaleFactor) {
vertices[index] = new Vector3(px, py, 1.0f);
uvs[index] = new Vector2(tx, ty);
}
}
} else {
float ty = 0.0f, py = -1.0f;
int index = 0, indexY = 0;
for (int y = 0; y <= hvCount2Half;
++y, indexY += hvCount2, ty += uvFactor, py += scaleFactor) {
float tx = 0.0f, px = -1.0f, py2 = py * py;
int x = 0;
for (; x <= hvCount2Half; ++x, ++index, tx += uvFactor, px += scaleFactor) {
float d = Mathf.Sqrt(px * px + py2 + 1.0f);
float theta = Mathf.Acos(1.0f / d);
float phi = Mathf.Atan2(py, px);
float sinTheta = Mathf.Sin(theta);
vertices[index] = new Vector3(
sinTheta * Mathf.Cos(phi),
sinTheta * Mathf.Sin(phi),
Mathf.Cos(theta));
uvs[index] = new Vector2(tx, ty);
}
int indexX = hvCount2Half - 1;
for (; x < hvCount2; ++x, ++index, --indexX, tx += uvFactor, px += scaleFactor) {
Vector3 v = vertices[indexY + indexX];
vertices[index] = new Vector3(-v.x, v.y, v.z);
uvs[index] = new Vector2(tx, ty);
}
}
indexY = (hvCount2Half - 1) * hvCount2;
for (int y = hvCount2Half + 1; y < hvCount2;
++y, indexY -= hvCount2, ty += uvFactor, py += scaleFactor) {
float tx = 0.0f, px = -1.0f;
int x = 0;
for (; x <= hvCount2Half; ++x, ++index, tx += uvFactor, px += scaleFactor) {
Vector3 v = vertices[indexY + x];
vertices[index] = new Vector3(v.x, -v.y, v.z);
uvs[index] = new Vector2(tx, ty);
}
int indexX = hvCount2Half - 1;
for (; x < hvCount2; ++x, ++index, --indexX, tx += uvFactor, px += scaleFactor) {
Vector3 v = vertices[indexY + indexX];
vertices[index] = new Vector3(-v.x, -v.y, v.z);
uvs[index] = new Vector2(tx, ty);
}
}
}
for (int y = 0, index = 0, ofst = 0; y < this.segments; ++y, ofst += hvCount2) {
int y0 = ofst, y1 = ofst + hvCount2;
for (int x = 0; x < this.segments; ++x, index += 6) {
triangles[index + 0] = y0 + x;
triangles[index + 1] = y1 + x;
triangles[index + 2] = y0 + x + 1;
triangles[index + 3] = y1 + x;
triangles[index + 4] = y1 + x + 1;
triangles[index + 5] = y0 + x + 1;
}
}
mesh.vertices = vertices;
mesh.uv = uvs;
mesh.triangles = triangles;
return mesh;
}
CombineInstance _CreatePlane(Mesh mesh, Quaternion rotation) {
return new CombineInstance() {
mesh = mesh,
subMeshIndex = 0,
transform = Matrix4x4.TRS(Vector3.zero, rotation, Vector3.one)};
}
Mesh _CreateSkyboxMesh() {
Mesh mesh = _CreateMesh();
var comb = new CombineInstance[] {
_CreatePlane(mesh, Quaternion.identity),
_CreatePlane(mesh, Quaternion.Euler(0.0f, 90.0f, 0.0f)),
_CreatePlane(mesh, Quaternion.Euler(0.0f, 180.0f, 0.0f)),
_CreatePlane(mesh, Quaternion.Euler(0.0f, 270.0f, 0.0f)),
_CreatePlane(mesh, Quaternion.Euler(-90.0f, 0.0f, 0.0f)),
_CreatePlane(mesh, Quaternion.Euler(90.0f, 0.0f, 0.0f))};
Mesh skymesh = new Mesh();
skymesh.CombineMeshes(comb, false, true);
return skymesh;
}
#endif
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using SampleClassLibrary;
using UnityEngine;
using System.Collections;
using Newtonsoft.Json;
using Assets.DustinHorne.JsonDotNetUnity.TestCases;
using Assets.DustinHorne.JsonDotNetUnity.TestCases.TestModels;
public class JsonTestScript
{
private TextMesh _text;
private const string BAD_RESULT_MESSAGE = "Incorrect Deserialized Result";
public JsonTestScript(TextMesh text)
{
_text = text;
}
/// <summary>
/// Simple Vector3 Serialization
/// </summary>
public void SerializeVector3()
{
LogStart("Vector3 Serialization");
try
{
var v = new Vector3(2, 4, 6);
var serialized = JsonConvert.SerializeObject(v);
LogSerialized(serialized);
var v2 = JsonConvert.DeserializeObject<Vector3>(serialized);
LogResult("4", v2.y);
if (v2.y != v.y)
{
DisplayFail("Vector3 Serialization", BAD_RESULT_MESSAGE);
}
DisplaySuccess("Vector3 Serialization");
}
catch(Exception ex)
{
DisplayFail("Vector3 Serialization", ex.Message);
}
LogEnd(1);
}
/// <summary>
/// List<T> serialization
/// </summary>
public void GenericListSerialization()
{
LogStart("List<T> Serialization");
try
{
var objList = new List<SimpleClassObject>();
for (var i = 0; i < 4; i++)
{
objList.Add(TestCaseUtils.GetSimpleClassObject());
}
var serialized = JsonConvert.SerializeObject(objList);
LogSerialized(serialized);
var newList = JsonConvert.DeserializeObject<List<SimpleClassObject>>(serialized);
LogResult(objList.Count.ToString(), newList.Count);
LogResult(objList[2].TextValue, newList[2].TextValue);
if((objList.Count != newList.Count) || (objList[3].TextValue != newList[3].TextValue))
{
DisplayFail("List<T> Serialization", BAD_RESULT_MESSAGE);
Debug.LogError("Deserialized List<T> has incorrect count or wrong item value");
}
else
{
DisplaySuccess("List<T> Serialization");
}
}
catch(Exception ex)
{
DisplayFail("List<T> Serialization", ex.Message);
throw;
}
LogEnd(2);
}
/// <summary>
/// Polymorphism
/// </summary>
public void PolymorphicSerialization()
{
LogStart("Polymorphic Serialization");
try
{
var list = new List<SampleBase>();
for (var i = 0; i < 4; i++)
{
list.Add(TestCaseUtils.GetSampleChid());
}
var serialized = JsonConvert.SerializeObject(list, Formatting.None, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
LogSerialized(serialized);
var newList = JsonConvert.DeserializeObject<List<SampleBase>>(serialized, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
var deserializedObject = newList[2] as SampleChild;
if (deserializedObject == null)
{
DisplayFail("Polymorphic Serialization", BAD_RESULT_MESSAGE);
}
else
{
LogResult(list[2].TextValue, newList[2].TextValue);
if (list[2].TextValue != newList[2].TextValue)
{
DisplayFail("Polymorphic Serialization", BAD_RESULT_MESSAGE);
}
else
{
DisplaySuccess("Polymorphic Serialization");
}
}
}
catch(Exception ex)
{
DisplayFail("Polymorphic Serialization", ex.Message);
throw;
}
LogEnd(3);
}
/// <summary>
/// Dictionary Serialization
/// </summary>
public void DictionarySerialization()
{
LogStart("Dictionary & Other DLL");
try
{
var o = new SampleExternalClass { SampleString = Guid.NewGuid().ToString() };
o.SampleDictionary.Add(1, "A");
o.SampleDictionary.Add(2, "B");
o.SampleDictionary.Add(3, "C");
o.SampleDictionary.Add(4, "D");
var serialized = JsonConvert.SerializeObject(o);
LogSerialized(serialized);
var newObj = JsonConvert.DeserializeObject<SampleExternalClass>(serialized);
LogResult(o.SampleString, newObj.SampleString);
LogResult(o.SampleDictionary.Count.ToString(), newObj.SampleDictionary.Count);
var keys = new StringBuilder(4);
var vals = new StringBuilder(4);
foreach (var kvp in o.SampleDictionary)
{
keys.Append(kvp.Key.ToString());
vals.Append(kvp.Value);
}
LogResult("1234", keys.ToString());
LogResult("ABCD", vals.ToString());
if ((o.SampleString != newObj.SampleString) || (o.SampleDictionary.Count != newObj.SampleDictionary.Count) ||
(keys.ToString() != "1234") || (vals.ToString() != "ABCD"))
{
DisplayFail("Dictionary & Other DLL", BAD_RESULT_MESSAGE);
}
else
{
DisplaySuccess("Dictionary & Other DLL");
}
}
catch(Exception ex)
{
DisplayFail("Dictionary & Other DLL", ex.Message);
throw;
}
}
/// <summary>
/// Serialize a dictionary with an object as the value
/// </summary>
public void DictionaryObjectValueSerialization()
{
LogStart("Dictionary (Object Value)");
try
{
var dict = new Dictionary<int, SampleBase>();
for (var i = 0; i < 4; i++)
{
dict.Add(i, TestCaseUtils.GetSampleBase());
}
var serialized = JsonConvert.SerializeObject(dict);
LogSerialized(serialized);
var newDict = JsonConvert.DeserializeObject<Dictionary<int, SampleBase>>(serialized);
LogResult(dict[1].TextValue, newDict[1].TextValue);
if (dict[1].TextValue != newDict[1].TextValue)
{
DisplayFail("Dictionary (Object Value)", BAD_RESULT_MESSAGE);
}
else
{
DisplaySuccess("Dictionary (Object Value)");
}
}
catch (Exception ex)
{
DisplayFail("Dictionary (Object Value)", ex.Message);
throw;
}
}
/// <summary>
/// Serialize a dictionary with an object as the key
/// </summary>
public void DictionaryObjectKeySerialization()
{
LogStart("Dictionary (Object As Key)");
try
{
var dict = new Dictionary<SampleBase, int>();
for (var i = 0; i < 4; i++)
{
dict.Add(TestCaseUtils.GetSampleBase(), i);
}
var serialized = JsonConvert.SerializeObject(dict);
LogSerialized(serialized);
_text.text = serialized;
var newDict = JsonConvert.DeserializeObject<Dictionary<SampleBase, int>>(serialized);
var oldKeys = new List<SampleBase>();
var newKeys = new List<SampleBase>();
foreach (var k in dict.Keys)
{
oldKeys.Add(k);
}
foreach (var k in newDict.Keys)
{
newKeys.Add(k);
}
LogResult(oldKeys[1].TextValue, newKeys[1].TextValue);
if (oldKeys[1].TextValue != newKeys[1].TextValue)
{
DisplayFail("Dictionary (Object As Key)", BAD_RESULT_MESSAGE);
}
else
{
DisplaySuccess("Dictionary (Object As Key)");
}
}
catch (Exception ex)
{
DisplayFail("Dictionary (Object As Key)", ex.Message);
throw;
}
}
#region Private Helper Methods
private void DisplaySuccess(string testName)
{
_text.text = testName + "\r\nSuccessful";
}
private void DisplayFail(string testName, string reason)
{
try
{
_text.text = testName + "\r\nFailed :( \r\n" + reason ?? string.Empty;
}
catch
{
Debug.Log("%%%%%%%%%%%" + testName);
}
}
private void LogStart(string testName)
{
Log(string.Empty);
Log(string.Format("======= SERIALIZATION TEST: {0} ==========", testName));
}
private void LogEnd(int testNum)
{
//Log(string.Format("====== SERIALIZATION TEST #{0} COMPLETE", testNum));
}
private void Log(object message)
{
Debug.Log(message);
}
private void LogSerialized(string message)
{
Debug.Log(string.Format("#### Serialized Object: {0}", message));
}
private void LogResult(string shouldEqual, object actual)
{
Log("--------------------");
Log(string.Format("*** Original Test value: {0}", shouldEqual));
Log(string.Format("*** Deserialized Test Value: {0}", actual));
Log("--------------------");
}
#endregion
}
| |
/* ====================================================================
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel; // need this for the properties metadata
using System.Drawing.Design;
using System.Xml;
using System.Globalization;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// PropertyAction -
/// </summary>
[TypeConverter(typeof(PropertyAppearanceConverter)),
Editor(typeof(PropertyAppearanceUIEditor), typeof(System.Drawing.Design.UITypeEditor))]
internal class PropertyAppearance : IReportItem
{
PropertyReportItem pri;
string[] _subitems;
string[] _names;
internal PropertyAppearance(PropertyReportItem ri)
{
pri = ri;
_names = null;
_subitems = new string[] { "Style", "" };
}
internal PropertyAppearance(PropertyReportItem ri, params string[] names)
{
pri = ri;
_names = names;
// now build the array used to get/set values
if (names != null)
{
_subitems = new string[names.Length + 2];
int i = 0;
foreach (string s in names)
_subitems[i++] = s;
_subitems[i++] = "Style";
}
else
_subitems = new string[] { "Style", "" };
}
internal string[] Names
{
get { return _names; }
}
[RefreshProperties(RefreshProperties.Repaint),
DescriptionAttribute("FontFamily is the name of the font family. Not all renderers support all fonts.")]
public PropertyExpr FontFamily
{
get
{
return new PropertyExpr(GetStyleValue("FontFamily", "Arial"));
}
set
{
SetStyleValue("FontFamily", value.Expression);
}
}
[RefreshProperties(RefreshProperties.Repaint),
DescriptionAttribute("Font size controls the text size.")]
public PropertyExpr FontSize
{
get
{
return new PropertyExpr(GetStyleValue("FontSize", "10pt"));
}
set
{
if (!pri.IsExpression(value.Expression))
DesignerUtility.ValidateSize(value.Expression, true, false);
SetStyleValue("FontSize", value.Expression);
}
}
[TypeConverter(typeof(FontStyleConverter)),
DescriptionAttribute("FontStyle determines if font is italicized.")]
public string FontStyle
{
get
{
return GetStyleValue("FontStyle", "Normal");
}
set
{
SetStyleValue("FontStyle", value);
}
}
[TypeConverter(typeof(FontWeightConverter)),
DescriptionAttribute("FontWeight controls the boldness of the font.")]
public string FontWeight
{
get
{
return GetStyleValue("FontWeight", "Normal");
}
set
{
SetStyleValue("FontWeight", value);
}
}
[TypeConverter(typeof(ColorConverter)),
DescriptionAttribute("Text color")]
public string Color
{
get
{
return GetStyleValue("Color", "black");
}
set
{
SetStyleValue("Color", value);
}
}
[TypeConverter(typeof(TextDecorationConverter)),
DescriptionAttribute("TextDecoration controls underline, overline, and linethrough. Not all renderers support all options.")]
public string TextDecoration
{
get
{
return GetStyleValue("TextDecoration", "None");
}
set
{
SetStyleValue("TextDecoration", value);
}
}
[TypeConverter(typeof(TextAlignConverter)),
DescriptionAttribute("Horizontal alignment")]
public string TextAlign
{
get
{
return GetStyleValue("TextAlign", "General");
}
set
{
SetStyleValue("TextAlign", value);
}
}
[TypeConverter(typeof(VerticalAlignConverter)),
DescriptionAttribute("Vertical alignment")]
public string VerticalAlign
{
get
{
return GetStyleValue("VerticalAlign", "Top");
}
set
{
SetStyleValue("VerticalAlign", value);
}
}
[TypeConverter(typeof(DirectionConverter)),
DescriptionAttribute("Text is either written left-to-right (LTR) or right-to-left (RTL).")]
public string Direction
{
get
{
return GetStyleValue("Direction", "LTR");
}
set
{
SetStyleValue("Direction", value);
}
}
[TypeConverter(typeof(WritingModeConverter)),
DescriptionAttribute("Text is either written horizontally (lr-tb) or vertically (tb-rl).")]
public string WritingMode
{
get
{
return GetStyleValue("WritingMode", "lr-tb");
}
set
{
SetStyleValue("WritingMode", value);
}
}
[TypeConverter(typeof(FormatConverter)),
DescriptionAttribute("Depending on type the value can be formatted.")]
public string Format
{
get
{
return GetStyleValue("Format", "");
}
set
{
SetStyleValue("Format", value);
}
}
public override string ToString()
{
string f = GetStyleValue("FontFamily", "Arial");
string s = GetStyleValue("FontSize", "10pt");
string c = GetStyleValue("Color", "Black");
return string.Format("{0}, {1}, {2}", f,s,c);
}
private string GetStyleValue(string l1, string def)
{
_subitems[_subitems.Length - 1] = l1;
return pri.GetWithList(def, _subitems);
}
private void SetStyleValue(string l1, string val)
{
_subitems[_subitems.Length - 1] = l1;
pri.SetWithList(val, _subitems);
}
#region IReportItem Members
public PropertyReportItem GetPRI()
{
return pri;
}
#endregion
}
internal class PropertyAppearanceConverter : ExpandableObjectConverter
{
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false;
}
public override bool CanConvertTo(ITypeDescriptorContext context,
System.Type destinationType)
{
if (destinationType == typeof(PropertyAppearance))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value is PropertyAppearance)
{
PropertyAppearance pf = value as PropertyAppearance;
return pf.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
internal class PropertyAppearanceUIEditor : UITypeEditor
{
internal PropertyAppearanceUIEditor()
{
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context,
IServiceProvider provider,
object value)
{
if ((context == null) || (provider == null))
return base.EditValue(context, provider, value);
// Access the Property Browser's UI display service
IWindowsFormsEditorService editorService =
(IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (editorService == null)
return base.EditValue(context, provider, value);
// Create an instance of the UI editor form
IReportItem iri = context.Instance as IReportItem;
if (iri == null)
return base.EditValue(context, provider, value);
PropertyReportItem pre = iri.GetPRI();
PropertyAppearance pf = value as PropertyAppearance;
if (pf == null)
return base.EditValue(context, provider, value);
using (SingleCtlDialog scd = new SingleCtlDialog(pre.DesignCtl, pre.Draw, pre.Nodes, SingleCtlTypeEnum.FontCtl, pf.Names))
{
// Display the UI editor dialog
if (editorService.ShowDialog(scd) == DialogResult.OK)
{
// Return the new property value from the UI editor form
return new PropertyAppearance(pre, pf.Names);
}
}
return base.EditValue(context, provider, value);
}
}
#region FontStyle
internal class FontStyleConverter : StringConverter
{
static readonly string[] StyleList = new string[] {"Normal","Italic"};
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false; // allow user to also edit the color directly
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(StyleList);
}
}
#endregion
#region FontWeight
internal class FontWeightConverter : StringConverter
{
static readonly string[] WeightList = new string[] { "Lighter", "Normal","Bold", "Bolder",
"100", "200", "300", "400", "500", "600", "700", "800", "900"};
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false; // allow user to also edit the color directly
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(WeightList);
}
}
#endregion
#region TextDecoration
internal class TextDecorationConverter : StringConverter
{
static readonly string[] TDList = new string[] { "Underline", "Overline", "LineThrough", "None"};
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false; // allow user to also edit directly
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(TDList);
}
}
#endregion
#region TextAlign
internal class TextAlignConverter : StringConverter
{
static readonly string[] TAList = new string[] { "Left", "Center", "Right", "General" };
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false; // allow user to also edit directly
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(TAList);
}
}
#endregion
#region VerticalAlign
internal class VerticalAlignConverter : StringConverter
{
static readonly string[] VAList = new string[] { "Top", "Middle", "Bottom" };
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false; // allow user to also edit directly
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(VAList);
}
}
#endregion
#region Direction
internal class DirectionConverter : StringConverter
{
static readonly string[] DirList = new string[] { "LTR", "RTL" };
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false; // allow user to also edit directly
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(DirList);
}
}
#endregion
#region WritingMode
internal class WritingModeConverter : StringConverter
{
static readonly string[] WMList = new string[] { "lr-tb", "tb-rl" };
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false; // allow user to also edit directly
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(WMList);
}
}
#endregion
#region Format
internal class FormatConverter : StringConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false; // allow user to also edit directly
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(StaticLists.FormatList);
}
}
#endregion
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// This class represents the Default COM+ binder.
//
//
namespace System {
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
//Marked serializable even though it has no state.
[Serializable]
internal class DefaultBinder : Binder
{
// This method is passed a set of methods and must choose the best
// fit. The methods all have the same number of arguments and the object
// array args. On exit, this method will choice the best fit method
// and coerce the args to match that method. By match, we mean all primitive
// arguments are exact matchs and all object arguments are exact or subclasses
// of the target. If the target OR is an interface, the object must implement
// that interface. There are a couple of exceptions
// thrown when a method cannot be returned. If no method matchs the args and
// ArgumentException is thrown. If multiple methods match the args then
// an AmbiguousMatchException is thrown.
//
// The most specific match will be selected.
//
[System.Security.SecuritySafeCritical] // auto-generated
public override MethodBase BindToMethod(
BindingFlags bindingAttr, MethodBase[] match, ref Object[] args,
ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, out Object state)
{
if (match == null || match.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match");
Contract.EndContractBlock();
MethodBase[] candidates = (MethodBase[]) match.Clone();
int i;
int j;
state = null;
#region Map named parameters to candidate parameter postions
// We are creating an paramOrder array to act as a mapping
// between the order of the args and the actual order of the
// parameters in the method. This order may differ because
// named parameters (names) may change the order. If names
// is not provided, then we assume the default mapping (0,1,...)
int[][] paramOrder = new int[candidates.Length][];
for (i = 0; i < candidates.Length; i++)
{
ParameterInfo[] par = candidates[i].GetParametersNoCopy();
// args.Length + 1 takes into account the possibility of a last paramArray that can be omitted
paramOrder[i] = new int[(par.Length > args.Length) ? par.Length : args.Length];
if (names == null)
{
// Default mapping
for (j = 0; j < args.Length; j++)
paramOrder[i][j] = j;
}
else
{
// Named parameters, reorder the mapping. If CreateParamOrder fails, it means that the method
// doesn't have a name that matchs one of the named parameters so we don't consider it any further.
if (!CreateParamOrder(paramOrder[i], par, names))
candidates[i] = null;
}
}
#endregion
Type[] paramArrayTypes = new Type[candidates.Length];
Type[] argTypes = new Type[args.Length];
#region Cache the type of the provided arguments
// object that contain a null are treated as if they were typeless (but match either object
// references or value classes). We mark this condition by placing a null in the argTypes array.
for (i = 0; i < args.Length; i++)
{
if (args[i] != null)
{
argTypes[i] = args[i].GetType();
}
}
#endregion
// Find the method that matches...
int CurIdx = 0;
bool defaultValueBinding = ((bindingAttr & BindingFlags.OptionalParamBinding) != 0);
Type paramArrayType = null;
#region Filter methods by parameter count and type
for (i = 0; i < candidates.Length; i++)
{
paramArrayType = null;
// If we have named parameters then we may have a hole in the candidates array.
if (candidates[i] == null)
continue;
// Validate the parameters.
ParameterInfo[] par = candidates[i].GetParametersNoCopy();
#region Match method by parameter count
if (par.Length == 0)
{
#region No formal parameters
if (args.Length != 0)
{
if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0)
continue;
}
// This is a valid routine so we move it up the candidates list.
paramOrder[CurIdx] = paramOrder[i];
candidates[CurIdx++] = candidates[i];
continue;
#endregion
}
else if (par.Length > args.Length)
{
#region Shortage of provided parameters
// If the number of parameters is greater than the number of args then
// we are in the situation were we may be using default values.
for (j = args.Length; j < par.Length - 1; j++)
{
if (par[j].DefaultValue == System.DBNull.Value)
break;
}
if (j != par.Length - 1)
continue;
if (par[j].DefaultValue == System.DBNull.Value)
{
if (!par[j].ParameterType.IsArray)
continue;
if (!par[j].IsDefined(typeof(ParamArrayAttribute), true))
continue;
paramArrayType = par[j].ParameterType.GetElementType();
}
#endregion
}
else if (par.Length < args.Length)
{
#region Excess provided parameters
// test for the ParamArray case
int lastArgPos = par.Length - 1;
if (!par[lastArgPos].ParameterType.IsArray)
continue;
if (!par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true))
continue;
if (paramOrder[i][lastArgPos] != lastArgPos)
continue;
paramArrayType = par[lastArgPos].ParameterType.GetElementType();
#endregion
}
else
{
#region Test for paramArray, save paramArray type
int lastArgPos = par.Length - 1;
if (par[lastArgPos].ParameterType.IsArray
&& par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true)
&& paramOrder[i][lastArgPos] == lastArgPos)
{
if (!par[lastArgPos].ParameterType.IsAssignableFrom(argTypes[lastArgPos]))
paramArrayType = par[lastArgPos].ParameterType.GetElementType();
}
#endregion
}
#endregion
Type pCls = null;
int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length;
#region Match method by parameter type
for (j = 0; j < argsToCheck; j++)
{
#region Classic argument coersion checks
// get the formal type
pCls = par[j].ParameterType;
if (pCls.IsByRef)
pCls = pCls.GetElementType();
// the type is the same
if (pCls == argTypes[paramOrder[i][j]])
continue;
// a default value is available
if (defaultValueBinding && args[paramOrder[i][j]] == Type.Missing)
continue;
// the argument was null, so it matches with everything
if (args[paramOrder[i][j]] == null)
continue;
// the type is Object, so it will match everything
if (pCls == typeof(Object))
continue;
// now do a "classic" type check
if (pCls.IsPrimitive)
{
if (argTypes[paramOrder[i][j]] == null || !CanConvertPrimitiveObjectToType(args[paramOrder[i][j]],(RuntimeType)pCls))
{
break;
}
}
else
{
if (argTypes[paramOrder[i][j]] == null)
continue;
if (!pCls.IsAssignableFrom(argTypes[paramOrder[i][j]]))
{
if (argTypes[paramOrder[i][j]].IsCOMObject)
{
if (pCls.IsInstanceOfType(args[paramOrder[i][j]]))
continue;
}
break;
}
}
#endregion
}
if (paramArrayType != null && j == par.Length - 1)
{
#region Check that excess arguments can be placed in the param array
for (; j < args.Length; j++)
{
if (paramArrayType.IsPrimitive)
{
if (argTypes[j] == null || !CanConvertPrimitiveObjectToType(args[j], (RuntimeType)paramArrayType))
break;
}
else
{
if (argTypes[j] == null)
continue;
if (!paramArrayType.IsAssignableFrom(argTypes[j]))
{
if (argTypes[j].IsCOMObject)
{
if (paramArrayType.IsInstanceOfType(args[j]))
continue;
}
break;
}
}
}
#endregion
}
#endregion
if (j == args.Length)
{
#region This is a valid routine so we move it up the candidates list
paramOrder[CurIdx] = paramOrder[i];
paramArrayTypes[CurIdx] = paramArrayType;
candidates[CurIdx++] = candidates[i];
#endregion
}
}
#endregion
// If we didn't find a method
if (CurIdx == 0)
throw new MissingMethodException(Environment.GetResourceString("MissingMember"));
if (CurIdx == 1)
{
#region Found only one method
if (names != null)
{
state = new BinderState((int[])paramOrder[0].Clone(), args.Length, paramArrayTypes[0] != null);
ReorderParams(paramOrder[0],args);
}
// If the parameters and the args are not the same length or there is a paramArray
// then we need to create a argument array.
ParameterInfo[] parms = candidates[0].GetParametersNoCopy();
if (parms.Length == args.Length)
{
if (paramArrayTypes[0] != null)
{
Object[] objs = new Object[parms.Length];
int lastPos = parms.Length - 1;
Array.Copy(args, 0, objs, 0, lastPos);
objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], 1);
((Array)objs[lastPos]).SetValue(args[lastPos], 0);
args = objs;
}
}
else if (parms.Length > args.Length)
{
Object[] objs = new Object[parms.Length];
for (i=0;i<args.Length;i++)
objs[i] = args[i];
for (;i<parms.Length - 1;i++)
objs[i] = parms[i].DefaultValue;
if (paramArrayTypes[0] != null)
objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[0], 0); // create an empty array for the
else
objs[i] = parms[i].DefaultValue;
args = objs;
}
else
{
if ((candidates[0].CallingConvention & CallingConventions.VarArgs) == 0)
{
Object[] objs = new Object[parms.Length];
int paramArrayPos = parms.Length - 1;
Array.Copy(args, 0, objs, 0, paramArrayPos);
objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], args.Length - paramArrayPos);
Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos);
args = objs;
}
}
#endregion
return candidates[0];
}
int currentMin = 0;
bool ambig = false;
for (i = 1; i < CurIdx; i++)
{
#region Walk all of the methods looking the most specific method to invoke
int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder[currentMin], paramArrayTypes[currentMin],
candidates[i], paramOrder[i], paramArrayTypes[i], argTypes, args);
if (newMin == 0)
{
ambig = true;
}
else if (newMin == 2)
{
currentMin = i;
ambig = false;
}
#endregion
}
if (ambig)
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
// Reorder (if needed)
if (names != null) {
state = new BinderState((int[])paramOrder[currentMin].Clone(), args.Length, paramArrayTypes[currentMin] != null);
ReorderParams(paramOrder[currentMin], args);
}
// If the parameters and the args are not the same length or there is a paramArray
// then we need to create a argument array.
ParameterInfo[] parameters = candidates[currentMin].GetParametersNoCopy();
if (parameters.Length == args.Length)
{
if (paramArrayTypes[currentMin] != null)
{
Object[] objs = new Object[parameters.Length];
int lastPos = parameters.Length - 1;
Array.Copy(args, 0, objs, 0, lastPos);
objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 1);
((Array)objs[lastPos]).SetValue(args[lastPos], 0);
args = objs;
}
}
else if (parameters.Length > args.Length)
{
Object[] objs = new Object[parameters.Length];
for (i=0;i<args.Length;i++)
objs[i] = args[i];
for (;i<parameters.Length - 1;i++)
objs[i] = parameters[i].DefaultValue;
if (paramArrayTypes[currentMin] != null)
{
objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 0);
}
else
{
objs[i] = parameters[i].DefaultValue;
}
args = objs;
}
else
{
if ((candidates[currentMin].CallingConvention & CallingConventions.VarArgs) == 0)
{
Object[] objs = new Object[parameters.Length];
int paramArrayPos = parameters.Length - 1;
Array.Copy(args, 0, objs, 0, paramArrayPos);
objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], args.Length - paramArrayPos);
Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos);
args = objs;
}
}
return candidates[currentMin];
}
// Given a set of fields that match the base criteria, select a field.
// if value is null then we have no way to select a field
[System.Security.SecuritySafeCritical] // auto-generated
public override FieldInfo BindToField(BindingFlags bindingAttr,FieldInfo[] match, Object value,CultureInfo cultureInfo)
{
if (match == null) {
throw new ArgumentNullException("match");
}
int i;
// Find the method that match...
int CurIdx = 0;
Type valueType = null;
FieldInfo[] candidates = (FieldInfo[]) match.Clone();
// If we are a FieldSet, then use the value's type to disambiguate
if ((bindingAttr & BindingFlags.SetField) != 0) {
valueType = value.GetType();
for (i=0;i<candidates.Length;i++) {
Type pCls = candidates[i].FieldType;
if (pCls == valueType) {
candidates[CurIdx++] = candidates[i];
continue;
}
if (value == Empty.Value) {
// the object passed in was null which would match any non primitive non value type
if (pCls.IsClass) {
candidates[CurIdx++] = candidates[i];
continue;
}
}
if (pCls == typeof(Object)) {
candidates[CurIdx++] = candidates[i];
continue;
}
if (pCls.IsPrimitive) {
if (CanConvertPrimitiveObjectToType(value,(RuntimeType)pCls)) {
candidates[CurIdx++] = candidates[i];
continue;
}
}
else {
if (pCls.IsAssignableFrom(valueType)) {
candidates[CurIdx++] = candidates[i];
continue;
}
}
}
if (CurIdx == 0)
throw new MissingFieldException(Environment.GetResourceString("MissingField"));
if (CurIdx == 1)
return candidates[0];
}
// Walk all of the methods looking the most specific method to invoke
int currentMin = 0;
bool ambig = false;
for (i=1;i<CurIdx;i++) {
int newMin = FindMostSpecificField(candidates[currentMin], candidates[i]);
if (newMin == 0)
ambig = true;
else {
if (newMin == 2) {
currentMin = i;
ambig = false;
}
}
}
if (ambig)
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
return candidates[currentMin];
}
// Given a set of methods that match the base criteria, select a method based
// upon an array of types. This method should return null if no method matchs
// the criteria.
[System.Security.SecuritySafeCritical] // auto-generated
public override MethodBase SelectMethod(BindingFlags bindingAttr,MethodBase[] match,Type[] types,ParameterModifier[] modifiers)
{
int i;
int j;
Type[] realTypes = new Type[types.Length];
for (i=0;i<types.Length;i++) {
realTypes[i] = types[i].UnderlyingSystemType;
if (!(realTypes[i] is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"types");
}
types = realTypes;
// We don't automatically jump out on exact match.
if (match == null || match.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match");
MethodBase[] candidates = (MethodBase[]) match.Clone();
// Find all the methods that can be described by the types parameter.
// Remove all of them that cannot.
int CurIdx = 0;
for (i=0;i<candidates.Length;i++) {
ParameterInfo[] par = candidates[i].GetParametersNoCopy();
if (par.Length != types.Length)
continue;
for (j=0;j<types.Length;j++) {
Type pCls = par[j].ParameterType;
if (pCls == types[j])
continue;
if (pCls == typeof(Object))
continue;
if (pCls.IsPrimitive) {
if (!(types[j].UnderlyingSystemType is RuntimeType) ||
!CanConvertPrimitive((RuntimeType)types[j].UnderlyingSystemType,(RuntimeType)pCls.UnderlyingSystemType))
break;
}
else {
if (!pCls.IsAssignableFrom(types[j]))
break;
}
}
if (j == types.Length)
candidates[CurIdx++] = candidates[i];
}
if (CurIdx == 0)
return null;
if (CurIdx == 1)
return candidates[0];
// Walk all of the methods looking the most specific method to invoke
int currentMin = 0;
bool ambig = false;
int[] paramOrder = new int[types.Length];
for (i=0;i<types.Length;i++)
paramOrder[i] = i;
for (i=1;i<CurIdx;i++) {
int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder, null, candidates[i], paramOrder, null, types, null);
if (newMin == 0)
ambig = true;
else {
if (newMin == 2) {
currentMin = i;
ambig = false;
currentMin = i;
}
}
}
if (ambig)
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
return candidates[currentMin];
}
// Given a set of properties that match the base criteria, select one.
[System.Security.SecuritySafeCritical] // auto-generated
public override PropertyInfo SelectProperty(BindingFlags bindingAttr,PropertyInfo[] match,Type returnType,
Type[] indexes,ParameterModifier[] modifiers)
{
// Allow a null indexes array. But if it is not null, every element must be non-null as well.
if (indexes != null && !Contract.ForAll(indexes, delegate(Type t) { return t != null; }))
{
Exception e; // Written this way to pass the Code Contracts style requirements.
#if FEATURE_LEGACYNETCF
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
e = new NullReferenceException();
else
#endif
e = new ArgumentNullException("indexes");
throw e;
}
if (match == null || match.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match");
Contract.EndContractBlock();
PropertyInfo[] candidates = (PropertyInfo[]) match.Clone();
int i,j = 0;
// Find all the properties that can be described by type indexes parameter
int CurIdx = 0;
int indexesLength = (indexes != null) ? indexes.Length : 0;
for (i=0;i<candidates.Length;i++) {
if (indexes != null)
{
ParameterInfo[] par = candidates[i].GetIndexParameters();
if (par.Length != indexesLength)
continue;
for (j=0;j<indexesLength;j++) {
Type pCls = par[j]. ParameterType;
// If the classes exactly match continue
if (pCls == indexes[j])
continue;
if (pCls == typeof(Object))
continue;
if (pCls.IsPrimitive) {
if (!(indexes[j].UnderlyingSystemType is RuntimeType) ||
!CanConvertPrimitive((RuntimeType)indexes[j].UnderlyingSystemType,(RuntimeType)pCls.UnderlyingSystemType))
break;
}
else {
if (!pCls.IsAssignableFrom(indexes[j]))
break;
}
}
}
if (j == indexesLength) {
if (returnType != null) {
if (candidates[i].PropertyType.IsPrimitive) {
if (!(returnType.UnderlyingSystemType is RuntimeType) ||
!CanConvertPrimitive((RuntimeType)returnType.UnderlyingSystemType,(RuntimeType)candidates[i].PropertyType.UnderlyingSystemType))
continue;
}
else {
if (!candidates[i].PropertyType.IsAssignableFrom(returnType))
continue;
}
}
candidates[CurIdx++] = candidates[i];
}
}
if (CurIdx == 0)
return null;
if (CurIdx == 1)
return candidates[0];
// Walk all of the properties looking the most specific method to invoke
int currentMin = 0;
bool ambig = false;
int[] paramOrder = new int[indexesLength];
for (i=0;i<indexesLength;i++)
paramOrder[i] = i;
for (i=1;i<CurIdx;i++) {
int newMin = FindMostSpecificType(candidates[currentMin].PropertyType, candidates[i].PropertyType,returnType);
if (newMin == 0 && indexes != null)
newMin = FindMostSpecific(candidates[currentMin].GetIndexParameters(),
paramOrder,
null,
candidates[i].GetIndexParameters(),
paramOrder,
null,
indexes,
null);
if (newMin == 0)
{
newMin = FindMostSpecificProperty(candidates[currentMin], candidates[i]);
if (newMin == 0)
ambig = true;
}
if (newMin == 2) {
ambig = false;
currentMin = i;
}
}
if (ambig)
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
return candidates[currentMin];
}
// ChangeType
// The default binder doesn't support any change type functionality.
// This is because the default is built into the low level invoke code.
public override Object ChangeType(Object value,Type type,CultureInfo cultureInfo)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ChangeType"));
}
public override void ReorderArgumentArray(ref Object[] args, Object state)
{
BinderState binderState = (BinderState)state;
ReorderParams(binderState.m_argsMap, args);
if (binderState.m_isParamArray) {
int paramArrayPos = args.Length - 1;
if (args.Length == binderState.m_originalSize)
args[paramArrayPos] = ((Object[])args[paramArrayPos])[0];
else {
// must be args.Length < state.originalSize
Object[] newArgs = new Object[args.Length];
Array.Copy(args, 0, newArgs, 0, paramArrayPos);
for (int i = paramArrayPos, j = 0; i < newArgs.Length; i++, j++) {
newArgs[i] = ((Object[])args[paramArrayPos])[j];
}
args = newArgs;
}
}
else {
if (args.Length > binderState.m_originalSize) {
Object[] newArgs = new Object[binderState.m_originalSize];
Array.Copy(args, 0, newArgs, 0, binderState.m_originalSize);
args = newArgs;
}
}
}
// Return any exact bindings that may exist. (This method is not defined on the
// Binder and is used by RuntimeType.)
public static MethodBase ExactBinding(MethodBase[] match,Type[] types,ParameterModifier[] modifiers)
{
if (match==null)
throw new ArgumentNullException("match");
Contract.EndContractBlock();
MethodBase[] aExactMatches = new MethodBase[match.Length];
int cExactMatches = 0;
for (int i=0;i<match.Length;i++) {
ParameterInfo[] par = match[i].GetParametersNoCopy();
if (par.Length == 0) {
continue;
}
int j;
for (j=0;j<types.Length;j++) {
Type pCls = par[j]. ParameterType;
// If the classes exactly match continue
if (!pCls.Equals(types[j]))
break;
}
if (j < types.Length)
continue;
// Add the exact match to the array of exact matches.
aExactMatches[cExactMatches] = match[i];
cExactMatches++;
}
if (cExactMatches == 0)
return null;
if (cExactMatches == 1)
return aExactMatches[0];
return FindMostDerivedNewSlotMeth(aExactMatches, cExactMatches);
}
// Return any exact bindings that may exist. (This method is not defined on the
// Binder and is used by RuntimeType.)
public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match,Type returnType,Type[] types,ParameterModifier[] modifiers)
{
if (match==null)
throw new ArgumentNullException("match");
Contract.EndContractBlock();
PropertyInfo bestMatch = null;
int typesLength = (types != null) ? types.Length : 0;
for (int i=0;i<match.Length;i++) {
ParameterInfo[] par = match[i].GetIndexParameters();
int j;
for (j=0;j<typesLength;j++) {
Type pCls = par[j].ParameterType;
// If the classes exactly match continue
if (pCls != types[j])
break;
}
if (j < typesLength)
continue;
if (returnType != null && returnType != match[i].PropertyType)
continue;
if (bestMatch != null)
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
bestMatch = match[i];
}
return bestMatch;
}
private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type paramArrayType1,
ParameterInfo[] p2, int[] paramOrder2, Type paramArrayType2,
Type[] types, Object[] args)
{
// A method using params is always less specific than one not using params
if (paramArrayType1 != null && paramArrayType2 == null) return 2;
if (paramArrayType2 != null && paramArrayType1 == null) return 1;
// now either p1 and p2 both use params or neither does.
bool p1Less = false;
bool p2Less = false;
for (int i = 0; i < types.Length; i++)
{
if (args != null && args[i] == Type.Missing)
continue;
Type c1, c2;
// If a param array is present, then either
// the user re-ordered the parameters in which case
// the argument to the param array is either an array
// in which case the params is conceptually ignored and so paramArrayType1 == null
// or the argument to the param array is a single element
// in which case paramOrder[i] == p1.Length - 1 for that element
// or the user did not re-order the parameters in which case
// the paramOrder array could contain indexes larger than p.Length - 1 (see VSW 577286)
// so any index >= p.Length - 1 is being put in the param array
if (paramArrayType1 != null && paramOrder1[i] >= p1.Length - 1)
c1 = paramArrayType1;
else
c1 = p1[paramOrder1[i]].ParameterType;
if (paramArrayType2 != null && paramOrder2[i] >= p2.Length - 1)
c2 = paramArrayType2;
else
c2 = p2[paramOrder2[i]].ParameterType;
if (c1 == c2) continue;
switch (FindMostSpecificType(c1, c2, types[i])) {
case 0: return 0;
case 1: p1Less = true; break;
case 2: p2Less = true; break;
}
}
// Two way p1Less and p2Less can be equal. All the arguments are the
// same they both equal false, otherwise there were things that both
// were the most specific type on....
if (p1Less == p2Less)
{
// if we cannot tell which is a better match based on parameter types (p1Less == p2Less),
// let's see which one has the most matches without using the params array (the longer one wins).
if (!p1Less && args != null)
{
if (p1.Length > p2.Length)
{
return 1;
}
else if (p2.Length > p1.Length)
{
return 2;
}
}
return 0;
}
else
{
return (p1Less == true) ? 1 : 2;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
private static int FindMostSpecificType(Type c1, Type c2, Type t)
{
// If the two types are exact move on...
if (c1 == c2)
return 0;
if (c1 == t)
return 1;
if (c2 == t)
return 2;
bool c1FromC2;
bool c2FromC1;
if (c1.IsByRef || c2.IsByRef)
{
if (c1.IsByRef && c2.IsByRef)
{
c1 = c1.GetElementType();
c2 = c2.GetElementType();
}
else if (c1.IsByRef)
{
if (c1.GetElementType() == c2)
return 2;
c1 = c1.GetElementType();
}
else
{
if (c2.GetElementType() == c1)
return 1;
c2 = c2.GetElementType();
}
}
if (c1.IsPrimitive && c2.IsPrimitive)
{
c1FromC2 = CanConvertPrimitive((RuntimeType)c2, (RuntimeType)c1);
c2FromC1 = CanConvertPrimitive((RuntimeType)c1, (RuntimeType)c2);
}
else
{
c1FromC2 = c1.IsAssignableFrom(c2);
c2FromC1 = c2.IsAssignableFrom(c1);
}
if (c1FromC2 == c2FromC1)
return 0;
if (c1FromC2)
{
return 2;
}
else
{
return 1;
}
}
private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type paramArrayType1,
MethodBase m2, int[] paramOrder2, Type paramArrayType2,
Type[] types, Object[] args)
{
// Find the most specific method based on the parameters.
int res = FindMostSpecific(m1.GetParametersNoCopy(), paramOrder1, paramArrayType1,
m2.GetParametersNoCopy(), paramOrder2, paramArrayType2, types, args);
// If the match was not ambigous then return the result.
if (res != 0)
return res;
// Check to see if the methods have the exact same name and signature.
if (CompareMethodSigAndName(m1, m2))
{
// Determine the depth of the declaring types for both methods.
int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType);
int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType);
// The most derived method is the most specific one.
if (hierarchyDepth1 == hierarchyDepth2)
{
return 0;
}
else if (hierarchyDepth1 < hierarchyDepth2)
{
return 2;
}
else
{
return 1;
}
}
// The match is ambigous.
return 0;
}
private static int FindMostSpecificField(FieldInfo cur1,FieldInfo cur2)
{
// Check to see if the fields have the same name.
if (cur1.Name == cur2.Name)
{
int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType);
int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType);
if (hierarchyDepth1 == hierarchyDepth2) {
Contract.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2");
return 0;
}
else if (hierarchyDepth1 < hierarchyDepth2)
return 2;
else
return 1;
}
// The match is ambigous.
return 0;
}
private static int FindMostSpecificProperty(PropertyInfo cur1,PropertyInfo cur2)
{
// Check to see if the fields have the same name.
if (cur1.Name == cur2.Name)
{
int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType);
int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType);
if (hierarchyDepth1 == hierarchyDepth2) {
return 0;
}
else if (hierarchyDepth1 < hierarchyDepth2)
return 2;
else
return 1;
}
// The match is ambigous.
return 0;
}
internal static bool CompareMethodSigAndName(MethodBase m1, MethodBase m2)
{
ParameterInfo[] params1 = m1.GetParametersNoCopy();
ParameterInfo[] params2 = m2.GetParametersNoCopy();
if (params1.Length != params2.Length)
return false;
int numParams = params1.Length;
for (int i = 0; i < numParams; i++)
{
if (params1[i].ParameterType != params2[i].ParameterType)
return false;
}
return true;
}
internal static int GetHierarchyDepth(Type t)
{
int depth = 0;
Type currentType = t;
do
{
depth++;
currentType = currentType.BaseType;
} while (currentType != null);
return depth;
}
internal static MethodBase FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches)
{
int deepestHierarchy = 0;
MethodBase methWithDeepestHierarchy = null;
for (int i = 0; i < cMatches; i++)
{
// Calculate the depth of the hierarchy of the declaring type of the
// current method.
int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType);
// The two methods have the same name, signature, and hierarchy depth.
// This can only happen if at least one is vararg or generic.
if (currentHierarchyDepth == deepestHierarchy)
{
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
}
// Check to see if this method is on the most derived class.
if (currentHierarchyDepth > deepestHierarchy)
{
deepestHierarchy = currentHierarchyDepth;
methWithDeepestHierarchy = match[i];
}
}
return methWithDeepestHierarchy;
}
// CanConvertPrimitive
// This will determine if the source can be converted to the target type
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool CanConvertPrimitive(RuntimeType source,RuntimeType target);
// CanConvertPrimitiveObjectToType
// This method will determine if the primitive object can be converted
// to a type.
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern bool CanConvertPrimitiveObjectToType(Object source,RuntimeType type);
// This method will sort the vars array into the mapping order stored
// in the paramOrder array.
private static void ReorderParams(int[] paramOrder,Object[] vars)
{
object[] varsCopy = new object[vars.Length];
for (int i = 0; i < vars.Length; i ++)
varsCopy[i] = vars[i];
for (int i = 0; i < vars.Length; i ++)
vars[i] = varsCopy[paramOrder[i]];
}
// This method will create the mapping between the Parameters and the underlying
// data based upon the names array. The names array is stored in the same order
// as the values and maps to the parameters of the method. We store the mapping
// from the parameters to the names in the paramOrder array. All parameters that
// don't have matching names are then stored in the array in order.
private static bool CreateParamOrder(int[] paramOrder,ParameterInfo[] pars,String[] names)
{
bool[] used = new bool[pars.Length];
// Mark which parameters have not been found in the names list
for (int i=0;i<pars.Length;i++)
paramOrder[i] = -1;
// Find the parameters with names.
for (int i=0;i<names.Length;i++) {
int j;
for (j=0;j<pars.Length;j++) {
if (names[i].Equals(pars[j].Name)) {
paramOrder[j] = i;
used[i] = true;
break;
}
}
// This is an error condition. The name was not found. This
// method must not match what we sent.
if (j == pars.Length)
return false;
}
// Now we fill in the holes with the parameters that are unused.
int pos = 0;
for (int i=0;i<pars.Length;i++) {
if (paramOrder[i] == -1) {
for (;pos<pars.Length;pos++) {
if (!used[pos]) {
paramOrder[i] = pos;
pos++;
break;
}
}
}
}
return true;
}
internal class BinderState {
internal int[] m_argsMap;
internal int m_originalSize;
internal bool m_isParamArray;
internal BinderState(int[] argsMap, int originalSize, bool isParamArray) {
m_argsMap = argsMap;
m_originalSize = originalSize;
m_isParamArray = isParamArray;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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.Linq;
using System.Net;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
namespace Aurora.ScriptEngine.AuroraDotNetEngine
{
/// <summary>
/// This manages app domains and controls what app domains are created/destroyed
/// </summary>
public class AppDomainManager
{
//private static readonly ILog MainConsole.Instance = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly List<AppDomainStructure> appDomains =
new List<AppDomainStructure>();
private readonly object m_appDomainLock = new object();
private readonly ScriptEngine m_scriptEngine;
private int AppDomainNameCount;
private AppDomainStructure currentAD;
private bool loadAllScriptsIntoCurrentDomain;
private bool loadAllScriptsIntoOneDomain = true;
private string m_PermissionLevel = "Internet";
private int maxScriptsPerAppDomain = 1;
public AppDomainManager(ScriptEngine scriptEngine)
{
m_scriptEngine = scriptEngine;
ReadConfig();
}
public string PermissionLevel
{
get { return m_PermissionLevel; }
}
public int NumberOfAppDomains
{
get { return appDomains.Count; }
}
// Internal list of all AppDomains
public void ReadConfig()
{
maxScriptsPerAppDomain = m_scriptEngine.ScriptConfigSource.GetInt(
"ScriptsPerAppDomain", 1);
m_PermissionLevel = m_scriptEngine.ScriptConfigSource.GetString(
"AppDomainPermissions", "Internet");
loadAllScriptsIntoCurrentDomain =
m_scriptEngine.ScriptConfigSource.GetBoolean("LoadAllScriptsIntoCurrentAppDomain", false);
loadAllScriptsIntoOneDomain = m_scriptEngine.ScriptConfigSource.GetBoolean(
"LoadAllScriptsIntoOneAppDomain", true);
}
// Find a free AppDomain, creating one if necessary
private AppDomainStructure GetFreeAppDomain()
{
if (loadAllScriptsIntoCurrentDomain)
{
if (currentAD != null)
return currentAD;
else
{
lock (m_appDomainLock)
{
currentAD = new AppDomainStructure { CurrentAppDomain = AppDomain.CurrentDomain };
AppDomain.CurrentDomain.AssemblyResolve += m_scriptEngine.AssemblyResolver.OnAssemblyResolve;
return currentAD;
}
}
}
lock (m_appDomainLock)
{
if (loadAllScriptsIntoOneDomain)
{
if (currentAD == null)
{
// Create a new current AppDomain
currentAD = new AppDomainStructure { CurrentAppDomain = PrepareNewAppDomain() };
}
}
else
{
// Current full?
if (currentAD != null &&
currentAD.ScriptsLoaded >= maxScriptsPerAppDomain)
{
// Add it to AppDomains list and empty current
lock (m_appDomainLock)
{
appDomains.Add(currentAD);
}
currentAD = null;
}
// No current
if (currentAD == null)
{
// Create a new current AppDomain
currentAD = new AppDomainStructure { CurrentAppDomain = PrepareNewAppDomain() };
}
}
}
return currentAD;
}
// Create and prepare a new AppDomain for scripts
private AppDomain PrepareNewAppDomain()
{
// Create and prepare a new AppDomain
AppDomainNameCount++;
// Construct and initialize settings for a second AppDomain.
AppDomainSetup ads = new AppDomainSetup
{
ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
DisallowBindingRedirects = true,
DisallowCodeDownload = true,
LoaderOptimization = LoaderOptimization.MultiDomainHost,
ShadowCopyFiles = "false",
ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
};
// Disable shadowing
AppDomain AD = CreateRestrictedDomain(m_PermissionLevel,
"ScriptAppDomain_" + AppDomainNameCount, ads);
AD.AssemblyResolve += m_scriptEngine.AssemblyResolver.OnAssemblyResolve;
// Return the new AppDomain
return AD;
}
/// From MRMModule.cs by Adam Frisby
/// <summary>
/// Create an AppDomain that contains policy restricting code to execute
/// with only the permissions granted by a named permission set
/// </summary>
/// <param name = "permissionSetName">name of the permission set to restrict to</param>
/// <param name = "appDomainName">'friendly' name of the appdomain to be created</param>
/// <exception cref = "ArgumentNullException">
/// if <paramref name = "permissionSetName" /> is null
/// </exception>
/// <exception cref = "ArgumentOutOfRangeException">
/// if <paramref name = "permissionSetName" /> is empty
/// </exception>
/// <returns>AppDomain with a restricted security policy</returns>
/// <remarks>
/// Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
/// Valid permissionSetName values are:
/// * FullTrust
/// * SkipVerification
/// * Execution
/// * Nothing
/// * LocalIntranet
/// * Internet
/// * Everything
/// </remarks>
public AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName, AppDomainSetup ads)
{
if (permissionSetName == null)
throw new ArgumentNullException("permissionSetName");
if (permissionSetName.Length == 0)
throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
"Cannot have an empty permission set name");
// Default to all code getting everything
PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);
AppDomain restrictedDomain = null;
#if NET_4_0
SecurityZone zone = SecurityZone.MyComputer;
try
{
zone = (SecurityZone)Enum.Parse(typeof(SecurityZone), permissionSetName);
}
catch
{
zone = SecurityZone.MyComputer;
}
Evidence ev = new Evidence();
ev.AddHostEvidence(new Zone(zone));
setIntersection = SecurityManager.GetStandardSandbox(ev);
setIntersection.AddPermission(new System.Net.SocketPermission(PermissionState.Unrestricted));
setIntersection.AddPermission(new System.Net.WebPermission(PermissionState.Unrestricted));
setIntersection.AddPermission(new System.Security.Permissions.SecurityPermission(PermissionState.Unrestricted));
// create an AppDomain where this policy will be in effect
restrictedDomain = AppDomain.CreateDomain(appDomainName, ev, ads, setIntersection, null);
#else
PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
UnionCodeGroup policyRoot = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);
bool foundName = false;
// iterate over each policy level
IEnumerator levelEnumerator = SecurityManager.PolicyHierarchy();
while (levelEnumerator.MoveNext())
{
PolicyLevel level = levelEnumerator.Current as PolicyLevel;
// if this level has defined a named permission set with the
// given name, then intersect it with what we've retrieved
// from all the previous levels
if (level != null)
{
PermissionSet levelSet = level.GetNamedPermissionSet(permissionSetName);
if (levelSet != null)
{
foundName = true;
if (setIntersection != null)
setIntersection = setIntersection.Intersect(levelSet);
}
}
}
// Intersect() can return null for an empty set, so convert that
// to an empty set object. Also return an empty set if we didn't find
// the named permission set we were looking for
if (setIntersection == null || !foundName)
setIntersection = new PermissionSet(PermissionState.None);
else
setIntersection = new NamedPermissionSet(permissionSetName, setIntersection);
// if no named permission sets were found, return an empty set,
// otherwise return the set that was found
setIntersection.AddPermission(new SocketPermission(PermissionState.Unrestricted));
setIntersection.AddPermission(new WebPermission(PermissionState.Unrestricted));
setIntersection.AddPermission(new SecurityPermission(PermissionState.Unrestricted));
PolicyStatement permissions = new PolicyStatement(setIntersection);
policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));
// create an AppDomain policy level for the policy tree
PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();
appDomainLevel.RootCodeGroup = policyRoot;
// create an AppDomain where this policy will be in effect
restrictedDomain = AppDomain.CreateDomain(appDomainName, null, ads);
restrictedDomain.SetAppDomainPolicy(appDomainLevel);
#endif
return restrictedDomain;
}
// Unload appdomains that are full and have only dead scripts
private void UnloadAppDomains()
{
lock (m_appDomainLock)
{
// Go through all
#if (!ISWIN)
foreach (AppDomainStructure ads in appDomains)
{
if (ads.ScriptsLoaded <= ads.ScriptsWaitingUnload)
{
// Remove from internal list
appDomains.Remove(ads);
try
{
// Unload
if (ads != null) AppDomain.Unload(ads.CurrentAppDomain);
}
catch
{
}
if (ads.CurrentAppDomain == currentAD.CurrentAppDomain)
currentAD = null;
ads.CurrentAppDomain = null;
}
}
#else
foreach (AppDomainStructure ads in appDomains.Where(ads => ads.ScriptsLoaded <= ads.ScriptsWaitingUnload))
{
// Remove from internal list
appDomains.Remove(ads);
try
{
// Unload
if (ads != null) AppDomain.Unload(ads.CurrentAppDomain);
}
catch
{
}
if (ads.CurrentAppDomain == currentAD.CurrentAppDomain)
currentAD = null;
ads.CurrentAppDomain = null;
}
#endif
if (currentAD != null)
{
if (currentAD.ScriptsLoaded <= currentAD.ScriptsWaitingUnload)
{
if (currentAD.CurrentAppDomain.Id != AppDomain.CurrentDomain.Id)
//Don't kill the current app domain!
{
try
{
// Unload
AppDomain.Unload(currentAD.CurrentAppDomain);
}
catch
{
}
currentAD.CurrentAppDomain = null;
currentAD = null;
}
}
}
}
}
public IScript LoadScript(string FileName, string TypeName, out AppDomain ad)
{
// Find next available AppDomain to put it in
AppDomainStructure FreeAppDomain = GetFreeAppDomain();
IScript mbrt = (IScript)
FreeAppDomain.CurrentAppDomain.CreateInstanceFromAndUnwrap(
FileName, TypeName);
FreeAppDomain.ScriptsLoaded++;
ad = FreeAppDomain.CurrentAppDomain;
return mbrt;
}
// Increase "dead script" counter for an AppDomain
public void UnloadScriptAppDomain(AppDomain ad)
{
lock (m_appDomainLock)
{
// Check if it is current AppDomain
if (currentAD.CurrentAppDomain == ad)
{
// Yes - increase
currentAD.ScriptsWaitingUnload++;
}
else
{
// Lopp through all AppDomains
#if (!ISWIN)
foreach (AppDomainStructure ads in appDomains)
{
if (ads.CurrentAppDomain == ad)
{
// Found it
ads.ScriptsWaitingUnload++;
break;
}
}
#else
foreach (AppDomainStructure ads in appDomains.Where(ads => ads.CurrentAppDomain == ad))
{
// Found it
ads.ScriptsWaitingUnload++;
break;
}
#endif
}
}
UnloadAppDomains(); // Outsite lock, has its own GetLock
}
#region Nested type: AppDomainStructure
private class AppDomainStructure
{
// The AppDomain itself
public AppDomain CurrentAppDomain;
// Number of scripts loaded into AppDomain
public int ScriptsLoaded;
// Number of dead scripts
public int ScriptsWaitingUnload;
}
#endregion
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.Management.Automation;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models;
namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
/// <summary>
/// Updates Azure Site Recovery Recovery Plan object in memory.
/// </summary>
[Cmdlet(
VerbsData.Edit,
"AzureRmRecoveryServicesAsrRecoveryPlan",
DefaultParameterSetName = ASRParameterSets.AppendGroup,
SupportsShouldProcess = true)]
[Alias(
"Edit-ASRRP",
"Edit-ASRRecoveryPlan")]
[OutputType(typeof(ASRRecoveryPlan))]
public class EditAzureRmRecoveryServicesAsrRecoveryPlan : SiteRecoveryCmdletBase
{
/// <summary>
/// Gets or sets Name of the Recovery Plan.
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true)]
[ValidateNotNullOrEmpty]
[Alias("RecoveryPlan")]
public ASRRecoveryPlan InputObject { get; set; }
/// <summary>
/// Gets or sets switch parameter
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.AppendGroup,
Mandatory = true)]
public SwitchParameter AppendGroup { get; set; }
/// <summary>
/// Gets or sets switch parameter
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.RemoveGroup,
Mandatory = true)]
public ASRRecoveryPlanGroup RemoveGroup { get; set; }
/// <summary>
/// Gets or sets group
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.AddReplicationProtectedItems,
Mandatory = true)]
[Parameter(
ParameterSetName = ASRParameterSets.RemoveReplicationProtectedItems,
Mandatory = true)]
public ASRRecoveryPlanGroup Group { get; set; }
/// <summary>
/// Gets or sets switch parameter
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.AddReplicationProtectedItems,
Mandatory = true)]
[Alias("AddProtectedItems")]
public ASRReplicationProtectedItem[] AddProtectedItem { get; set; }
/// <summary>
/// Gets or sets switch parameter
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.RemoveReplicationProtectedItems,
Mandatory = true)]
[Alias("RemoveProtectedItems")]
public ASRReplicationProtectedItem[] RemoveProtectedItem { get; set; }
/// <summary>
/// ProcessRecord of the command.
/// </summary>
public override void ExecuteSiteRecoveryCmdlet()
{
base.ExecuteSiteRecoveryCmdlet();
if (this.ShouldProcess(
this.InputObject.FriendlyName,
VerbsData.Edit))
{
ASRRecoveryPlanGroup tempGroup;
switch (this.ParameterSetName)
{
case ASRParameterSets.AppendGroup:
var recoveryPlanGroup = new RecoveryPlanGroup
{
GroupType = RecoveryPlanGroupType.Boot,
ReplicationProtectedItems = new List<RecoveryPlanProtectedItem>(),
StartGroupActions = new List<RecoveryPlanAction>(),
EndGroupActions = new List<RecoveryPlanAction>()
};
this.InputObject.Groups.Add(
new ASRRecoveryPlanGroup(
"Group " + (this.InputObject.Groups.Count - 1),
recoveryPlanGroup));
break;
case ASRParameterSets.RemoveGroup:
tempGroup = this.InputObject.Groups.FirstOrDefault(
g => string.Compare(
g.Name,
this.RemoveGroup.Name,
StringComparison.OrdinalIgnoreCase) ==
0);
if (tempGroup != null)
{
this.InputObject.Groups.Remove(tempGroup);
this.InputObject = this.InputObject.RefreshASRRecoveryPlanGroupNames();
}
else
{
throw new PSArgumentException(
string.Format(
Resources.GroupNotFoundInRecoveryPlan,
this.RemoveGroup.Name,
this.InputObject.FriendlyName));
}
break;
case ASRParameterSets.AddReplicationProtectedItems:
foreach (var rpi in this.AddProtectedItem)
{
var fabricName = Utilities.GetValueFromArmId(
rpi.ID,
ARMResourceTypeConstants.ReplicationFabrics);
var replicationProtectedItemResponse = this.RecoveryServicesClient
.GetAzureSiteRecoveryReplicationProtectedItem(
fabricName,
Utilities.GetValueFromArmId(
rpi.ID,
ARMResourceTypeConstants.ReplicationProtectionContainers),
rpi.Name);
tempGroup = this.InputObject.Groups.FirstOrDefault(
g => string.Compare(
g.Name,
this.Group.Name,
StringComparison.OrdinalIgnoreCase) ==
0);
if (tempGroup != null)
{
foreach (var gp in this.InputObject.Groups)
{
if (gp.ReplicationProtectedItems == null)
continue;
if (gp.ReplicationProtectedItems.Any(
pi => string.Compare(
pi.Id,
replicationProtectedItemResponse.Id,
StringComparison.OrdinalIgnoreCase) ==
0))
{
throw new PSArgumentException(
string.Format(
Resources.VMAlreadyPartOfGroup,
rpi.FriendlyName,
gp.Name,
this.InputObject.FriendlyName));
}
}
this.InputObject.Groups[this.InputObject.Groups.IndexOf(tempGroup)]
.ReplicationProtectedItems
.Add(replicationProtectedItemResponse);
}
else
{
throw new PSArgumentException(
string.Format(
Resources.GroupNotFoundInRecoveryPlan,
this.Group.Name,
this.InputObject.FriendlyName));
}
}
break;
case ASRParameterSets.RemoveReplicationProtectedItems:
foreach (var rpi in this.RemoveProtectedItem)
{
var fabricName = Utilities.GetValueFromArmId(
rpi.ID,
ARMResourceTypeConstants.ReplicationFabrics);
tempGroup = this.InputObject.Groups.FirstOrDefault(
g => string.Compare(
g.Name,
this.Group.Name,
StringComparison.OrdinalIgnoreCase) ==
0);
if (tempGroup != null)
{
var ReplicationProtectedItem = this.InputObject
.Groups[this.InputObject.Groups.IndexOf(tempGroup)]
.ReplicationProtectedItems.FirstOrDefault(
pi => string.Compare(
pi.Id,
rpi.ID,
StringComparison.OrdinalIgnoreCase) ==
0);
if (ReplicationProtectedItem != null)
{
this.InputObject
.Groups[this.InputObject.Groups.IndexOf(tempGroup)]
.ReplicationProtectedItems.Remove(ReplicationProtectedItem);
}
else
{
throw new PSArgumentException(
string.Format(
Resources.VMNotFoundInGroup,
rpi.FriendlyName,
this.Group.Name,
this.InputObject.FriendlyName));
}
}
else
{
throw new PSArgumentException(
string.Format(
Resources.GroupNotFoundInRecoveryPlan,
this.Group.Name,
this.InputObject.FriendlyName));
}
}
break;
}
;
this.WriteObject(this.InputObject);
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnTipoEvento class.
/// </summary>
[Serializable]
public partial class PnTipoEventoCollection : ActiveList<PnTipoEvento, PnTipoEventoCollection>
{
public PnTipoEventoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnTipoEventoCollection</returns>
public PnTipoEventoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnTipoEvento o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_tipo_evento table.
/// </summary>
[Serializable]
public partial class PnTipoEvento : ActiveRecord<PnTipoEvento>, IActiveRecord
{
#region .ctors and Default Settings
public PnTipoEvento()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnTipoEvento(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnTipoEvento(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnTipoEvento(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_tipo_evento", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdTipoEvento = new TableSchema.TableColumn(schema);
colvarIdTipoEvento.ColumnName = "id_tipo_evento";
colvarIdTipoEvento.DataType = DbType.Int32;
colvarIdTipoEvento.MaxLength = 0;
colvarIdTipoEvento.AutoIncrement = true;
colvarIdTipoEvento.IsNullable = false;
colvarIdTipoEvento.IsPrimaryKey = true;
colvarIdTipoEvento.IsForeignKey = false;
colvarIdTipoEvento.IsReadOnly = false;
colvarIdTipoEvento.DefaultSetting = @"";
colvarIdTipoEvento.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdTipoEvento);
TableSchema.TableColumn colvarTipoEvento = new TableSchema.TableColumn(schema);
colvarTipoEvento.ColumnName = "tipo_evento";
colvarTipoEvento.DataType = DbType.AnsiString;
colvarTipoEvento.MaxLength = -1;
colvarTipoEvento.AutoIncrement = false;
colvarTipoEvento.IsNullable = true;
colvarTipoEvento.IsPrimaryKey = false;
colvarTipoEvento.IsForeignKey = false;
colvarTipoEvento.IsReadOnly = false;
colvarTipoEvento.DefaultSetting = @"";
colvarTipoEvento.ForeignKeyTableName = "";
schema.Columns.Add(colvarTipoEvento);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_tipo_evento",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdTipoEvento")]
[Bindable(true)]
public int IdTipoEvento
{
get { return GetColumnValue<int>(Columns.IdTipoEvento); }
set { SetColumnValue(Columns.IdTipoEvento, value); }
}
[XmlAttribute("TipoEvento")]
[Bindable(true)]
public string TipoEvento
{
get { return GetColumnValue<string>(Columns.TipoEvento); }
set { SetColumnValue(Columns.TipoEvento, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varTipoEvento)
{
PnTipoEvento item = new PnTipoEvento();
item.TipoEvento = varTipoEvento;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdTipoEvento,string varTipoEvento)
{
PnTipoEvento item = new PnTipoEvento();
item.IdTipoEvento = varIdTipoEvento;
item.TipoEvento = varTipoEvento;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdTipoEventoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn TipoEventoColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdTipoEvento = @"id_tipo_evento";
public static string TipoEvento = @"tipo_evento";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
namespace System.Runtime.InteropServices.WindowsRuntime
{
/// <summary><p>Provides factory methods to construct WinRT-compatible representations of asynchronous operations.</p>
/// <p>The factory methods take as inputs functions (delegates) that provide managed Task objects;
/// Different factory methods return different sub-interfaces of <code>Windows.Foundation.IAyncInfo</code>.
/// When an asynchronous operation created by this factory is actually started (by calling <code>Start()</code>),
/// the specified <code>Task</code>-provider delegate will be invoked to create the <code>Task</code> that will
/// be wrapped by the to-WinRT adapter.</p> </summary>
[CLSCompliant(false)]
public static class AsyncInfo
{
#region Factory methods for creating "normal" IAsyncInfo instances backed by a Task created by a pastProvider delegate
/// <summary>
/// Creates and starts an <see cref="IAsyncAction"/> instance from a function that generates
/// a <see cref="System.Threading.Tasks.Task"/>.
/// Use this overload if your task supports cancellation in order to hook-up the <code>Cancel</code>
/// mechanism exposed by the created asynchronous action and the cancellation of your task.</summary>
/// <param name="taskProvider">The function to invoke to create the task when the IAsyncInfo is started.
/// The function is passed a <see cref="System.Threading.CancellationToken"/> that the task may monitor
/// to be notified of a cancellation request;
/// you may ignore the <code>CancellationToken</code> if your task does not support cancellation.</param>
/// <returns>An unstarted <see cref="IAsyncAction"/> instance. </returns>
public static IAsyncAction Run(Func<CancellationToken, Task> taskProvider)
{
if (taskProvider == null)
throw new ArgumentNullException(nameof(taskProvider));
return new TaskToAsyncActionAdapter(taskProvider);
}
/// <summary>
/// Creates and starts an <see cref="IAsyncActionWithProgress{TProgress}"/> instance from a function
/// that generates a <see cref="System.Threading.Tasks.Task"/>.
/// Use this overload if your task supports cancellation and progress monitoring is order to:
/// (1) hook-up the <code>Cancel</code> mechanism of the created asynchronous action and the cancellation of your task,
/// and (2) hook-up the <code>Progress</code> update delegate exposed by the created async action and the progress updates
/// published by your task.</summary>
/// <param name="taskProvider">The function to invoke to create the task when the IAsyncInfo is started.
/// The function is passed a <see cref="System.Threading.CancellationToken"/> that the task may monitor
/// to be notified of a cancellation request;
/// you may ignore the <code>CancellationToken</code> if your task does not support cancellation.
/// It is also passed a <see cref="System.IProgress{TProgress}"/> instance to which progress updates may be published;
/// you may ignore the <code>IProgress</code> if your task does not support progress reporting.</param>
/// <returns>An unstarted <see cref="IAsyncActionWithProgress{TProgress}"/> instance.</returns>
public static IAsyncActionWithProgress<TProgress> Run<TProgress>(Func<CancellationToken, IProgress<TProgress>, Task> taskProvider)
{
if (taskProvider == null)
throw new ArgumentNullException(nameof(taskProvider));
return new TaskToAsyncActionWithProgressAdapter<TProgress>(taskProvider);
}
/// <summary>
/// Creates and starts an <see cref="IAsyncOperation{TResult}"/> instance from a function
/// that generates a <see cref="System.Threading.Tasks.Task{TResult}"/>.
/// Use this overload if your task supports cancellation in order to hook-up the <code>Cancel</code>
/// mechanism exposed by the created asynchronous operation and the cancellation of your task.</summary>
/// <param name="taskProvider">The function to invoke to create the task when the IAsyncInfo is started.
/// The function is passed a <see cref="System.Threading.CancellationToken"/> that the task may monitor
/// to be notified of a cancellation request;
/// you may ignore the <code>CancellationToken</code> if your task does not support cancellation.</param>
/// <returns>An unstarted <see cref="IAsyncOperation{TResult}"/> instance.</returns>
public static IAsyncOperation<TResult> Run<TResult>(Func<CancellationToken, Task<TResult>> taskProvider)
{
// This is only internal to reduce the number of public overloads.
// Code execution flows through this method when the method above is called. We can always make this public.
if (taskProvider == null)
throw new ArgumentNullException(nameof(taskProvider));
return new TaskToAsyncOperationAdapter<TResult>(taskProvider);
}
/// <summary>
/// Creates and starts an <see cref="IAsyncOperationWithProgress{TResult, TProgress}"/> instance
/// from a function that generates a <see cref="System.Threading.Tasks.Task{TResult}"/>.<br />
/// Use this overload if your task supports cancellation and progress monitoring is order to:
/// (1) hook-up the <code>Cancel</code> mechanism of the created asynchronous operation and the cancellation of your task,
/// and (2) hook-up the <code>Progress</code> update delegate exposed by the created async operation and the progress
/// updates published by your task.</summary>
/// <typeparam name="TResult">The result type of the task.</typeparam>
/// <typeparam name="TProgress">The type used for progress notifications.</typeparam>
/// <param name="taskProvider">The function to invoke to create the task when the IAsyncOperationWithProgress is started.<br />
/// The function is passed a <see cref="System.Threading.CancellationToken"/> that the task may monitor
/// to be notified of a cancellation request;
/// you may ignore the <code>CancellationToken</code> if your task does not support cancellation.
/// It is also passed a <see cref="System.IProgress{TProgress}"/> instance to which progress updates may be published;
/// you may ignore the <code>IProgress</code> if your task does not support progress reporting.</param>
/// <returns>An unstarted <see cref="IAsyncOperationWithProgress{TResult, TProgress}"/> instance.</returns>
public static IAsyncOperationWithProgress<TResult, TProgress> Run<TResult, TProgress>(
Func<CancellationToken, IProgress<TProgress>, Task<TResult>> taskProvider)
{
if (taskProvider == null)
throw new ArgumentNullException(nameof(taskProvider));
return new TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>(taskProvider);
}
#endregion Factory methods for creating "normal" IAsyncInfo instances backed by a Task created by a pastProvider delegate
#region Factory methods for creating IAsyncInfo instances that have already completed synchronously
internal static IAsyncAction CreateCompletedAction()
{
var asyncInfo = new TaskToAsyncActionAdapter(isCanceled: false);
return asyncInfo;
}
internal static IAsyncActionWithProgress<TProgress> CreateCompletedAction<TProgress>()
{
var asyncInfo = new TaskToAsyncActionWithProgressAdapter<TProgress>(isCanceled: false);
return asyncInfo;
}
internal static IAsyncOperation<TResult> CreateCompletedOperation<TResult>(TResult synchronousResult)
{
var asyncInfo = new TaskToAsyncOperationAdapter<TResult>(synchronousResult);
return asyncInfo;
}
internal static IAsyncOperationWithProgress<TResult, TProgress> CreateCompletedOperation<TResult, TProgress>(TResult synchronousResult)
{
var asyncInfo = new TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>(synchronousResult);
return asyncInfo;
}
#endregion Factory methods for creating IAsyncInfo instances that have already completed synchronously
#region Factory methods for creating IAsyncInfo instances that have already completed synchronously with an error
internal static IAsyncAction CreateFaultedAction(Exception error)
{
if (error == null)
throw new ArgumentNullException(nameof(error));
var asyncInfo = new TaskToAsyncActionAdapter(isCanceled: false);
asyncInfo.DangerousSetError(error);
Debug.Assert(asyncInfo.Status == AsyncStatus.Error);
return asyncInfo;
}
internal static IAsyncActionWithProgress<TProgress> CreateFaultedAction<TProgress>(Exception error)
{
if (error == null)
throw new ArgumentNullException(nameof(error));
var asyncInfo = new TaskToAsyncActionWithProgressAdapter<TProgress>(isCanceled: false);
asyncInfo.DangerousSetError(error);
Debug.Assert(asyncInfo.Status == AsyncStatus.Error);
return asyncInfo;
}
internal static IAsyncOperation<TResult> CreateFaultedOperation<TResult>(Exception error)
{
if (error == null)
throw new ArgumentNullException(nameof(error));
var asyncInfo = new TaskToAsyncOperationAdapter<TResult>(default(TResult));
asyncInfo.DangerousSetError(error);
Debug.Assert(asyncInfo.Status == AsyncStatus.Error);
return asyncInfo;
}
internal static IAsyncOperationWithProgress<TResult, TProgress> CreateFaultedOperation<TResult, TProgress>(Exception error)
{
if (error == null)
throw new ArgumentNullException(nameof(error));
var asyncInfo = new TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>(default(TResult));
asyncInfo.DangerousSetError(error);
Debug.Assert(asyncInfo.Status == AsyncStatus.Error);
return asyncInfo;
}
#endregion Factory methods for creating IAsyncInfo instances that have already completed synchronously with an error
} // class AsyncInfo
} // namespace
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using wkt = Google.Protobuf.WellKnownTypes;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Monitoring.V3.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedAlertPolicyServiceClientTest
{
[xunit::FactAttribute]
public void GetAlertPolicyRequestObject()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.GetAlertPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAlertPolicyRequestObjectAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.GetAlertPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.GetAlertPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAlertPolicy()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.GetAlertPolicy(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAlertPolicyAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.GetAlertPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.GetAlertPolicyAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAlertPolicyResourceNames1()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.GetAlertPolicy(request.AlertPolicyName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAlertPolicyResourceNames1Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.GetAlertPolicyAsync(request.AlertPolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.GetAlertPolicyAsync(request.AlertPolicyName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetAlertPolicyResourceNames2()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.GetAlertPolicy(request.ResourceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAlertPolicyResourceNames2Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
GetAlertPolicyRequest request = new GetAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.GetAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.GetAlertPolicyAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.GetAlertPolicyAsync(request.ResourceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateAlertPolicyRequestObject()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.CreateAlertPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateAlertPolicyRequestObjectAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.CreateAlertPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.CreateAlertPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateAlertPolicy()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.CreateAlertPolicy(request.Name, request.AlertPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateAlertPolicyAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.CreateAlertPolicyAsync(request.Name, request.AlertPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.CreateAlertPolicyAsync(request.Name, request.AlertPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateAlertPolicyResourceNames1()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.CreateAlertPolicy(request.ProjectName, request.AlertPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateAlertPolicyResourceNames1Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.CreateAlertPolicyAsync(request.ProjectName, request.AlertPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.CreateAlertPolicyAsync(request.ProjectName, request.AlertPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateAlertPolicyResourceNames2()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.CreateAlertPolicy(request.OrganizationName, request.AlertPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateAlertPolicyResourceNames2Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.CreateAlertPolicyAsync(request.OrganizationName, request.AlertPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.CreateAlertPolicyAsync(request.OrganizationName, request.AlertPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateAlertPolicyResourceNames3()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.CreateAlertPolicy(request.FolderName, request.AlertPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateAlertPolicyResourceNames3Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.CreateAlertPolicyAsync(request.FolderName, request.AlertPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.CreateAlertPolicyAsync(request.FolderName, request.AlertPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateAlertPolicyResourceNames4()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.CreateAlertPolicy(request.ResourceName, request.AlertPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateAlertPolicyResourceNames4Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
CreateAlertPolicyRequest request = new CreateAlertPolicyRequest
{
AlertPolicy = new AlertPolicy(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.CreateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.CreateAlertPolicyAsync(request.ResourceName, request.AlertPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.CreateAlertPolicyAsync(request.ResourceName, request.AlertPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAlertPolicyRequestObject()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteAlertPolicy(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAlertPolicyRequestObjectAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteAlertPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAlertPolicyAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAlertPolicy()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteAlertPolicy(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAlertPolicyAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteAlertPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAlertPolicyAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAlertPolicyResourceNames1()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteAlertPolicy(request.AlertPolicyName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAlertPolicyResourceNames1Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteAlertPolicyAsync(request.AlertPolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAlertPolicyAsync(request.AlertPolicyName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteAlertPolicyResourceNames2()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteAlertPolicy(request.ResourceName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteAlertPolicyResourceNames2Async()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteAlertPolicyAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteAlertPolicyAsync(request.ResourceName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateAlertPolicyRequestObject()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
UpdateAlertPolicyRequest request = new UpdateAlertPolicyRequest
{
UpdateMask = new wkt::FieldMask(),
AlertPolicy = new AlertPolicy(),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.UpdateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.UpdateAlertPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateAlertPolicyRequestObjectAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
UpdateAlertPolicyRequest request = new UpdateAlertPolicyRequest
{
UpdateMask = new wkt::FieldMask(),
AlertPolicy = new AlertPolicy(),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.UpdateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.UpdateAlertPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.UpdateAlertPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateAlertPolicy()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
UpdateAlertPolicyRequest request = new UpdateAlertPolicyRequest
{
UpdateMask = new wkt::FieldMask(),
AlertPolicy = new AlertPolicy(),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.UpdateAlertPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy response = client.UpdateAlertPolicy(request.UpdateMask, request.AlertPolicy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateAlertPolicyAsync()
{
moq::Mock<AlertPolicyService.AlertPolicyServiceClient> mockGrpcClient = new moq::Mock<AlertPolicyService.AlertPolicyServiceClient>(moq::MockBehavior.Strict);
UpdateAlertPolicyRequest request = new UpdateAlertPolicyRequest
{
UpdateMask = new wkt::FieldMask(),
AlertPolicy = new AlertPolicy(),
};
AlertPolicy expectedResponse = new AlertPolicy
{
AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"),
DisplayName = "display_name137f65c2",
Combiner = AlertPolicy.Types.ConditionCombinerType.AndWithMatchingResource,
CreationRecord = new MutationRecord(),
MutationRecord = new MutationRecord(),
Conditions =
{
new AlertPolicy.Types.Condition(),
},
Documentation = new AlertPolicy.Types.Documentation(),
NotificationChannels =
{
"notification_channelseafebd2f",
},
UserLabels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Enabled = true,
Validity = new gr::Status(),
AlertStrategy = new AlertPolicy.Types.AlertStrategy(),
};
mockGrpcClient.Setup(x => x.UpdateAlertPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AlertPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AlertPolicyServiceClient client = new AlertPolicyServiceClientImpl(mockGrpcClient.Object, null);
AlertPolicy responseCallSettings = await client.UpdateAlertPolicyAsync(request.UpdateMask, request.AlertPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
AlertPolicy responseCancellationToken = await client.UpdateAlertPolicyAsync(request.UpdateMask, request.AlertPolicy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class FloatKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AtRoot_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClass_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalStatement_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalVariableDeclaration_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStackAlloc()
{
VerifyKeyword(
@"class C {
int* foo = stackalloc $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InFixedStatement()
{
VerifyKeyword(
@"fixed ($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InDelegateReturnType()
{
VerifyKeyword(
@"public delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCastType()
{
VerifyKeyword(AddInsideMethod(
@"var str = (($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCastType2()
{
VerifyKeyword(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOuterConst()
{
VerifyKeyword(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterInnerConst()
{
VerifyKeyword(AddInsideMethod(
@"const $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InEmptyStatement()
{
VerifyKeyword(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInEnumBaseTypes()
{
VerifyAbsence(
@"enum E : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType1()
{
VerifyKeyword(AddInsideMethod(
@"IList<$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType2()
{
VerifyKeyword(AddInsideMethod(
@"IList<int,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType3()
{
VerifyKeyword(AddInsideMethod(
@"IList<int[],$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType4()
{
VerifyKeyword(AddInsideMethod(
@"IList<IFoo<int?,byte*>,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInBaseList()
{
VerifyAbsence(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType_InBaseList()
{
VerifyKeyword(
@"class C : IList<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIs()
{
VerifyKeyword(AddInsideMethod(
@"var v = foo is $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAs()
{
VerifyKeyword(AddInsideMethod(
@"var v = foo as $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethod()
{
VerifyKeyword(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterField()
{
VerifyKeyword(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterProperty()
{
VerifyKeyword(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAttribute()
{
VerifyKeyword(
@"class C {
[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideStruct()
{
VerifyKeyword(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideInterface()
{
VerifyKeyword(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideClass()
{
VerifyKeyword(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPartial()
{
VerifyAbsence(@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedPartial()
{
VerifyAbsence(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAbstract()
{
VerifyKeyword(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedInternal()
{
VerifyKeyword(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedStaticPublic()
{
VerifyKeyword(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPublicStatic()
{
VerifyKeyword(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterVirtualPublic()
{
VerifyKeyword(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPublic()
{
VerifyKeyword(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPrivate()
{
VerifyKeyword(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedProtected()
{
VerifyKeyword(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedSealed()
{
VerifyKeyword(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedStatic()
{
VerifyKeyword(
@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodOpenParen()
{
VerifyKeyword(
@"class C {
void Foo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodComma()
{
VerifyKeyword(
@"class C {
void Foo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodAttribute()
{
VerifyKeyword(
@"class C {
void Foo(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterConstructorOpenParen()
{
VerifyKeyword(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterConstructorComma()
{
VerifyKeyword(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterConstructorAttribute()
{
VerifyKeyword(
@"class C {
public C(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateOpenParen()
{
VerifyKeyword(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateComma()
{
VerifyKeyword(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateAttribute()
{
VerifyKeyword(
@"delegate void D(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterThis()
{
VerifyKeyword(
@"static class C {
public static void Foo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterRef()
{
VerifyKeyword(
@"class C {
void Foo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOut()
{
VerifyKeyword(
@"class C {
void Foo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterLambdaRef()
{
VerifyKeyword(
@"class C {
void Foo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterLambdaOut()
{
VerifyKeyword(
@"class C {
void Foo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterParams()
{
VerifyKeyword(
@"class C {
void Foo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InImplicitOperator()
{
VerifyKeyword(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InExplicitOperator()
{
VerifyKeyword(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIndexerBracket()
{
VerifyKeyword(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIndexerBracketComma()
{
VerifyKeyword(
@"class C {
int this[int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNewInExpression()
{
VerifyKeyword(AddInsideMethod(
@"new $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOut2()
{
VerifyKeyword(
@"class C {
private static void RoundToFloat(double d, out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOut3()
{
VerifyKeyword(
@"class C {
private static void RoundToFloat(double d, out $$ float f)");
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InTypeOf()
{
VerifyKeyword(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InDefault()
{
VerifyKeyword(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InSizeOf()
{
VerifyKeyword(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInObjectInitializerMemberContext()
{
VerifyAbsence(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCrefContext()
{
VerifyKeyword(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCrefContextNotAfterDot()
{
VerifyAbsence(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[WorkItem(18374)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAsync()
{
VerifyKeyword(@"class c { async $$ }");
}
[WorkItem(18374)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterAsyncAsType()
{
VerifyAbsence(@"class c { async async $$ }");
}
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInCrefTypeParameter()
{
VerifyAbsence(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
}
}
| |
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using NuGet.Frameworks;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.Test.Helpers;
using NuGet.Versioning;
using Xunit;
namespace NupkgWrench.Tests
{
public class ReleaseCommandTests
{
[Fact]
public async Task Command_ReleaseCommand_MultipleNewVersions_EachTFMTakesCorrectVersion()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "1.0.0"
}
};
var depGroup1 = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("1.0.0"))
});
var depGroup2 = new PackageDependencyGroup(NuGetFramework.Parse("net46"), new[] {
new PackageDependency("b", VersionRange.Parse("2.0.0"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup1);
testPackageA.Nuspec.Dependencies.Add(depGroup2);
var testPackageB1 = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "1.0.0"
}
};
var testPackageB2 = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "2.0.0"
}
};
var testPackageB3 = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "0.1.0"
}
};
var testPackageB4 = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "9.0.0"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB1 = testPackageB1.Save(workingDir.Root);
var zipFileB2 = testPackageB2.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-r", "beta" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.1.0.0-beta.nupkg"));
var dependencyBNet45 = nuspecA.GetDependencyGroups().Single(e => e.TargetFramework == NuGetFramework.Parse("net45")).Packages.Single(e => e.Id == "b");
var dependencyBNet46 = nuspecA.GetDependencyGroups().Single(e => e.TargetFramework == NuGetFramework.Parse("net46")).Packages.Single(e => e.Id == "b");
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("1.0.0-beta", dependencyBNet45.VersionRange.ToLegacyShortString());
Assert.Equal("2.0.0-beta", dependencyBNet46.VersionRange.ToLegacyShortString());
}
}
[Fact]
public async Task Command_ReleaseCommand_MultipleNewVersions_TakeLowestValid()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "6.0.0"
}
};
var depGroup = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("5.0.0"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup);
var testPackageB1 = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "6.0.0"
}
};
var testPackageB2 = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "7.0.0"
}
};
var testPackageB3 = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "1.0.0"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB1 = testPackageB1.Save(workingDir.Root);
var zipFileB2 = testPackageB2.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-r", "beta" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.6.0.0-beta.nupkg"));
var dependencyB = nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "b");
var dependencyBString = dependencyB.VersionRange.ToLegacyShortString();
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("6.0.0-beta", dependencyBString);
}
}
[Fact]
public async Task Command_ReleaseCommand_NewMinVersionNonInclusive_SwitchesMode()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "6.0.0"
}
};
var depGroup = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("(6.0.0, )"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup);
var testPackageB = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "7.0.0"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB = testPackageB.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-n", "6.0.0" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.6.0.0.nupkg"));
var dependencyB = nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "b");
var dependencyBString = dependencyB.VersionRange.ToLegacyShortString();
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("6.0.0", dependencyBString);
}
}
[Fact]
public async Task Command_ReleaseCommand_NewMaxVersionNonInclusive_SwitchesMode()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "6.0.0"
}
};
var depGroup = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("(, 6.0.0)"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup);
var testPackageB = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "1.0.0"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB = testPackageB.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-n", "6.0.0" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.6.0.0.nupkg"));
var dependencyB = nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "b");
var dependencyBString = dependencyB.VersionRange.ToLegacyShortString();
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("(, 6.0.0]", dependencyBString);
}
}
[Fact]
public async Task Command_ReleaseCommand_NewVersionOutsideOfOriginalRange_DoubleSided()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "6.0.0"
}
};
var depGroup = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("[1.0.0, 2.0.0]"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup);
var testPackageB = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "1.5.0"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB = testPackageB.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-n", "9.0.0" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.9.0.0.nupkg"));
var dependencyB = nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "b");
var dependencyBString = dependencyB.VersionRange.ToLegacyShortString();
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("[9.0.0]", dependencyBString);
}
}
[Fact]
public async Task Command_ReleaseCommand_VersionOutsideOfOriginalRange()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "6.0.0"
}
};
var depGroup = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("[1.0.0, 2.0.0]"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup);
var testPackageB = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "6.0.0"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB = testPackageB.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-n", "9.0.0" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.9.0.0.nupkg"));
var dependencyB = nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "b");
var dependencyBString = dependencyB.VersionRange.ToLegacyShortString();
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("[1.0.0, 2.0.0]", dependencyBString);
Assert.Contains("dependency b does not allow the original version of b 6.0.0. Skipping.", string.Join("|", log.Messages));
}
}
[Fact]
public async Task Command_ReleaseCommand_NewVersionAboveMax()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "6.0.0"
}
};
var depGroup = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("[ , 6.0.0]"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup);
var testPackageB = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "6.0.0"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB = testPackageB.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-n", "9.0.0" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.9.0.0.nupkg"));
var dependencyB = nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "b");
var dependencyBString = dependencyB.VersionRange.ToLegacyShortString();
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("(, 9.0.0]", dependencyBString);
}
}
[Fact]
public async Task Command_ReleaseCommand_NewVersionAboveMax_MatchOnMin()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "6.0.0"
}
};
var depGroup = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("[6.0.0 , 7.0.0]"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup);
var testPackageB = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "6.0.0"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB = testPackageB.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-n", "9.0.0" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.9.0.0.nupkg"));
var dependencyB = nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "b");
var dependencyBString = dependencyB.VersionRange.ToLegacyShortString();
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("[9.0.0]", dependencyBString);
}
}
[Fact]
public async Task Command_ReleaseCommand_NewVersionAboveMin()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "6.0.0"
}
};
var depGroup = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("5.0.0"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup);
var testPackageB = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "6.0.0"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB = testPackageB.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-n", "9.0.0" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.9.0.0.nupkg"));
var dependencyB = nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "b");
var dependencyBString = dependencyB.VersionRange.ToLegacyShortString();
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("9.0.0", dependencyBString);
}
}
[Fact]
public async Task Command_ReleaseCommand_NewVersionBelowMin()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "6.0.0"
}
};
var depGroup = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("5.0.0"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup);
var testPackageB = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "6.0.0"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB = testPackageB.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-n", "1.0.0" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.1.0.0.nupkg"));
var dependencyB = nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "b");
var dependencyBString = dependencyB.VersionRange.ToLegacyShortString();
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("1.0.0", dependencyBString);
}
}
[Fact]
public async Task Command_ReleaseCommand_Stable()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "1.0.0-beta.1.2"
}
};
var depGroup = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("2.0.0-alpha")),
new PackageDependency("c", VersionRange.Parse("[1.0.0-beta]"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup);
var testPackageB = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "2.0.0-alpha"
}
};
var testPackageC = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "c",
Version = "1.0.0-beta"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB = testPackageB.Save(workingDir.Root);
var zipFileC = testPackageC.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.1.0.0.nupkg"));
var nuspecB = GetNuspec(Path.Combine(workingDir.Root, "b.2.0.0.nupkg"));
var nuspecC = GetNuspec(Path.Combine(workingDir.Root, "c.1.0.0.nupkg"));
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("1.0.0", nuspecA.GetVersion().ToString());
Assert.Equal("2.0.0", nuspecB.GetVersion().ToString());
Assert.Equal("1.0.0", nuspecC.GetVersion().ToString());
Assert.Equal("2.0.0", nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "b").VersionRange.ToLegacyShortString());
Assert.Equal("[1.0.0]", nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "c").VersionRange.ToLegacyShortString());
}
}
[Fact]
public async Task Command_ReleaseCommand_FourPartVersion()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "1.0.0"
}
};
var testPackageB = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "2.0.0-alpha"
}
};
var testPackageC = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "c",
Version = "1.2.3.4"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB = testPackageB.Save(workingDir.Root);
var zipFileC = testPackageC.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "--four-part-version" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.1.0.0.0.nupkg"));
var nuspecB = GetNuspec(Path.Combine(workingDir.Root, "b.2.0.0.0-alpha.nupkg"));
var nuspecC = GetNuspec(Path.Combine(workingDir.Root, "c.1.2.3.4.nupkg"));
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("1.0.0.0", nuspecA.GetVersion().ToString());
Assert.Equal("2.0.0.0-alpha", nuspecB.GetVersion().ToString());
Assert.Equal("1.2.3.4", nuspecC.GetVersion().ToString());
}
}
[Fact]
public async Task Command_ReleaseCommand_ChangeVersion()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "1.0.0-beta.1.2"
}
};
var depGroup = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("2.0.0-alpha")),
new PackageDependency("c", VersionRange.Parse("[1.0.0-beta]"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup);
var testPackageB = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "2.0.0-alpha"
}
};
var testPackageC = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "c",
Version = "1.0.0-beta"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB = testPackageB.Save(workingDir.Root);
var zipFileC = testPackageC.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-n", "5.1.1-delta" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.5.1.1-delta.nupkg"));
var nuspecB = GetNuspec(Path.Combine(workingDir.Root, "b.5.1.1-delta.nupkg"));
var nuspecC = GetNuspec(Path.Combine(workingDir.Root, "c.5.1.1-delta.nupkg"));
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("5.1.1-delta", nuspecA.GetVersion().ToString());
Assert.Equal("5.1.1-delta", nuspecB.GetVersion().ToString());
Assert.Equal("5.1.1-delta", nuspecC.GetVersion().ToString());
Assert.Equal("5.1.1-delta", nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "b").VersionRange.ToLegacyShortString());
Assert.Equal("[5.1.1-delta]", nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "c").VersionRange.ToLegacyShortString());
}
}
[Fact]
public async Task Command_ReleaseCommand_Label()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "1.0.0-beta.1.2"
}
};
var depGroup = new PackageDependencyGroup(NuGetFramework.Parse("net45"), new[] {
new PackageDependency("b", VersionRange.Parse("2.0.0-alpha")),
new PackageDependency("c", VersionRange.Parse("[1.0.0-beta]"))
});
testPackageA.Nuspec.Dependencies.Add(depGroup);
var testPackageB = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "b",
Version = "2.0.0-alpha"
}
};
var testPackageC = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "c",
Version = "1.0.0-beta"
}
};
var zipFileA = testPackageA.Save(workingDir.Root);
var zipFileB = testPackageB.Save(workingDir.Root);
var zipFileC = testPackageC.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "--label", "rc.1" }, log);
var nuspecA = GetNuspec(Path.Combine(workingDir.Root, "a.1.0.0-rc.1.nupkg"));
var nuspecB = GetNuspec(Path.Combine(workingDir.Root, "b.2.0.0-rc.1.nupkg"));
var nuspecC = GetNuspec(Path.Combine(workingDir.Root, "c.1.0.0-rc.1.nupkg"));
// Assert
Assert.Equal(0, exitCode);
Assert.Equal("1.0.0-rc.1", nuspecA.GetVersion().ToString());
Assert.Equal("2.0.0-rc.1", nuspecB.GetVersion().ToString());
Assert.Equal("1.0.0-rc.1", nuspecC.GetVersion().ToString());
Assert.Equal("2.0.0-rc.1", nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "b").VersionRange.ToLegacyShortString());
Assert.Equal("[1.0.0-rc.1]", nuspecA.GetDependencyGroups().Single().Packages.Single(e => e.Id == "c").VersionRange.ToLegacyShortString());
}
}
[Fact]
public async Task Command_ReleaseCommand_CollisionOnNewVersion()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA1 = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "1.0.0"
}
};
var testPackageA2 = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "2.0.0"
}
};
var zipFileA1 = testPackageA1.Save(workingDir.Root);
var zipFileA2 = testPackageA2.Save(workingDir.Root);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-n", "3.0.0" }, log);
// Assert
Assert.Equal(1, exitCode);
Assert.Contains("Output file name collision on", log.GetMessages());
}
}
[Fact]
public async Task Command_ReleaseCommand_NoCollisionOnNewVersionWhenSymbols()
{
using (var workingDir = new TestFolder())
{
// Arrange
var testPackageA1 = new TestNupkg()
{
Nuspec = new TestNuspec()
{
Id = "a",
Version = "1.0.0"
}
};
var zipFileA1 = testPackageA1.Save(workingDir.Root);
var symbolsPath = zipFileA1.FullName.Replace(".nupkg", ".symbols.nupkg");
File.Copy(zipFileA1.FullName, symbolsPath);
var log = new TestLogger();
// Act
var exitCode = await Program.MainCore(new[] { "release", workingDir.Root, "-n", "3.0.0" }, log);
// Assert
Assert.Equal(0, exitCode);
var nuspecA1 = GetNuspec(Path.Combine(workingDir.Root, "a.3.0.0.nupkg"));
var nuspecA2 = GetNuspec(Path.Combine(workingDir.Root, "a.3.0.0.symbols.nupkg"));
Assert.Equal("3.0.0", nuspecA1.GetVersion().ToNormalizedString());
Assert.Equal("3.0.0", nuspecA2.GetVersion().ToNormalizedString());
}
}
private static NuspecReader GetNuspec(string path)
{
using (var reader = new PackageArchiveReader(path))
{
return reader.NuspecReader;
}
}
}
}
| |
// 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.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security;
using System.Windows.Input;
namespace System.Runtime.InteropServices.WindowsRuntime
{
// Local definition of Windows.UI.Xaml.Interop.INotifyCollectionChangedEventArgs
[ComImport]
[Guid("4cf68d33-e3f2-4964-b85e-945b4f7e2f21")]
[WindowsRuntimeImport]
internal interface INotifyCollectionChangedEventArgs
{
NotifyCollectionChangedAction Action { get; }
IList NewItems { get; }
IList OldItems { get; }
int NewStartingIndex { get; }
int OldStartingIndex { get; }
}
// Local definition of Windows.UI.Xaml.Data.IPropertyChangedEventArgs
[ComImport]
[Guid("4f33a9a0-5cf4-47a4-b16f-d7faaf17457e")]
[WindowsRuntimeImport]
internal interface IPropertyChangedEventArgs
{
string PropertyName { get; }
}
// Local definition of Windows.UI.Xaml.Interop.INotifyCollectionChanged
[ComImport]
[Guid("28b167d5-1a31-465b-9b25-d5c3ae686c40")]
[WindowsRuntimeImport]
internal interface INotifyCollectionChanged_WinRT
{
EventRegistrationToken add_CollectionChanged(NotifyCollectionChangedEventHandler value);
void remove_CollectionChanged(EventRegistrationToken token);
}
// Local definition of Windows.UI.Xaml.Data.INotifyPropertyChanged
[ComImport]
[Guid("cf75d69c-f2f4-486b-b302-bb4c09baebfa")]
[WindowsRuntimeImport]
internal interface INotifyPropertyChanged_WinRT
{
EventRegistrationToken add_PropertyChanged(PropertyChangedEventHandler value);
void remove_PropertyChanged(EventRegistrationToken token);
}
// Local definition of Windows.UI.Xaml.Input.ICommand
[ComImport]
[Guid("e5af3542-ca67-4081-995b-709dd13792df")]
[WindowsRuntimeImport]
internal interface ICommand_WinRT
{
EventRegistrationToken add_CanExecuteChanged(EventHandler<object> value);
void remove_CanExecuteChanged(EventRegistrationToken token);
bool CanExecute(object parameter);
void Execute(object parameter);
}
// Local definition of Windows.UI.Xaml.Interop.NotifyCollectionChangedEventHandler
[Guid("ca10b37c-f382-4591-8557-5e24965279b0")]
[WindowsRuntimeImport]
internal delegate void NotifyCollectionChangedEventHandler_WinRT(object sender, NotifyCollectionChangedEventArgs e);
// Local definition of Windows.UI.Xaml.Data.PropertyChangedEventHandler
[Guid("50f19c16-0a22-4d8e-a089-1ea9951657d2")]
[WindowsRuntimeImport]
internal delegate void PropertyChangedEventHandler_WinRT(object sender, PropertyChangedEventArgs e);
internal static class NotifyCollectionChangedEventArgsMarshaler
{
// Extracts properties from a managed NotifyCollectionChangedEventArgs and passes them to
// a VM-implemented helper that creates a WinRT NotifyCollectionChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
internal static IntPtr ConvertToNative(NotifyCollectionChangedEventArgs managedArgs)
{
if (managedArgs == null)
return IntPtr.Zero;
return System.StubHelpers.EventArgsMarshaler.CreateNativeNCCEventArgsInstance(
(int)managedArgs.Action,
managedArgs.NewItems,
managedArgs.OldItems,
managedArgs.NewStartingIndex,
managedArgs.OldStartingIndex);
}
// Extracts properties from a WinRT NotifyCollectionChangedEventArgs and creates a new
// managed NotifyCollectionChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
internal static NotifyCollectionChangedEventArgs ConvertToManaged(IntPtr nativeArgsIP)
{
if (nativeArgsIP == IntPtr.Zero)
return null;
object obj = System.StubHelpers.InterfaceMarshaler.ConvertToManagedWithoutUnboxing(nativeArgsIP);
INotifyCollectionChangedEventArgs nativeArgs = (INotifyCollectionChangedEventArgs)obj;
return CreateNotifyCollectionChangedEventArgs(
nativeArgs.Action,
nativeArgs.NewItems,
nativeArgs.OldItems,
nativeArgs.NewStartingIndex,
nativeArgs.OldStartingIndex);
}
internal static NotifyCollectionChangedEventArgs CreateNotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action, IList newItems, IList oldItems, int newStartingIndex, int oldStartingIndex)
{
switch (action)
{
case NotifyCollectionChangedAction.Add:
return new NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex);
case NotifyCollectionChangedAction.Remove:
return new NotifyCollectionChangedEventArgs(action, oldItems, oldStartingIndex);
case NotifyCollectionChangedAction.Replace:
return new NotifyCollectionChangedEventArgs(action, newItems, oldItems, newStartingIndex);
case NotifyCollectionChangedAction.Move:
return new NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex, oldStartingIndex);
case NotifyCollectionChangedAction.Reset:
return new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
default: throw new ArgumentException("Invalid action value: " + action);
}
}
}
internal static class PropertyChangedEventArgsMarshaler
{
// Extracts PropertyName from a managed PropertyChangedEventArgs and passes them to
// a VM-implemented helper that creates a WinRT PropertyChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
internal static IntPtr ConvertToNative(PropertyChangedEventArgs managedArgs)
{
if (managedArgs == null)
return IntPtr.Zero;
return System.StubHelpers.EventArgsMarshaler.CreateNativePCEventArgsInstance(managedArgs.PropertyName);
}
// Extracts properties from a WinRT PropertyChangedEventArgs and creates a new
// managed PropertyChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
internal static PropertyChangedEventArgs ConvertToManaged(IntPtr nativeArgsIP)
{
if (nativeArgsIP == IntPtr.Zero)
return null;
object obj = System.StubHelpers.InterfaceMarshaler.ConvertToManagedWithoutUnboxing(nativeArgsIP);
IPropertyChangedEventArgs nativeArgs = (IPropertyChangedEventArgs)obj;
return new PropertyChangedEventArgs(nativeArgs.PropertyName);
}
}
// This is a set of stub methods implementing the support for the managed INotifyCollectionChanged
// interface on WinRT objects that support the WinRT INotifyCollectionChanged. Used by the interop
// mashaling infrastructure.
internal sealed class NotifyCollectionChangedToManagedAdapter
{
private NotifyCollectionChangedToManagedAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
internal event NotifyCollectionChangedEventHandler CollectionChanged
{
// void CollectionChanged.add(NotifyCollectionChangedEventHandler)
add
{
INotifyCollectionChanged_WinRT _this = Unsafe.As<INotifyCollectionChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to subscribe the event
Func<NotifyCollectionChangedEventHandler, EventRegistrationToken> addMethod =
new Func<NotifyCollectionChangedEventHandler, EventRegistrationToken>(_this.add_CollectionChanged);
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_CollectionChanged);
WindowsRuntimeMarshal.AddEventHandler<NotifyCollectionChangedEventHandler>(addMethod, removeMethod, value);
}
// void CollectionChanged.remove(NotifyCollectionChangedEventHandler)
remove
{
INotifyCollectionChanged_WinRT _this = Unsafe.As<INotifyCollectionChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to unsubscribe the event
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_CollectionChanged);
WindowsRuntimeMarshal.RemoveEventHandler<NotifyCollectionChangedEventHandler>(removeMethod, value);
}
}
}
// This is a set of stub methods implementing the support for the WinRT INotifyCollectionChanged
// interface on managed objects that support the managed INotifyCollectionChanged. Used by the interop
// mashaling infrastructure.
internal sealed class NotifyCollectionChangedToWinRTAdapter
{
private NotifyCollectionChangedToWinRTAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
// An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj.
// Since here the class can be an arbitrary implementation of INotifyCollectionChanged, we have to keep the EventRegistrationTokenTable's
// separately, associated with the implementations using ConditionalWeakTable.
private static ConditionalWeakTable<INotifyCollectionChanged, EventRegistrationTokenTable<NotifyCollectionChangedEventHandler>> s_weakTable =
new ConditionalWeakTable<INotifyCollectionChanged, EventRegistrationTokenTable<NotifyCollectionChangedEventHandler>>();
// EventRegistrationToken CollectionChanged.add(NotifyCollectionChangedEventHandler value)
internal EventRegistrationToken add_CollectionChanged(NotifyCollectionChangedEventHandler value)
{
INotifyCollectionChanged _this = Unsafe.As<INotifyCollectionChanged>(this);
EventRegistrationTokenTable<NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventRegistrationToken token = table.AddEventHandler(value);
_this.CollectionChanged += value;
return token;
}
// void CollectionChanged.remove(EventRegistrationToken token)
internal void remove_CollectionChanged(EventRegistrationToken token)
{
INotifyCollectionChanged _this = Unsafe.As<INotifyCollectionChanged>(this);
EventRegistrationTokenTable<NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
NotifyCollectionChangedEventHandler handler = table.ExtractHandler(token);
if (handler != null)
{
_this.CollectionChanged -= handler;
}
}
}
// This is a set of stub methods implementing the support for the managed INotifyPropertyChanged
// interface on WinRT objects that support the WinRT INotifyPropertyChanged. Used by the interop
// mashaling infrastructure.
internal sealed class NotifyPropertyChangedToManagedAdapter
{
private NotifyPropertyChangedToManagedAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
internal event PropertyChangedEventHandler PropertyChanged
{
// void PropertyChanged.add(PropertyChangedEventHandler)
add
{
INotifyPropertyChanged_WinRT _this = Unsafe.As<INotifyPropertyChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to subscribe the event
Func<PropertyChangedEventHandler, EventRegistrationToken> addMethod =
new Func<PropertyChangedEventHandler, EventRegistrationToken>(_this.add_PropertyChanged);
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_PropertyChanged);
WindowsRuntimeMarshal.AddEventHandler<PropertyChangedEventHandler>(addMethod, removeMethod, value);
}
// void PropertyChanged.remove(PropertyChangedEventHandler)
remove
{
INotifyPropertyChanged_WinRT _this = Unsafe.As<INotifyPropertyChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to unsubscribe the event
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_PropertyChanged);
WindowsRuntimeMarshal.RemoveEventHandler<PropertyChangedEventHandler>(removeMethod, value);
}
}
}
// This is a set of stub methods implementing the support for the WinRT INotifyPropertyChanged
// interface on managed objects that support the managed INotifyPropertyChanged. Used by the interop
// mashaling infrastructure.
internal sealed class NotifyPropertyChangedToWinRTAdapter
{
private NotifyPropertyChangedToWinRTAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
// An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj.
// Since here the class can be an arbitrary implementation of INotifyCollectionChanged, we have to keep the EventRegistrationTokenTable's
// separately, associated with the implementations using ConditionalWeakTable.
private static ConditionalWeakTable<INotifyPropertyChanged, EventRegistrationTokenTable<PropertyChangedEventHandler>> s_weakTable =
new ConditionalWeakTable<INotifyPropertyChanged, EventRegistrationTokenTable<PropertyChangedEventHandler>>();
// EventRegistrationToken PropertyChanged.add(PropertyChangedEventHandler value)
internal EventRegistrationToken add_PropertyChanged(PropertyChangedEventHandler value)
{
INotifyPropertyChanged _this = Unsafe.As<INotifyPropertyChanged>(this);
EventRegistrationTokenTable<PropertyChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventRegistrationToken token = table.AddEventHandler(value);
_this.PropertyChanged += value;
return token;
}
// void PropertyChanged.remove(EventRegistrationToken token)
internal void remove_PropertyChanged(EventRegistrationToken token)
{
INotifyPropertyChanged _this = Unsafe.As<INotifyPropertyChanged>(this);
EventRegistrationTokenTable<PropertyChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
PropertyChangedEventHandler handler = table.ExtractHandler(token);
if (handler != null)
{
_this.PropertyChanged -= handler;
}
}
}
// This is a set of stub methods implementing the support for the managed ICommand
// interface on WinRT objects that support the WinRT ICommand_WinRT.
// Used by the interop mashaling infrastructure.
// Instances of this are really RCWs of ICommand_WinRT (not ICommandToManagedAdapter or any ICommand).
internal sealed class ICommandToManagedAdapter /*: System.Windows.Input.ICommand*/
{
private static ConditionalWeakTable<EventHandler, EventHandler<object>> s_weakTable =
new ConditionalWeakTable<EventHandler, EventHandler<object>>();
private ICommandToManagedAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
private event EventHandler CanExecuteChanged
{
// void CanExecuteChanged.add(EventHandler)
add
{
ICommand_WinRT _this = Unsafe.As<ICommand_WinRT>(this);
// call the WinRT eventing support in mscorlib to subscribe the event
Func<EventHandler<object>, EventRegistrationToken> addMethod =
new Func<EventHandler<object>, EventRegistrationToken>(_this.add_CanExecuteChanged);
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_CanExecuteChanged);
// value is of type System.EventHandler, but ICommand_WinRT (and thus WindowsRuntimeMarshal.AddEventHandler)
// expects an instance of EventHandler<object>. So we get/create a wrapper of value here.
EventHandler<object> handler_WinRT = s_weakTable.GetValue(value, ICommandAdapterHelpers.CreateWrapperHandler);
WindowsRuntimeMarshal.AddEventHandler<EventHandler<object>>(addMethod, removeMethod, handler_WinRT);
}
// void CanExecuteChanged.remove(EventHandler)
remove
{
ICommand_WinRT _this = Unsafe.As<ICommand_WinRT>(this);
// call the WinRT eventing support in mscorlib to unsubscribe the event
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_CanExecuteChanged);
// value is of type System.EventHandler, but ICommand_WinRT (and thus WindowsRuntimeMarshal.RemoveEventHandler)
// expects an instance of EventHandler<object>. So we get/create a wrapper of value here.
// Also we do a value check rather than an instance check to ensure that different instances of the same delegates are treated equal.
EventHandler<object> handler_WinRT = ICommandAdapterHelpers.GetValueFromEquivalentKey(s_weakTable, value, ICommandAdapterHelpers.CreateWrapperHandler);
WindowsRuntimeMarshal.RemoveEventHandler<EventHandler<object>>(removeMethod, handler_WinRT);
}
}
private bool CanExecute(object parameter)
{
ICommand_WinRT _this = Unsafe.As<ICommand_WinRT>(this);
return _this.CanExecute(parameter);
}
private void Execute(object parameter)
{
ICommand_WinRT _this = Unsafe.As<ICommand_WinRT>(this);
_this.Execute(parameter);
}
}
// This is a set of stub methods implementing the support for the WinRT ICommand_WinRT
// interface on managed objects that support the managed ICommand interface.
// Used by the interop mashaling infrastructure.
// Instances of this are really CCWs of ICommand (not ICommandToWinRTAdapter or any ICommand_WinRT).
internal sealed class ICommandToWinRTAdapter /*: ICommand_WinRT*/
{
private ICommandToWinRTAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
// An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj.
// Since here the class can be an arbitrary implementation of ICommand, we have to keep the EventRegistrationTokenTable's
// separately, associated with the implementations using ConditionalWeakTable.
private static ConditionalWeakTable<ICommand, EventRegistrationTokenTable<EventHandler>> s_weakTable =
new ConditionalWeakTable<ICommand, EventRegistrationTokenTable<EventHandler>>();
// EventRegistrationToken PropertyChanged.add(EventHandler<object> value)
private EventRegistrationToken add_CanExecuteChanged(EventHandler<object> value)
{
ICommand _this = Unsafe.As<ICommand>(this);
EventRegistrationTokenTable<EventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventHandler handler = ICommandAdapterHelpers.CreateWrapperHandler(value);
EventRegistrationToken token = table.AddEventHandler(handler);
_this.CanExecuteChanged += handler;
return token;
}
// void PropertyChanged.remove(EventRegistrationToken token)
private void remove_CanExecuteChanged(EventRegistrationToken token)
{
ICommand _this = Unsafe.As<ICommand>(this);
EventRegistrationTokenTable<EventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventHandler handler = table.ExtractHandler(token);
if (handler != null)
{
_this.CanExecuteChanged -= handler;
}
}
private bool CanExecute(object parameter)
{
ICommand _this = Unsafe.As<ICommand>(this);
return _this.CanExecute(parameter);
}
private void Execute(object parameter)
{
ICommand _this = Unsafe.As<ICommand>(this);
_this.Execute(parameter);
}
}
// A couple of ICommand adapter helpers need to be transparent, and so are in their own type
internal static class ICommandAdapterHelpers
{
internal static EventHandler<object> CreateWrapperHandler(EventHandler handler)
{
// Check whether it is a round-tripping case i.e. the sender is of the type eventArgs,
// If so we use it else we pass EventArgs.Empty
return (object sender, object e) =>
{
EventArgs eventArgs = e as EventArgs;
handler(sender, (eventArgs == null ? System.EventArgs.Empty : eventArgs));
};
}
internal static EventHandler CreateWrapperHandler(EventHandler<object> handler)
{
return (object sender, EventArgs e) => handler(sender, e);
}
internal static EventHandler<object> GetValueFromEquivalentKey(
ConditionalWeakTable<EventHandler, EventHandler<object>> table,
EventHandler key,
ConditionalWeakTable<EventHandler, EventHandler<object>>.CreateValueCallback callback)
{
foreach (KeyValuePair<EventHandler, EventHandler<object>> item in table)
{
if (Object.Equals(item.Key, key))
return item.Value;
}
EventHandler<object> value = callback(key);
table.Add(key, value);
return value;
}
}
}
| |
using Braintree.Exceptions;
using NUnit.Framework;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Braintree.Tests.Integration
{
[TestFixture]
public class AddressIntegrationTest
{
private BraintreeGateway gateway;
[SetUp]
public void Setup()
{
gateway = new BraintreeGateway
{
Environment = Environment.DEVELOPMENT,
MerchantId = "integration_merchant_id",
PublicKey = "integration_public_key",
PrivateKey = "integration_private_key"
};
}
[Test]
public void Create_CreatesAddressForGivenCustomerId()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var addressRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryCodeAlpha2 = "US",
CountryCodeAlpha3 = "USA",
CountryCodeNumeric = "840",
CountryName = "United States of America"
};
Address address = gateway.Address.Create(customer.Id, addressRequest).Target;
Assert.AreEqual("Michael", address.FirstName);
Assert.AreEqual("Angelo", address.LastName);
Assert.AreEqual("Angelo Co.", address.Company);
Assert.AreEqual("1 E Main St", address.StreetAddress);
Assert.AreEqual("Apt 3", address.ExtendedAddress);
Assert.AreEqual("Chicago", address.Locality);
Assert.AreEqual("IL", address.Region);
Assert.AreEqual("60622", address.PostalCode);
Assert.AreEqual("US", address.CountryCodeAlpha2);
Assert.AreEqual("USA", address.CountryCodeAlpha3);
Assert.AreEqual("840", address.CountryCodeNumeric);
Assert.AreEqual("United States of America", address.CountryName);
Assert.IsNotNull(address.CreatedAt);
Assert.IsNotNull(address.UpdatedAt);
}
[Test]
#if netcore
public async Task CreateAsync_CreatesAddressForGivenCustomerId()
#else
public void CreateAsync_CreatesAddressForGivenCustomerId()
{
Task.Run(async() =>
#endif
{
Result<Customer> customerResult = await gateway.Customer.CreateAsync(new CustomerRequest());
Customer customer = customerResult.Target;
var addressRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryCodeAlpha2 = "US",
CountryCodeAlpha3 = "USA",
CountryCodeNumeric = "840",
CountryName = "United States of America"
};
Result<Address> addressResult = await gateway.Address.CreateAsync(customer.Id, addressRequest);
Address address = addressResult.Target;
Assert.AreEqual("Michael", address.FirstName);
Assert.AreEqual("Angelo", address.LastName);
Assert.AreEqual("Angelo Co.", address.Company);
Assert.AreEqual("1 E Main St", address.StreetAddress);
Assert.AreEqual("Apt 3", address.ExtendedAddress);
Assert.AreEqual("Chicago", address.Locality);
Assert.AreEqual("IL", address.Region);
Assert.AreEqual("60622", address.PostalCode);
Assert.AreEqual("US", address.CountryCodeAlpha2);
Assert.AreEqual("USA", address.CountryCodeAlpha3);
Assert.AreEqual("840", address.CountryCodeNumeric);
Assert.AreEqual("United States of America", address.CountryName);
Assert.IsNotNull(address.CreatedAt);
Assert.IsNotNull(address.UpdatedAt);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Find_FindsAddress()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var addressRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America"
};
Address createdAddress = gateway.Address.Create(customer.Id, addressRequest).Target;
Address address = gateway.Address.Find(customer.Id, createdAddress.Id);
Assert.AreEqual("Michael", address.FirstName);
Assert.AreEqual("Angelo", address.LastName);
Assert.AreEqual("Angelo Co.", address.Company);
Assert.AreEqual("1 E Main St", address.StreetAddress);
Assert.AreEqual("Apt 3", address.ExtendedAddress);
Assert.AreEqual("Chicago", address.Locality);
Assert.AreEqual("IL", address.Region);
Assert.AreEqual("60622", address.PostalCode);
Assert.AreEqual("United States of America", address.CountryName);
}
[Test]
#if netcore
public async Task FindAsync_FindsAddress()
#else
public void FindAsync_FindsAddress()
{
Task.Run(async() =>
#endif
{
Result<Customer> customerResult = await gateway.Customer.CreateAsync(new CustomerRequest());
Customer customer = customerResult.Target;
var addressRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America"
};
Result<Address> addressResult = await gateway.Address.CreateAsync(customer.Id, addressRequest);
Address createdAddress = addressResult.Target;
Address address = await gateway.Address.FindAsync(customer.Id, createdAddress.Id);
Assert.AreEqual("Michael", address.FirstName);
Assert.AreEqual("Angelo", address.LastName);
Assert.AreEqual("Angelo Co.", address.Company);
Assert.AreEqual("1 E Main St", address.StreetAddress);
Assert.AreEqual("Apt 3", address.ExtendedAddress);
Assert.AreEqual("Chicago", address.Locality);
Assert.AreEqual("IL", address.Region);
Assert.AreEqual("60622", address.PostalCode);
Assert.AreEqual("United States of America", address.CountryName);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Update_UpdatesAddressForGivenCustomerIdAndAddressId()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var addressCreateRequest = new AddressRequest
{
FirstName = "Dave",
LastName = "Inchy",
Company = "Leon Ardo Co.",
StreetAddress = "1 E State St",
ExtendedAddress = "Apt 4",
Locality = "Boston",
Region = "MA",
PostalCode = "11111",
CountryName = "Canada",
CountryCodeAlpha2 = "CA",
CountryCodeAlpha3 = "CAN",
CountryCodeNumeric = "124"
};
Address originalAddress = gateway.Address.Create(customer.Id, addressCreateRequest).Target;
var addressUpdateRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America",
CountryCodeAlpha2 = "US",
CountryCodeAlpha3 = "USA",
CountryCodeNumeric = "840"
};
Address address = gateway.Address.Update(customer.Id, originalAddress.Id, addressUpdateRequest).Target;
Assert.AreEqual("Michael", address.FirstName);
Assert.AreEqual("Angelo", address.LastName);
Assert.AreEqual("Angelo Co.", address.Company);
Assert.AreEqual("1 E Main St", address.StreetAddress);
Assert.AreEqual("Apt 3", address.ExtendedAddress);
Assert.AreEqual("Chicago", address.Locality);
Assert.AreEqual("IL", address.Region);
Assert.AreEqual("60622", address.PostalCode);
Assert.AreEqual("United States of America", address.CountryName);
Assert.AreEqual("US", address.CountryCodeAlpha2);
Assert.AreEqual("USA", address.CountryCodeAlpha3);
Assert.AreEqual("840", address.CountryCodeNumeric);
}
[Test]
#if netcore
public async Task UpdateAsync_UpdatesAddressForGivenCustomerIdAndAddressId()
#else
public void UpdateAsync_UpdatesAddressForGivenCustomerIdAndAddressId()
{
Task.Run(async() =>
#endif
{
Result<Customer> customerResult = await gateway.Customer.CreateAsync(new CustomerRequest());
Customer customer = customerResult.Target;
var addressCreateRequest = new AddressRequest
{
FirstName = "Dave",
LastName = "Inchy",
Company = "Leon Ardo Co.",
StreetAddress = "1 E State St",
ExtendedAddress = "Apt 4",
Locality = "Boston",
Region = "MA",
PostalCode = "11111",
CountryName = "Canada",
CountryCodeAlpha2 = "CA",
CountryCodeAlpha3 = "CAN",
CountryCodeNumeric = "124"
};
Result<Address> addressResult = await gateway.Address.CreateAsync(customer.Id, addressCreateRequest);
Address originalAddress = addressResult.Target;
var addressUpdateRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America",
CountryCodeAlpha2 = "US",
CountryCodeAlpha3 = "USA",
CountryCodeNumeric = "840"
};
addressResult = await gateway.Address.UpdateAsync(customer.Id, originalAddress.Id, addressUpdateRequest);
Address address = addressResult.Target;
Assert.AreEqual("Michael", address.FirstName);
Assert.AreEqual("Angelo", address.LastName);
Assert.AreEqual("Angelo Co.", address.Company);
Assert.AreEqual("1 E Main St", address.StreetAddress);
Assert.AreEqual("Apt 3", address.ExtendedAddress);
Assert.AreEqual("Chicago", address.Locality);
Assert.AreEqual("IL", address.Region);
Assert.AreEqual("60622", address.PostalCode);
Assert.AreEqual("United States of America", address.CountryName);
Assert.AreEqual("US", address.CountryCodeAlpha2);
Assert.AreEqual("USA", address.CountryCodeAlpha3);
Assert.AreEqual("840", address.CountryCodeNumeric);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Update_ReturnsAnErrorResult_ForInconsistentCountry()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var addressCreateRequest = new AddressRequest
{
FirstName = "Dave",
LastName = "Inchy",
Company = "Leon Ardo Co.",
StreetAddress = "1 E State St",
ExtendedAddress = "Apt 4",
Locality = "Boston",
Region = "MA",
PostalCode = "11111",
CountryName = "Canada",
CountryCodeAlpha2 = "CA",
CountryCodeAlpha3 = "CAN",
CountryCodeNumeric = "124"
};
Address originalAddress = gateway.Address.Create(customer.Id, addressCreateRequest).Target;
var addressUpdateRequest = new AddressRequest
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America",
CountryCodeAlpha3 = "MEX"
};
Result<Address> result = gateway.Address.Update(customer.Id, originalAddress.Id, addressUpdateRequest);
Assert.AreEqual(
ValidationErrorCode.ADDRESS_INCONSISTENT_COUNTRY,
result.Errors.ForObject("Address").OnField("Base")[0].Code
);
}
[Test]
public void Delete_DeletesTheAddress()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var addressRequest = new AddressRequest
{
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
};
Address createdAddress = gateway.Address.Create(customer.Id, addressRequest).Target;
Assert.AreEqual(createdAddress.Id, gateway.Address.Find(customer.Id, createdAddress.Id).Id);
try {
Result<Address> result = gateway.Address.Delete(customer.Id, createdAddress.Id);
Assert.IsTrue(result.IsSuccess());
} catch (NotFoundException) {
Assert.Fail("Unable to delete the created address");
}
Assert.Throws<NotFoundException> (() => gateway.Address.Find(customer.Id, createdAddress.Id));
}
[Test]
#if netcore
public async Task DeleteAsync_DeletesTheAddress()
#else
public void DeleteAsync_DeletesTheAddress()
{
Task.Run(async() =>
#endif
{
Result<Customer> customerResult = await gateway.Customer.CreateAsync(new CustomerRequest());
Customer customer = customerResult.Target;
var addressRequest = new AddressRequest
{
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
};
Result<Address> addressResult = await gateway.Address.CreateAsync(customer.Id, addressRequest);
Address createdAddress = addressResult.Target;
Assert.AreEqual(createdAddress.Id, gateway.Address.Find(customer.Id, createdAddress.Id).Id);
try {
Result<Address> result = await gateway.Address.DeleteAsync(customer.Id, createdAddress.Id);
Assert.IsTrue(result.IsSuccess());
} catch (NotFoundException) {
Assert.Fail("Unable to delete the created address");
}
Assert.Throws<NotFoundException> (() => gateway.Address.Find(customer.Id, createdAddress.Id));
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Create_ReturnsAnErrorResult()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest request = new AddressRequest() { CountryName = "United States of Hammer" };
Result<Address> createResult = gateway.Address.Create(customer.Id, request);
Assert.IsFalse(createResult.IsSuccess());
Dictionary<string, string> parameters = createResult.Parameters;
Assert.AreEqual("integration_merchant_id", parameters["merchant_id"]);
Assert.AreEqual(customer.Id, parameters["customer_id"]);
Assert.AreEqual("United States of Hammer", parameters["address[country_name]"]);
}
[Test]
public void Create_ReturnsAnErrorResult_ForInconsistentCountry()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest request = new AddressRequest()
{
CountryName = "United States of America",
CountryCodeAlpha2 = "BZ"
};
Result<Address> createResult = gateway.Address.Create(customer.Id, request);
Assert.IsFalse(createResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.ADDRESS_INCONSISTENT_COUNTRY,
createResult.Errors.ForObject("Address").OnField("Base")[0].Code
);
}
[Test]
public void Create_ReturnsAnErrorResult_ForIncorrectAlpha2()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest request = new AddressRequest()
{
CountryCodeAlpha2 = "ZZ"
};
Result<Address> createResult = gateway.Address.Create(customer.Id, request);
Assert.IsFalse(createResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED,
createResult.Errors.ForObject("Address").OnField("CountryCodeAlpha2")[0].Code
);
}
[Test]
public void Create_ReturnsAnErrorResult_ForIncorrectAlpha3()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest request = new AddressRequest()
{
CountryCodeAlpha3 = "ZZZ"
};
Result<Address> createResult = gateway.Address.Create(customer.Id, request);
Assert.IsFalse(createResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED,
createResult.Errors.ForObject("Address").OnField("CountryCodeAlpha3")[0].Code
);
}
[Test]
public void Create_ReturnsAnErrorResult_ForIncorrectNumeric()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest request = new AddressRequest()
{
CountryCodeNumeric = "000"
};
Result<Address> createResult = gateway.Address.Create(customer.Id, request);
Assert.IsFalse(createResult.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED,
createResult.Errors.ForObject("Address").OnField("CountryCodeNumeric")[0].Code
);
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace ASC.Mail.Net.SIP.Stack
{
#region usings
using System;
using System.IO;
using System.Net;
using System.Threading;
using IO;
using Mime;
using TCP;
using UDP;
#endregion
/// <summary>
/// Implements SIP Flow. Defined in draft-ietf-sip-outbound.
/// </summary>
/// <remarks>A Flow is a network protocol layer (layer 4) association
/// between two hosts that is represented by the network address and
/// port number of both ends and by the protocol. For TCP, a flow is
/// equivalent to a TCP connection. For UDP a flow is a bidirectional
/// stream of datagrams between a single pair of IP addresses and
/// ports of both peers.
/// </remarks>
public class SIP_Flow : IDisposable
{
#region Events
/// <summary>
/// Is raised when flow is disposing.
/// </summary>
public event EventHandler IsDisposing = null;
#endregion
#region Members
private readonly DateTime m_CreateTime;
private readonly string m_ID = "";
private readonly bool m_IsServer;
private readonly IPEndPoint m_pLocalEP;
private readonly object m_pLock = new object();
private readonly IPEndPoint m_pRemoteEP;
private readonly SIP_Stack m_pStack;
private readonly string m_Transport = "";
private long m_BytesWritten;
private bool m_IsDisposed;
private DateTime m_LastActivity;
private bool m_LastCRLF;
private TimerEx m_pKeepAliveTimer;
private MemoryStream m_pMessage;
private TCP_Session m_pTcpSession;
#endregion
#region Properties
/// <summary>
/// Gets if this object is disposed.
/// </summary>
public bool IsDisposed
{
get { return m_IsDisposed; }
}
/// <summary>
/// Gets if this flow is server flow or client flow.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public bool IsServer
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_IsServer;
}
}
/// <summary>
/// Gets time when flow was created.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public DateTime CreateTime
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_CreateTime;
}
}
/// <summary>
/// Gets flow ID.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public string ID
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_ID;
}
}
/// <summary>
/// Gets flow local IP end point.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public IPEndPoint LocalEP
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_pLocalEP;
}
}
/// <summary>
/// Gets flow remote IP end point.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public IPEndPoint RemoteEP
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_pRemoteEP;
}
}
/// <summary>
/// Gets flow transport.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public string Transport
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_Transport;
}
}
/// <summary>
/// Gets if flow is reliable transport.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public bool IsReliable
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_Transport != SIP_Transport.UDP;
}
}
/// <summary>
/// Gets if this connection is secure.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public bool IsSecure
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
if (m_Transport == SIP_Transport.TLS)
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// Gets or sets if flow sends keep-alive packets.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public bool SendKeepAlives
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_pKeepAliveTimer != null;
}
set
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
if (value)
{
if (m_pKeepAliveTimer == null)
{
m_pKeepAliveTimer = new TimerEx(15000, true);
m_pKeepAliveTimer.Elapsed += delegate
{
// Log:
if (m_pStack.TransportLayer.Stack.Logger != null)
{
m_pStack.TransportLayer.Stack.Logger.AddWrite
("",
null,
2,
"Flow [id='" + ID + "'] sent \"ping\"",
LocalEP,
RemoteEP);
}
try
{
SendInternal(new[]
{
(byte) '\r', (byte) '\n',
(byte) '\r', (byte) '\n'
});
}
catch
{
// We don't care about errors here.
}
};
m_pKeepAliveTimer.Enabled = true;
}
}
else
{
if (m_pKeepAliveTimer != null)
{
m_pKeepAliveTimer.Dispose();
m_pKeepAliveTimer = null;
}
}
}
}
/// <summary>
/// Gets when flow had last(send or receive) activity.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public DateTime LastActivity
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
if (m_Transport == SIP_Transport.TCP || m_Transport == SIP_Transport.TLS)
{
return m_pTcpSession.LastActivity;
}
else
{
return m_LastActivity;
}
}
}
// TODO: BytesReaded
/// <summary>
/// Gets how many bytes this flow has sent to remote party.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public long BytesWritten
{
get
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return m_BytesWritten;
}
}
#endregion
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="stack">Owner stack.</param>
/// <param name="isServer">Specifies if flow is server or client flow.</param>
/// <param name="localEP">Local IP end point.</param>
/// <param name="remoteEP">Remote IP end point.</param>
/// <param name="transport">SIP transport.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>localEP</b>,<b>remoteEP</b> or <b>transport</b> is null reference.</exception>
/// <exception cref="ArgumentException">Is raised whena any of the arguments has invalid value.</exception>
internal SIP_Flow(SIP_Stack stack,
bool isServer,
IPEndPoint localEP,
IPEndPoint remoteEP,
string transport)
{
if (stack == null)
{
throw new ArgumentNullException("stack");
}
if (localEP == null)
{
throw new ArgumentNullException("localEP");
}
if (remoteEP == null)
{
throw new ArgumentNullException("remoteEP");
}
if (transport == null)
{
throw new ArgumentNullException("transport");
}
m_pStack = stack;
m_IsServer = isServer;
m_pLocalEP = localEP;
m_pRemoteEP = remoteEP;
m_Transport = transport.ToUpper();
m_CreateTime = DateTime.Now;
m_LastActivity = DateTime.Now;
m_ID = m_pLocalEP + "-" + m_pRemoteEP + "-" + m_Transport;
m_pMessage = new MemoryStream();
}
/// <summary>
/// Server TCP,TLS constructor.
/// </summary>
/// <param name="stack">Owner stack.</param>
/// <param name="session">TCP session.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>stack</b> or <b>session</b> is null reference.</exception>
internal SIP_Flow(SIP_Stack stack, TCP_Session session)
{
if (stack == null)
{
throw new ArgumentNullException("stack");
}
if (session == null)
{
throw new ArgumentNullException("session");
}
m_pStack = stack;
m_pTcpSession = session;
m_IsServer = true;
m_pLocalEP = session.LocalEndPoint;
m_pRemoteEP = session.RemoteEndPoint;
m_Transport = session.IsSecureConnection ? SIP_Transport.TLS : SIP_Transport.TCP;
m_CreateTime = DateTime.Now;
m_LastActivity = DateTime.Now;
m_ID = m_pLocalEP + "-" + m_pRemoteEP + "-" + m_Transport;
m_pMessage = new MemoryStream();
BeginReadHeader();
}
#endregion
#region Methods
/// <summary>
/// Cleans up any resources being used.
/// </summary>
public void Dispose()
{
lock (m_pLock)
{
if (m_IsDisposed)
{
return;
}
OnDisposing();
m_IsDisposed = true;
if (m_pTcpSession != null)
{
m_pTcpSession.Dispose();
m_pTcpSession = null;
}
m_pMessage = null;
if (m_pKeepAliveTimer != null)
{
m_pKeepAliveTimer.Dispose();
m_pKeepAliveTimer = null;
}
}
}
/// <summary>
/// Sends specified request to flow remote end point.
/// </summary>
/// <param name="request">SIP request to send.</param>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
/// <exception cref="ArgumentNullException">Is raised when <b>request</b> is null reference.</exception>
public void Send(SIP_Request request)
{
lock (m_pLock)
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
if (request == null)
{
throw new ArgumentNullException("request");
}
SendInternal(request.ToByteData());
}
}
/// <summary>
/// Sends specified response to flow remote end point.
/// </summary>
/// <param name="response">SIP response to send.</param>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
/// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference.</exception>
public void Send(SIP_Response response)
{
lock (m_pLock)
{
if (m_IsDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
if (response == null)
{
throw new ArgumentNullException("response");
}
SendInternal(response.ToByteData());
}
}
#endregion
#region Utility methods
/// <summary>
/// Starts reading SIP message header.
/// </summary>
private void BeginReadHeader()
{
// Clear old data.
m_pMessage.SetLength(0);
// Start reading SIP message header.
m_pTcpSession.TcpStream.BeginReadHeader(m_pMessage,
m_pStack.TransportLayer.Stack.MaximumMessageSize,
SizeExceededAction.JunkAndThrowException,
BeginReadHeader_Completed,
null);
}
/// <summary>
/// This method is called when SIP message header reading has completed.
/// </summary>
/// <param name="asyncResult">An IAsyncResult that represents an asynchronous call.</param>
private void BeginReadHeader_Completed(IAsyncResult asyncResult)
{
try
{
int countStored = m_pTcpSession.TcpStream.EndReadHeader(asyncResult);
// We got CRLF(ping or pong).
if (countStored == 0)
{
// We have ping request.
if (IsServer)
{
// We have full ping request.
if (m_LastCRLF)
{
m_LastCRLF = false;
m_pStack.TransportLayer.OnMessageReceived(this,
new[]
{
(byte) '\r', (byte) '\n',
(byte) '\r', (byte) '\n'
});
}
// We have first CRLF of ping request.
else
{
m_LastCRLF = true;
}
}
// We got pong to our ping request.
else
{
m_pStack.TransportLayer.OnMessageReceived(this, new[] {(byte) '\r', (byte) '\n'});
}
// Wait for new SIP message.
BeginReadHeader();
}
// We have SIP message header.
else
{
m_LastCRLF = false;
// Add header terminator blank line.
m_pMessage.Write(new[] {(byte) '\r', (byte) '\n'}, 0, 2);
m_pMessage.Position = 0;
string contentLengthValue = MimeUtils.ParseHeaderField("Content-Length:", m_pMessage);
m_pMessage.Position = m_pMessage.Length;
int contentLength = 0;
// Read message body.
if (contentLengthValue != "")
{
contentLength = Convert.ToInt32(contentLengthValue);
}
// Start reading message body.
if (contentLength > 0)
{
// Read body data.
m_pTcpSession.TcpStream.BeginReadFixedCount(m_pMessage,
contentLength,
BeginReadData_Completed,
null);
}
// Message with no body.
else
{
byte[] messageData = m_pMessage.ToArray();
// Wait for new SIP message.
BeginReadHeader();
m_pStack.TransportLayer.OnMessageReceived(this, messageData);
}
}
}
catch
{
Dispose();
}
}
/// <summary>
/// This method is called when SIP message data reading has completed.
/// </summary>
/// <param name="asyncResult">An IAsyncResult that represents an asynchronous call.</param>
private void BeginReadData_Completed(IAsyncResult asyncResult)
{
try
{
m_pTcpSession.TcpStream.EndReadFixedCount(asyncResult);
byte[] messageData = m_pMessage.ToArray();
// Wait for new SIP message.
BeginReadHeader();
m_pStack.TransportLayer.OnMessageReceived(this, messageData);
}
catch
{
Dispose();
}
}
/// <summary>
/// Raises <b>Disposed</b> event.
/// </summary>
private void OnDisposing()
{
if (IsDisposing != null)
{
IsDisposing(this, new EventArgs());
}
}
#endregion
#region Internal methods
/// <summary>
/// Starts flow processing.
/// </summary>
internal void Start()
{
// Move processing to thread pool.
AutoResetEvent startLock = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(delegate
{
lock (m_pLock)
{
startLock.Set();
// TCP / TLS client, connect to remote end point.
if (!m_IsServer && m_Transport != SIP_Transport.UDP)
{
try
{
TCP_Client client = new TCP_Client();
client.Connect(m_pLocalEP,
m_pRemoteEP,
m_Transport == SIP_Transport.TLS);
m_pTcpSession = client;
BeginReadHeader();
}
catch
{
Dispose();
}
}
}
});
startLock.WaitOne();
}
/// <summary>
/// Sends specified data to the remote end point.
/// </summary>
/// <param name="data">Data to send.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>data</b> is null reference.</exception>
internal void SendInternal(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
try
{
if (m_Transport == SIP_Transport.UDP)
{
m_pStack.TransportLayer.UdpServer.SendPacket(m_pLocalEP, data, 0, data.Length, m_pRemoteEP);
}
else if (m_Transport == SIP_Transport.TCP)
{
m_pTcpSession.TcpStream.Write(data, 0, data.Length);
}
else if (m_Transport == SIP_Transport.TLS)
{
m_pTcpSession.TcpStream.Write(data, 0, data.Length);
}
m_BytesWritten += data.Length;
}
catch (IOException x)
{
Dispose();
throw x;
}
}
/// <summary>
/// This method is called when flow gets new UDP packet.
/// </summary>
/// <param name="e">UDP data.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>e</b> is null reference.</exception>
internal void OnUdpPacketReceived(UDP_PacketEventArgs e)
{
if (e == null)
{
throw new ArgumentNullException("e");
}
m_LastActivity = DateTime.Now;
m_pStack.TransportLayer.OnMessageReceived(this, e.Data);
}
#endregion
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Sce.Atf.Applications;
using Sce.Sled.Resources;
using Sce.Sled.Shared;
using Sce.Sled.Shared.Services;
namespace Sce.Sled
{
/// <summary>
/// Find/Replace In Files Form
/// </summary>
partial class SledFindAndReplaceForm : Form
{
/// <summary>
/// Constructor
/// </summary>
private SledFindAndReplaceForm()
{
s_instance = this;
InitializeComponent();
if (!StartLocation.IsEmpty)
{
StartPosition = FormStartPosition.Manual;
Location = StartLocation;
}
// Associate SledFindAndReplaceModes enum to find/replace buttons
m_strpFindDropDown_QuickFindItem.Tag = SledFindAndReplaceModes.QuickFind;
m_strpFindDropDown_FindInFilesItem.Tag = SledFindAndReplaceModes.FindInFiles;
m_strpReplaceDropDown_QuickReplaceItem.Tag = SledFindAndReplaceModes.QuickReplace;
m_strpReplaceDropDown_ReplaceInFilesItem.Tag = SledFindAndReplaceModes.ReplaceInFiles;
//
// Add all individual find/replace controls to the form
//
// Add "Quick Find"
m_frmQuickFind = new SledFindAndReplaceForm_QuickFind {Tag = SledFindAndReplaceModes.QuickFind};
m_lstForms.Add(m_frmQuickFind);
m_frmQuickFind.FindAndReplaceEvent += SubFormFindAndReplaceEvent;
// Add "Find In Files"
m_frmFindInFiles = new SledFindAndReplaceForm_FindInFiles {Tag = SledFindAndReplaceModes.FindInFiles};
m_lstForms.Add(m_frmFindInFiles);
m_frmFindInFiles.FindAndReplaceEvent += SubFormFindAndReplaceEvent;
// Add "Quick Replace"
m_frmQuickReplace = new SledFindAndReplaceForm_QuickReplace {Tag = SledFindAndReplaceModes.QuickReplace};
m_lstForms.Add(m_frmQuickReplace);
m_frmQuickReplace.FindAndReplaceEvent += SubFormFindAndReplaceEvent;
// Add "Replace In Files"
m_frmReplaceInFiles = new SledFindAndReplaceForm_ReplaceInFiles {Tag = SledFindAndReplaceModes.ReplaceInFiles};
m_lstForms.Add(m_frmReplaceInFiles);
m_frmReplaceInFiles.FindAndReplaceEvent += SubFormFindAndReplaceEvent;
SkinService.SkinChangedOrApplied += SkinServiceSkinChangedOrApplied;
ApplySkin();
}
/// <summary>
/// Hide the base class Show() method
/// </summary>
public new void Show()
{
Show(null);
}
/// <summary>
/// Hide the base class Show() method
/// </summary>
/// <param name="owner"></param>
public new void Show(IWin32Window owner)
{
if (Visible)
Activate();
else
base.Show(owner);
}
/// <summary>
/// Gets/sets the find/replace mode to use
/// </summary>
public SledFindAndReplaceModes Mode
{
get { return m_mode; }
set
{
var bChangeMode = (m_bLoaded && (m_mode != value));
m_mode = value;
if (bChangeMode)
ChangeMode(value);
}
}
/// <summary>
/// Initial text to input in the find or replace form
/// </summary>
public string InitialText { get; set; }
/// <summary>
/// Check if the Find In Files dialog already exists or not
/// </summary>
public static SledFindAndReplaceForm Instance
{
get { return s_instance ?? (s_instance = new SledFindAndReplaceForm()); }
}
private static SledFindAndReplaceForm s_instance;
/// <summary>
/// Gets/sets the start location of the form
/// </summary>
public static Point StartLocation { get; set; }
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape)
Close();
return base.ProcessCmdKey(ref msg, keyData);
}
private void StrpDropDownDropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Tag == null)
return;
var mode = (SledFindAndReplaceModes)e.ClickedItem.Tag;
if (Mode != mode)
ChangeMode(mode);
}
private void SledFindAndReplaceFormLoad(object sender, EventArgs e)
{
if (m_mode == SledFindAndReplaceModes.None)
m_mode = SledFindAndReplaceModes.QuickFind;
m_bLoaded = true;
}
private void SledFindAndReplaceFormShown(object sender, EventArgs e)
{
if (!m_firstShown)
{
ChangeMode(Mode);
m_firstShown = true;
}
}
private void SledFindAndReplaceFormFormClosed(object sender, FormClosedEventArgs e)
{
SkinService.SkinChangedOrApplied -= SkinServiceSkinChangedOrApplied;
s_instance = null;
}
private void SubFormFindAndReplaceEvent(object sender, SledFindAndReplaceEventArgs e)
{
// Run find or replace event
((SledFindAndReplaceService)m_findAndReplaceService.Get).Run(e);
var bMakeSound = true;
// Check result
switch (e.Result)
{
// Do nothing
case SledFindAndReplaceResult.Success:
bMakeSound = false;
break;
// No results were found
case SledFindAndReplaceResult.NothingFound:
SledOutDevice.OutLine(SledMessageType.Info, Localization.SledFindAndReplaceErrorNothingFound);
break;
// No documents to search in
case SledFindAndReplaceResult.NothingToSearch:
SledOutDevice.OutLine(SledMessageType.Info, Localization.SledFindAndReplaceErrorNoDocsToSearch);
break;
default: NotifyMissingResultProperty(this); break;
}
// Beep if not successful
if (bMakeSound)
{
// Beep like VS does
System.Media.SystemSounds.Exclamation.Play();
}
}
[System.Diagnostics.Conditional("DEBUG")]
private static void NotifyMissingResultProperty(IWin32Window form)
{
SledOutDevice.OutLine(SledMessageType.Warning, "[Find & Replace] Your find or replace event needs to set the \"Result\" property!");
MessageBox.Show(form, "Your find or replace event needs to set the \"Result\" property!");
}
private void ChangeMode(SledFindAndReplaceModes mode)
{
m_mode = mode;
ISledFindAndReplaceSubForm theFrm = null;
// Activate correct control and deactivate incorrect control
foreach (ISledFindAndReplaceSubForm frm in m_lstForms)
{
if ((SledFindAndReplaceModes)frm.Control.Tag == Mode)
theFrm = frm;
Controls.Remove(frm.Control);
}
if (theFrm == null)
return;
Controls.Add(theFrm.Control);
theFrm.InitialText = InitialText;
Invalidate(true);
}
private void SledFindAndReplaceFormLocationChanged(object sender, EventArgs e)
{
StartLocation = Location;
}
private void SkinServiceSkinChangedOrApplied(object sender, EventArgs e)
{
ApplySkin();
}
private void ApplySkin()
{
foreach (var frm in m_lstForms)
SkinService.ApplyActiveSkin(frm.Control);
var mode = Mode;
ChangeMode(SledFindAndReplaceModes.None);
ChangeMode(mode);
}
private readonly SledFindAndReplaceForm_QuickFind m_frmQuickFind;
private readonly SledFindAndReplaceForm_FindInFiles m_frmFindInFiles;
private readonly SledFindAndReplaceForm_QuickReplace m_frmQuickReplace;
private readonly SledFindAndReplaceForm_ReplaceInFiles m_frmReplaceInFiles;
private readonly IList<ISledFindAndReplaceSubForm> m_lstForms = new List<ISledFindAndReplaceSubForm>();
private readonly SledServiceReference<ISledFindAndReplaceService> m_findAndReplaceService =
new SledServiceReference<ISledFindAndReplaceService>();
private bool m_bLoaded;
private bool m_firstShown;
private SledFindAndReplaceModes m_mode = SledFindAndReplaceModes.None;
/// <summary>
/// Utility class for a ComboBox item and to also aid with embedding some data with a string on the ComboBox
/// </summary>
public class TextAssociation
{
public TextAssociation(string text, object tag)
{
m_text = text;
m_tag = tag;
}
public override string ToString()
{
if (m_text == null)
return string.Empty;
return m_text;
}
public string Text
{
get { return m_text; }
}
public object Tag
{
get { return m_tag; }
}
private readonly string m_text;
private readonly object m_tag;
}
}
}
| |
namespace AngleSharp.Io
{
using AngleSharp.Text;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Contains a list of common mime-types.
/// </summary>
public static class MimeTypeNames
{
#region Fields
private static readonly String[] CommonJsTypes = new[]
{
"application/ecmascript",
"application/javascript",
"application/x-ecmascript",
"application/x-javascript",
"text/ecmascript",
"text/javascript",
"text/javascript1.0",
"text/javascript1.1",
"text/javascript1.2",
"text/javascript1.3",
"text/javascript1.4",
"text/javascript1.5",
"text/jscript",
"text/livescript",
"text/x-ecmascript",
"text/x-javascript",
};
#endregion
#region Map File extensions to Mime types
private static readonly Dictionary<String, String> Extensions = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase)
{
{ ".3dm", "x-world/x-3dmf" },
{ ".3dmf", "x-world/x-3dmf" },
{ ".a", "application/octet-stream" },
{ ".aab", "application/x-authorware-bin" },
{ ".aam", "application/x-authorware-map" },
{ ".aas", "application/x-authorware-seg" },
{ ".abc", "text/vnd.abc" },
{ ".acgi", "text/html" },
{ ".afl", "video/animaflex" },
{ ".ai", "application/postscript" },
{ ".aif", "audio/aiff" },
{ ".aifc", "audio/aiff" },
{ ".aiff", "audio/aiff" },
{ ".aim", "application/x-aim" },
{ ".aip", "text/x-audiosoft-intra" },
{ ".ani", "application/x-navi-animation" },
{ ".aos", "application/x-nokia-9000-communicator-add-on-software" },
{ ".apng", "image/apng" },
{ ".aps", "application/mime" },
{ ".arc", "application/octet-stream" },
{ ".arj", "application/arj" },
{ ".art", "image/x-jg" },
{ ".asf", "video/x-ms-asf" },
{ ".asm", "text/x-asm" },
{ ".asp", "text/asp" },
{ ".asx", "application/x-mplayer2" },
{ ".au", "audio/basic" },
{ ".avi", "video/avi" },
{ ".avif", "image/avif" },
{ ".avifs", "image/avif-sequence" },
{ ".avs", "video/avs-video" },
{ ".bcpio", "application/x-bcpio" },
{ ".bin", "application/octet-stream" },
{ ".bm", "image/bmp" },
{ ".bmp", "image/bmp" },
{ ".boo", "application/book" },
{ ".book", "application/book" },
{ ".boz", "application/x-bzip2" },
{ ".bsh", "application/x-bsh" },
{ ".bz", "application/x-bzip" },
{ ".bz2", "application/x-bzip2" },
{ ".c", "text/plain" },
{ ".cat", "application/vnd.ms-pki.seccat" },
{ ".cc", "text/plain" },
{ ".ccad", "application/clariscad" },
{ ".cco", "application/x-cocoa" },
{ ".cdf", "application/cdf" },
{ ".cer", "application/x-x509-ca-cert" },
{ ".cha", "application/x-chat" },
{ ".chat", "application/x-chat" },
{ ".class", "application/java" },
{ ".com", "application/octet-stream" },
{ ".conf", "text/plain" },
{ ".cpio", "application/x-cpio" },
{ ".cpp", "text/x-c" },
{ ".cpt", "application/x-cpt" },
{ ".crl", "application/pkix-crl" },
{ ".crt", "application/x-x509-ca-cert" },
{ ".csh", "application/x-csh" },
{ ".css", "text/css" },
{ ".cxx", "text/plain" },
{ ".dcr", "application/x-director" },
{ ".deepv", "application/x-deepv" },
{ ".def", "text/plain" },
{ ".der", "application/x-x509-ca-cert" },
{ ".dif", "video/x-dv" },
{ ".dir", "application/x-director" },
{ ".dl", "video/dl" },
{ ".doc", "application/msword" },
{ ".dot", "application/msword" },
{ ".dp", "application/commonground" },
{ ".drw", "application/drafting" },
{ ".dump", "application/octet-stream" },
{ ".dv", "video/x-dv" },
{ ".dvi", "application/x-dvi" },
{ ".dwf", "model/vnd.dwf" },
{ ".dwg", "application/acad" },
{ ".dxf", "application/dxf" },
{ ".dxr", "application/x-director" },
{ ".el", "text/x-script.elisp" },
{ ".elc", "application/x-elc" },
{ ".env", "application/x-envoy" },
{ ".eps", "application/postscript" },
{ ".es", "application/x-esrehber" },
{ ".etx", "text/x-setext" },
{ ".evy", "application/envoy" },
{ ".exe", "application/octet-stream" },
{ ".f", "text/plain" },
{ ".f77", "text/x-fortran" },
{ ".f90", "text/plain" },
{ ".fdf", "application/vnd.fdf" },
{ ".fif", "image/fif" },
{ ".fli", "video/fli" },
{ ".flo", "image/florian" },
{ ".flx", "text/vnd.fmi.flexstor" },
{ ".fmf", "video/x-atomic3d-feature" },
{ ".for", "text/plain" },
{ ".fpx", "image/vnd.fpx" },
{ ".frl", "application/freeloader" },
{ ".funk", "audio/make" },
{ ".g", "text/plain" },
{ ".g3", "image/g3fax" },
{ ".gif", "image/gif" },
{ ".gl", "video/gl" },
{ ".gsd", "audio/x-gsm" },
{ ".gsm", "audio/x-gsm" },
{ ".gsp", "application/x-gsp" },
{ ".gss", "application/x-gss" },
{ ".gtar", "application/x-gtar" },
{ ".gz", "application/x-gzip" },
{ ".gzip", "application/x-gzip" },
{ ".h", "text/plain" },
{ ".hdf", "application/x-hdf" },
{ ".help", "application/x-helpfile" },
{ ".hgl", "application/vnd.hp-hpgl" },
{ ".hh", "text/plain" },
{ ".hlb", "text/x-script" },
{ ".hlp", "application/hlp" },
{ ".hpg", "application/vnd.hp-hpgl" },
{ ".hpgl", "application/vnd.hp-hpgl" },
{ ".hqx", "application/binhex" },
{ ".hta", "application/hta" },
{ ".htc", "text/x-component" },
{ ".htm", "text/html" },
{ ".html", "text/html" },
{ ".htmls", "text/html" },
{ ".htt", "text/webviewhtml" },
{ ".htx", "text/html" },
{ ".ice", "x-conference/x-cooltalk" },
{ ".ico", "image/x-icon" },
{ ".idc", "text/plain" },
{ ".ief", "image/ief" },
{ ".iefs", "image/ief" },
{ ".iges", "application/iges" },
{ ".igs", "application/iges" },
{ ".ima", "application/x-ima" },
{ ".imap", "application/x-httpd-imap" },
{ ".inf", "application/inf" },
{ ".ins", "application/x-internett-signup" },
{ ".ip", "application/x-ip2" },
{ ".isu", "video/x-isvideo" },
{ ".it", "audio/it" },
{ ".iv", "application/x-inventor" },
{ ".ivr", "i-world/i-vrml" },
{ ".ivy", "application/x-livescreen" },
{ ".jam", "audio/x-jam" },
{ ".jav", "text/plain" },
{ ".java", "text/plain" },
{ ".jcm", "application/x-java-commerce" },
{ ".jfif", "image/jpeg" },
{ ".jpe", "image/jpeg" },
{ ".jpeg", "image/jpeg" },
{ ".jpg", "image/jpeg" },
{ ".jps", "image/x-jps" },
{ ".js", "application/javascript" },
{ ".jxl", "image/jxl" },
{ ".jut", "image/jutvision" },
{ ".kar", "audio/midi" },
{ ".ksh", "application/x-ksh" },
{ ".la", "audio/nspaudio" },
{ ".lam", "audio/x-liveaudio" },
{ ".latex", "application/x-latex" },
{ ".lha", "application/lha" },
{ ".lhx", "application/octet-stream" },
{ ".list", "text/plain" },
{ ".lma", "audio/nspaudio" },
{ ".log", "text/plain" },
{ ".lsp", "application/x-lisp" },
{ ".lst", "text/plain" },
{ ".lsx", "text/x-la-asf" },
{ ".ltx", "application/x-latex" },
{ ".lzh", "application/x-lzh" },
{ ".lzx", "application/lzx" },
{ ".m", "text/plain" },
{ ".m1v", "video/mpeg" },
{ ".m2a", "audio/mpeg" },
{ ".m2v", "video/mpeg" },
{ ".m3u", "audio/x-mpequrl" },
{ ".man", "application/x-troff-man" },
{ ".map", "application/x-navimap" },
{ ".mar", "text/plain" },
{ ".mbd", "application/mbedlet" },
{ ".mc", " application/x-magic-cap-package-1.0" },
{ ".mcd", "application/mcad" },
{ ".mcf", "image/vasa" },
{ ".mcp", "application/netmc" },
{ ".me", "application/x-troff-me" },
{ ".mht", "message/rfc822" },
{ ".mhtml", "message/rfc822" },
{ ".mid", "audio/midi" },
{ ".midi", "audio/midi" },
{ ".mif", "application/x-frame" },
{ ".mime", "www/mime" },
{ ".mjf", "audio/x-vnd.audioexplosion.mjuicemediafile" },
{ ".mjpg", "video/x-motion-jpeg" },
{ ".mm", "application/x-meme" },
{ ".mme", "application/base64" },
{ ".mod", "audio/mod" },
{ ".moov", "video/quicktime" },
{ ".mov", "video/quicktime" },
{ ".movie", "video/x-sgi-movie" },
{ ".mp2", "audio/mpeg" },
{ ".mp3", "audio/mpeg3" },
{ ".mpa", "audio/mpeg" },
{ ".mpc", "application/x-project" },
{ ".mpe", "video/mpeg" },
{ ".mpeg", "video/mpeg" },
{ ".mpg", "video/mpeg" },
{ ".mpga", "audio/mpeg" },
{ ".mpp", "application/vnd.ms-project" },
{ ".mpt", "application/x-project" },
{ ".mpv", "application/x-project" },
{ ".mpx", "application/x-project" },
{ ".mrc", "application/marc" },
{ ".ms", "application/x-troff-ms" },
{ ".mv", "video/x-sgi-movie" },
{ ".my", "audio/make" },
{ ".mzz", "application/x-vnd.audioexplosion.mzz" },
{ ".nap", "image/naplps" },
{ ".naplps", "image/naplps" },
{ ".nc", "application/x-netcdf" },
{ ".ncm", "application/vnd.nokia.configuration-message" },
{ ".nif", "image/x-niff" },
{ ".niff", "image/x-niff" },
{ ".nix", "application/x-mix-transfer" },
{ ".nsc", "application/x-conference" },
{ ".nvd", "application/x-navidoc" },
{ ".o", "application/octet-stream" },
{ ".oda", "application/oda" },
{ ".omc", "application/x-omc" },
{ ".omcd", "application/x-omcdatamaker" },
{ ".omcr", "application/x-omcregerator" },
{ ".p", "text/x-pascal" },
{ ".p10", "application/pkcs10" },
{ ".p12", "application/pkcs-12" },
{ ".p7a", "application/x-pkcs7-signature" },
{ ".p7c", "application/pkcs7-mime" },
{ ".p7m", "application/pkcs7-mime" },
{ ".p7r", "application/x-pkcs7-certreqresp" },
{ ".p7s", "application/pkcs7-signature" },
{ ".part", "application/pro_eng" },
{ ".pas", "text/pascal" },
{ ".pbm", "image/x-portable-bitmap" },
{ ".pcl", "application/vnd.hp-pcl" },
{ ".pct", "image/x-pict" },
{ ".pcx", "image/x-pcx" },
{ ".pdb", "chemical/x-pdb" },
{ ".pdf", "application/pdf" },
{ ".pfunk", "audio/make" },
{ ".pgm", "image/x-portable-graymap" },
{ ".pic", "image/pict" },
{ ".pict", "image/pict" },
{ ".pkg", "application/x-newton-compatible-pkg" },
{ ".pko", "application/vnd.ms-pki.pko" },
{ ".pl", "text/plain" },
{ ".plx", "application/x-pixclscript" },
{ ".pm", "image/x-xpixmap" },
{ ".pm4", "application/x-pagemaker" },
{ ".pm5", "application/x-pagemaker" },
{ ".png", "image/png" },
{ ".pnm", "application/x-portable-anymap" },
{ ".pot", "application/mspowerpoint" },
{ ".pov", "model/x-pov" },
{ ".ppa", "application/vnd.ms-powerpoint" },
{ ".ppm", "image/x-portable-pixmap" },
{ ".pps", "application/mspowerpoint" },
{ ".ppt", "application/powerpoint" },
{ ".ppz", "application/mspowerpoint" },
{ ".pre", "application/x-freelance" },
{ ".prt", "application/pro_eng" },
{ ".ps", "application/postscript" },
{ ".psd", "application/octet-stream" },
{ ".pvu", "paleovu/x-pv" },
{ ".pwz", "application/vnd.ms-powerpoint" },
{ ".py", "text/x-script.phyton" },
{ ".pyc", "applicaiton/x-bytecode.python" },
{ ".qcp", "audio/vnd.qcelp" },
{ ".qd3", "x-world/x-3dmf" },
{ ".qd3d", "x-world/x-3dmf" },
{ ".qif", "image/x-quicktime" },
{ ".qt", "video/quicktime" },
{ ".qtc", "video/x-qtc" },
{ ".qti", "image/x-quicktime" },
{ ".qtif", "image/x-quicktime" },
{ ".ra", "audio/x-realaudio" },
{ ".ram", "audio/x-pn-realaudio" },
{ ".ras", "image/cmu-raster" },
{ ".rast", "image/cmu-raster" },
{ ".rexx", "text/x-script.rexx" },
{ ".rf", "image/vnd.rn-realflash" },
{ ".rgb", "image/x-rgb" },
{ ".rm", "audio/x-pn-realaudio" },
{ ".rmi", "audio/mid" },
{ ".rmm", "audio/x-pn-realaudio" },
{ ".rmp", "audio/x-pn-realaudio" },
{ ".rng", "application/ringing-tones" },
{ ".rnx", "application/vnd.rn-realplayer" },
{ ".roff", "application/x-troff" },
{ ".rp", "image/vnd.rn-realpix" },
{ ".rpm", "audio/x-pn-realaudio-plugin" },
{ ".rt", "text/richtext" },
{ ".rtf", "application/rtf" },
{ ".rtx", "application/rtf" },
{ ".rv", "video/vnd.rn-realvideo" },
{ ".s", "text/x-asm" },
{ ".s3m", "audio/s3m" },
{ ".saveme", "application/octet-stream" },
{ ".sbk", "application/x-tbook" },
{ ".scm", "video/x-scm" },
{ ".sdml", "text/plain" },
{ ".sdp", "application/sdp" },
{ ".sdr", "application/sounder" },
{ ".sea", "application/sea" },
{ ".set", "application/set" },
{ ".sgm", "text/sgml" },
{ ".sgml", "text/sgml" },
{ ".sh", "application/x-sh" },
{ ".shar", "application/x-bsh" },
{ ".shtml", "text/html" },
{ ".sid", "audio/x-psid" },
{ ".sit", "application/x-sit" },
{ ".skd", "application/x-koan" },
{ ".skm", "application/x-koan" },
{ ".skp", "application/x-koan" },
{ ".skt", "application/x-koan" },
{ ".sl", "application/x-seelogo" },
{ ".smi", "application/smil" },
{ ".smil", "application/smil" },
{ ".snd", "audio/basic" },
{ ".sol", "application/solids" },
{ ".spc", "application/x-pkcs7-certificates" },
{ ".spl", "application/futuresplash" },
{ ".spr", "application/x-sprite" },
{ ".sprite", "application/x-sprite" },
{ ".src", "application/x-wais-source" },
{ ".ssi", "text/x-server-parsed-html" },
{ ".ssm", "application/streamingmedia" },
{ ".sst", "application/vnd.ms-pki.certstore" },
{ ".step", "application/step" },
{ ".stl", "application/sla" },
{ ".stp", "application/step" },
{ ".sv4cpio", "application/x-sv4cpio" },
{ ".sv4crc", "application/x-sv4crc" },
{ ".svf", "image/vnd.dwg" },
{ ".svg", "image/svg+xml" },
{ ".swf", "application/x-shockwave-flash" },
{ ".t", "application/x-troff" },
{ ".talk", "text/x-speech" },
{ ".tar", "application/x-tar" },
{ ".tbk", "application/toolbook" },
{ ".tcl", "application/x-tcl" },
{ ".tcsh", "text/x-script.tcsh" },
{ ".tex", "application/x-tex" },
{ ".texi", "application/x-texinfo" },
{ ".texinfo", "application/x-texinfo" },
{ ".text", "text/plain" },
{ ".tgz", "application/gnutar" },
{ ".tif", "image/tiff" },
{ ".tiff", "image/tiff" },
{ ".tr", "application/x-troff" },
{ ".tsi", "audio/tsp-audio" },
{ ".tsp", "audio/tsplayer" },
{ ".tsv", "text/tab-separated-values" },
{ ".turbot", "image/florian" },
{ ".txt", "text/plain" },
{ ".uil", "text/x-uil" },
{ ".uni", "text/uri-list" },
{ ".unis", "text/uri-list" },
{ ".unv", "application/i-deas" },
{ ".uri", "text/uri-list" },
{ ".uris", "text/uri-list" },
{ ".ustar", "application/x-ustar" },
{ ".uu", "text/x-uuencode" },
{ ".uue", "text/x-uuencode" },
{ ".vcd", "application/x-cdlink" },
{ ".vcs", "text/x-vcalendar" },
{ ".vda", "application/vda" },
{ ".vdo", "video/vdo" },
{ ".vew", "application/groupwise" },
{ ".viv", "video/vivo" },
{ ".vivo", "video/vivo" },
{ ".vmd", "application/vocaltec-media-desc" },
{ ".vmf", "application/vocaltec-media-file" },
{ ".voc", "audio/voc" },
{ ".vos", "video/vosaic" },
{ ".vox", "audio/voxware" },
{ ".vqe", "audio/x-twinvq-plugin" },
{ ".vqf", "audio/x-twinvq" },
{ ".vql", "audio/x-twinvq-plugin" },
{ ".vrml", "model/vrml" },
{ ".vrt", "x-world/x-vrt" },
{ ".vsd", "application/x-visio" },
{ ".vst", "application/x-visio" },
{ ".vsw", "application/x-visio" },
{ ".w60", "application/wordperfect6.0" },
{ ".w61", "application/wordperfect6.1" },
{ ".w6w", "application/msword" },
{ ".wav", "audio/wav" },
{ ".wb1", "application/x-qpro" },
{ ".wbmp", "image/vnd.wap.wbmp" },
{ ".web", "application/vnd.xara" },
{ ".webp", "image/webp" },
{ ".wiz", "application/msword" },
{ ".wk1", "application/x-123" },
{ ".wmf", "windows/metafile" },
{ ".wml", "text/vnd.wap.wml" },
{ ".wmlc", "application/vnd.wap.wmlc" },
{ ".wmls", "text/vnd.wap.wmlscript" },
{ ".wmlsc", "application/vnd.wap.wmlscriptc" },
{ ".word", "application/msword" },
{ ".wp", "application/wordperfect" },
{ ".wp5", "application/wordperfect" },
{ ".wp6", "application/wordperfect" },
{ ".wpd", "application/wordperfect" },
{ ".wq1", "application/x-lotus" },
{ ".wri", "application/mswrite" },
{ ".wrl", "model/vrml" },
{ ".wrz", "model/vrml" },
{ ".wsc", "text/scriplet" },
{ ".wsrc", "application/x-wais-source" },
{ ".wtk", "application/x-wintalk" },
{ ".xbm", "image/xbm" },
{ ".xdr", "video/x-amt-demorun" },
{ ".xgz", "xgl/drawing" },
{ ".xif", "image/vnd.xiff" },
{ ".xl", "application/excel" },
{ ".xla", "application/excel" },
{ ".xlb", "application/excel" },
{ ".xlc", "application/excel" },
{ ".xld", "application/excel" },
{ ".xlk", "application/excel" },
{ ".xll", "application/excel" },
{ ".xlm", "application/excel" },
{ ".xls", "application/excel" },
{ ".xlt", "application/excel" },
{ ".xlv", "application/excel" },
{ ".xlw", "application/excel" },
{ ".xm", "audio/xm" },
{ ".xml", "application/xml" },
{ ".xmz", "xgl/movie" },
{ ".xpix", "application/x-vnd.ls-xpix" },
{ ".xpm", "image/xpm" },
{ ".x", "image/png" },
{ ".xsr", "video/x-amt-showrun" },
{ ".xwd", "image/x-xwd" },
{ ".xyz", "chemical/x-pdb" },
{ ".z", "application/x-compressed" },
{ ".zip", "application/zip" },
{ ".zoo", "application/octet-stream" },
{ ".zsh", "text/x-script.zsh" },
};
/// <summary>
/// Gets the mime type from a file extension ".ext".
/// </summary>
/// <param name="extension">The extension (starting with a dot).</param>
/// <returns>The mime-type of the given extension.</returns>
public static String FromExtension(String extension)
{
if (Extensions.TryGetValue(extension, out var mime))
{
return mime;
}
return Binary;
}
/// <summary>
/// Gets some extension ".ext" from a MIME type.
/// </summary>
/// <param name="mimeType">The mime-type of the given extension.</param>
/// <returns>An extension (starting with a dot) or an empty string.</returns>
public static String GetExtension(String mimeType) => Extensions.FirstOrDefault(x => x.Value.Isi(mimeType)).Key ?? String.Empty;
#endregion
#region Known Mime Types
/// <summary>
/// Gets the mime-type for HTML text: text/html.
/// </summary>
public static readonly String Html = "text/html";
/// <summary>
/// Gets the mime-type for a PNG image: image/png.
/// </summary>
public static readonly String Png = "image/png";
/// <summary>
/// Gets the mime-type for plain text: text/plain.
/// </summary>
public static readonly String Plain = "text/plain";
/// <summary>
/// Gets the mime-type for XML text: text/xml.
/// </summary>
public static readonly String Xml = "text/xml";
/// <summary>
/// Gets the mime-type for SVG text: image/svg+xml.
/// </summary>
public static readonly String Svg = "image/svg+xml";
/// <summary>
/// Gets the mime-type for a cascading style sheet: text/css.
/// </summary>
public static readonly String Css = "text/css";
/// <summary>
/// Gets the default mime-type for JavaScript scripts: text/javascript.
/// </summary>
public static readonly String DefaultJavaScript = "text/javascript";
/// <summary>
/// Gets the mime-type for JSON text: application/json.
/// </summary>
public static readonly String ApplicationJson = "application/json";
/// <summary>
/// Gets the mime-type for XML applications: application/xml.
/// </summary>
public static readonly String ApplicationXml = "application/xml";
/// <summary>
/// Gets the mime-type for XHTML / XML text: application/xhtml+xml.
/// </summary>
public static readonly String ApplicationXHtml = "application/xhtml+xml";
/// <summary>
/// Gets the mime-type for raw binary data: application/octet-stream.
/// </summary>
public static readonly String Binary = "application/octet-stream";
/// <summary>
/// Gets the mime-type for a form: application/x-www-form-urlencoded.
/// </summary>
public static readonly String UrlencodedForm = "application/x-www-form-urlencoded";
/// <summary>
/// Gets the mime-type for multipart form data: multipart/form-data.
/// </summary>
public static readonly String MultipartForm = "multipart/form-data";
/// <summary>
/// Checks if the given mime-type is one of the JavaScript variants.
/// </summary>
/// <param name="type">The type to check for.</param>
/// <returns>
/// True if it is a legal JavaScript mime-type, otherwise false.
/// </returns>
public static Boolean IsJavaScript(String type)
{
foreach (var commonJsType in CommonJsTypes)
{
if (type.Isi(commonJsType))
{
return true;
}
}
return false;
}
/// <summary>
/// Checks if the given mime-type is equivalent to the provided string
/// representation.
/// </summary>
/// <param name="type">The type to check for.</param>
/// <param name="content">THe string representation.</param>
/// <returns>
/// True if both (type and representation) are equivalent, else false.
/// </returns>
public static Boolean Represents(this MimeType type, String content)
{
var other = new MimeType(content);
return type.Equals(other);
}
#endregion
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
namespace DotSpatial.Data
{
/// <summary>
/// The attribute cache caches the attributes from the dbf file.
/// </summary>
public class AttributeCache : IEnumerable<Dictionary<string, object>>
{
private static int rowsPerPage;
private readonly IAttributeSource _dataSupply;
private int _editRowIndex;
/// <summary>
/// Initializes a new instance of the <see cref="AttributeCache"/> class that can create data tables by using a DataPageRetriever.
/// </summary>
/// <param name="dataSupplier">Any structure that implements IDataPageRetriever.</param>
/// <param name="rowsPerPage">The rows per page.</param>
public AttributeCache(IAttributeSource dataSupplier, int rowsPerPage)
{
_dataSupply = dataSupplier;
AttributeCache.rowsPerPage = rowsPerPage;
_editRowIndex = -1;
LoadFirstTwoPages();
}
#region Properties
/// <summary>
/// Gets or sets the row being edited.
/// </summary>
public Dictionary<string, object> EditRow { get; set; }
/// <summary>
/// Gets or sets the integer index of the row being edited.
/// </summary>
public int EditRowIndex
{
get
{
return _editRowIndex;
}
set
{
if (value < 0 || value >= _dataSupply.NumRows())
{
EditRow = null;
return;
}
EditRow = RetrieveElement(value);
_editRowIndex = value;
}
}
/// <summary>
/// Gets the number of rows in the data supply.
/// </summary>
public int NumRows => _dataSupply.NumRows();
/// <summary>
/// Gets or sets the pages currently stored in the cache.
/// </summary>
public DataPage[] Pages { get; set; }
#endregion
/// <inheritdoc />
public IEnumerator<Dictionary<string, object>> GetEnumerator()
{
return new AttributeCacheEnumerator(this);
}
#region Methods
/// <summary>
/// Obtains the element at the specified index.
/// </summary>
/// <param name="rowIndex">Index of the row that should be retrieved.</param>
/// <returns>The retrieved row.</returns>
public Dictionary<string, object> RetrieveElement(int rowIndex)
{
if (EditRowIndex == rowIndex)
{
return EditRow;
}
Dictionary<string, object> element = new Dictionary<string, object>();
if (IfPageCachedThenSetElement(rowIndex, ref element))
{
return element;
}
return RetrieveDataCacheItThenReturnElement(rowIndex);
}
/// <summary>
/// Obtains the element at the specified index.
/// </summary>
/// <param name="rowIndex">Index of the row that contains the element.</param>
/// <param name="columnIndex">Index of the column that contains the element.</param>
/// <returns>Element found at the specified index.</returns>
public object RetrieveElement(int rowIndex, int columnIndex)
{
DataColumn[] columns = _dataSupply.GetColumns();
if (rowIndex == _editRowIndex && EditRow != null)
{
return EditRow[columns[columnIndex].ColumnName];
}
object element;
if (IfPageCachedThenSetElement(rowIndex, columnIndex, out element))
{
return element;
}
return RetrieveDataCacheItThenReturnElement(rowIndex, columnIndex);
}
/// <summary>
/// Saves the changes in the edit row to the tabular cache as well as the underlying database.
/// </summary>
public void SaveChanges()
{
_dataSupply.Edit(EditRowIndex, EditRow);
DataRow dr = null;
if (IsRowCachedInPage(0, _editRowIndex))
{
dr = Pages[0].Table.Rows[_editRowIndex];
}
if (IsRowCachedInPage(1, _editRowIndex))
{
dr = Pages[1].Table.Rows[_editRowIndex];
}
if (dr == null) return;
foreach (KeyValuePair<string, object> pair in EditRow)
{
dr[pair.Key] = pair.Value;
}
}
/// <summary>
/// Gets an enumperator that enumerates the dictionaries that represent the row content stored by field name.
/// </summary>
/// <returns>An enumperator that enumerates the dictionaries that represent the row content stored by field name.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return new AttributeCacheEnumerator(this);
}
/// <summary>
/// Returns the index of the cached page most distant from the given index and therefore least likely to be reused.
/// </summary>
/// <param name="rowIndex">Row index that is used to find the most distant page.</param>
/// <returns>The index of the cached page most distant from the given index and therefore least likely to be reused.</returns>
private int GetIndexToUnusedPage(int rowIndex)
{
if (rowIndex > Pages[0].HighestIndex && rowIndex > Pages[1].HighestIndex)
{
int offsetFromPage0 = rowIndex - Pages[0].HighestIndex;
int offsetFromPage1 = rowIndex - Pages[1].HighestIndex;
return offsetFromPage0 < offsetFromPage1 ? 1 : 0;
}
else
{
int offsetFromPage0 = Pages[0].LowestIndex - rowIndex;
int offsetFromPage1 = Pages[1].LowestIndex - rowIndex;
return offsetFromPage0 < offsetFromPage1 ? 1 : 0;
}
}
/// <summary>
/// Sets the value of the element parameter if the value is in the cache.
/// </summary>
/// <param name="rowIndex">Index of the row that contains the data that gets assigned to element.</param>
/// <param name="columnIndex">Index of the column that contains the data that gets assigned to element.</param>
/// <param name="element">Element whose data gets set.</param>
/// <returns>True, if the element was set or the index was bigger than the number of rows in the page.</returns>
private bool IfPageCachedThenSetElement(int rowIndex, int columnIndex, out object element)
{
element = string.Empty;
int index = rowIndex % rowsPerPage;
// jany_: why check only the first 2 pages if Pages could have more than 2?
for (int i = 0; i <= 1; i++)
{
if (IsRowCachedInPage(i, rowIndex))
{
if (Pages[i].Table.Rows.Count <= index) return true;
element = Pages[i].Table.Rows[index][columnIndex];
return true;
}
}
return false;
}
/// <summary>
/// Sets the value of the element parameter if the value is in the cache.
/// </summary>
/// <param name="rowIndex">Index of the row that contains the data that gets assigned to element.</param>
/// <param name="element">Element whose data gets set.</param>
/// <returns>True, if the data was set.</returns>
private bool IfPageCachedThenSetElement(int rowIndex, ref Dictionary<string, object> element)
{
// jany_: why check only the first 2 pages if Pages could have more than 2?
for (int i = 0; i <= 1; i++)
{
if (IsRowCachedInPage(i, rowIndex))
{
DataRow dr = Pages[i].Table.Rows[rowIndex % rowsPerPage];
foreach (DataColumn column in Pages[0].Table.Columns)
{
string name = column.ColumnName;
element.Add(name, dr[name]);
}
return true;
}
}
return false;
}
/// <summary>
/// Returns a value indicating whether the given row index is contained in the DataPage with the given pageNumber.
/// </summary>
/// <param name="pageNumber">Number of the page, that should contain the index.</param>
/// <param name="rowIndex">Row index that should be contained by the page.</param>
/// <returns>True, if the row index was found in the page with the given number.</returns>
private bool IsRowCachedInPage(int pageNumber, int rowIndex)
{
return rowIndex <= Pages[pageNumber].HighestIndex && rowIndex >= Pages[pageNumber].LowestIndex;
}
/// <summary>
/// Loads the first to Pages.
/// </summary>
private void LoadFirstTwoPages()
{
DataPage p1 = new DataPage(_dataSupply.GetAttributes(DataPage.MapToLowerBoundary(0), rowsPerPage), 0);
DataPage p2 = new DataPage(_dataSupply.GetAttributes(DataPage.MapToLowerBoundary(rowsPerPage), rowsPerPage), rowsPerPage);
Pages = new[] { p1, p2 };
}
private object RetrieveDataCacheItThenReturnElement(int rowIndex, int columnIndex)
{
// Retrieve a page worth of data containing the requested value.
DataTable table = _dataSupply.GetAttributes(DataPage.MapToLowerBoundary(rowIndex), rowsPerPage);
// Replace the cached page furthest from the requested cell
// with a new page containing the newly retrieved data.
Pages[GetIndexToUnusedPage(rowIndex)] = new DataPage(table, rowIndex);
return RetrieveElement(rowIndex, columnIndex);
}
private Dictionary<string, object> RetrieveDataCacheItThenReturnElement(int rowIndex)
{
// Retrieve a page worth of data containing the requested value.
DataTable table = _dataSupply.GetAttributes(DataPage.MapToLowerBoundary(rowIndex), rowsPerPage);
// Replace the cached page furthest from the requested cell
// with a new page containing the newly retrieved data.
Pages[GetIndexToUnusedPage(rowIndex)] = new DataPage(table, rowIndex);
return RetrieveElement(rowIndex);
}
#endregion
#region Classes
/// <summary>
/// Represents one page of data.
/// </summary>
public struct DataPage
{
/// <summary>
/// The data Table.
/// </summary>
public readonly DataTable Table;
/// <summary>
/// Initializes a new instance of the <see cref="DataPage"/> struct representing one page of data-row values.
/// </summary>
/// <param name="table">The DataTable that controls the content.</param>
/// <param name="rowIndex">The integer row index.</param>
public DataPage(DataTable table, int rowIndex)
{
Table = table;
LowestIndex = MapToLowerBoundary(rowIndex);
HighestIndex = MapToUpperBoundary(rowIndex);
Debug.Assert(LowestIndex >= 0, "LowestIndex must >= 0");
Debug.Assert(HighestIndex >= 0, "HighestIndex must >= 0");
}
/// <summary>
/// Gets the integer lowest index of the page.
/// </summary>
public int LowestIndex { get; }
/// <summary>
/// Gets the integer highest index of the page.
/// </summary>
public int HighestIndex { get; }
/// <summary>
/// Given an arbitrary row index, this calculates what the lower boundary would be for the page containing the index.
/// </summary>
/// <param name="rowIndex">Row index used for calculation.</param>
/// <returns>The lowest index of the page containing the given index.</returns>
public static int MapToLowerBoundary(int rowIndex)
{
// Return the lowest index of a page containing the given index.
return (rowIndex / rowsPerPage) * rowsPerPage;
}
/// <summary>
/// Tests to see if the specified index is in this page.
/// </summary>
/// <param name="index">Index that should be checked.</param>
/// <returns>True, if the page contains the index.</returns>
public bool Contains(int index)
{
return index > LowestIndex && index < HighestIndex;
}
/// <summary>
/// Given an arbitrary row index, this calculates the upper boundary for the page containing the index.
/// </summary>
/// <param name="rowIndex">Row index used for calculation.</param>
/// <returns>The highest index of the page containing the given index.</returns>
private static int MapToUpperBoundary(int rowIndex)
{
// Return the highest index of a page containing the given index.
return MapToLowerBoundary(rowIndex) + rowsPerPage - 1;
}
}
/// <summary>
/// Enumerates the dictionaries that represent row content stored by field name.
/// </summary>
private class AttributeCacheEnumerator : IEnumerator<Dictionary<string, object>>
{
private readonly AttributeCache _cache;
private int _row;
/// <summary>
/// Initializes a new instance of the <see cref="AttributeCacheEnumerator"/> class.
/// </summary>
/// <param name="cache">Cache that contains the data.</param>
public AttributeCacheEnumerator(AttributeCache cache)
{
_cache = cache;
}
/// <inheritdoc />
public Dictionary<string, object> Current { get; private set; }
/// <inheritdoc />
object IEnumerator.Current => Current;
/// <inheritdoc />
public void Dispose()
{
}
/// <inheritdoc />
public bool MoveNext()
{
_row += 1;
if (_row >= _cache._dataSupply.NumRows()) return false;
Current = _cache.RetrieveElement(_row);
return true;
}
/// <inheritdoc />
public void Reset()
{
_row = -1;
}
}
#endregion
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.txt file at the root of this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants;
namespace Microsoft.VisualStudio.Project
{
[CLSCompliant(false), ComVisible(true)]
public class NestedProjectNode : HierarchyNode, IPropertyNotifySink
{
#region fields
private IVsHierarchy nestedHierarchy;
Guid projectInstanceGuid = Guid.Empty;
private string projectName = String.Empty;
private string projectPath = String.Empty;
private ImageHandler imageHandler;
/// <summary>
/// Defines an object that will be a mutex for this object for synchronizing thread calls.
/// </summary>
private static volatile object Mutex = new object();
/// <summary>
/// Sets the dispose flag on the object.
/// </summary>
private bool isDisposed;
// A cooike retrieved when advising on property chnanged events.
private uint projectPropertyNotifySinkCookie;
#endregion
#region properties
internal IVsHierarchy NestedHierarchy
{
get
{
return this.nestedHierarchy;
}
}
#endregion
#region virtual properties
/// <summary>
/// Returns the __VSADDVPFLAGS that will be passed in when calling AddVirtualProjectEx
/// </summary>
protected virtual uint VirtualProjectFlags
{
get { return 0; }
}
#endregion
#region overridden properties
/// <summary>
/// The path of the nested project.
/// </summary>
public override string Url
{
get
{
return this.projectPath;
}
}
/// <summary>
/// The Caption of the nested project.
/// </summary>
public override string Caption
{
get
{
return Path.GetFileNameWithoutExtension(this.projectName);
}
}
public override Guid ItemTypeGuid
{
get
{
return VSConstants.GUID_ItemType_SubProject;
}
}
/// <summary>
/// Defines whether a node can execute a command if in selection.
/// We do this in order to let the nested project to handle the execution of its own commands.
/// </summary>
public override bool CanExecuteCommand
{
get
{
return false;
}
}
public override int SortPriority
{
get { return DefaultSortOrderNode.NestedProjectNode; }
}
protected bool IsDisposed
{
get { return this.isDisposed; }
set { this.isDisposed = value; }
}
#endregion
#region ctor
protected NestedProjectNode()
{
}
public NestedProjectNode(ProjectNode root, ProjectElement element)
: base(root, element)
{
this.IsExpanded = true;
}
#endregion
#region IPropertyNotifySink Members
/// <summary>
/// Notifies a sink that the [bindable] property specified by dispID has changed.
/// If dispID is DISPID_UNKNOWN, then multiple properties have changed together.
/// The client (owner of the sink) should then retrieve the current value of each property of interest from the object that generated the notification.
/// In our case we will care about the VSLangProj80.VsProjPropId.VBPROJPROPID_FileName and update the changes in the parent project file.
/// </summary>
/// <param name="dispid">Dispatch identifier of the property that is about to change or DISPID_UNKNOWN if multiple properties are about to change.</param>
public virtual void OnChanged(int dispid)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (dispid == (int)VSLangProj80.VsProjPropId.VBPROJPROPID_FileName)
{
// Get the filename of the nested project. Inetead of asking the label on the nested we ask the filename, since the label might not yet been set.
IVsProject3 nestedProject = this.nestedHierarchy as IVsProject3;
if (nestedProject != null)
{
string document;
nestedProject.GetMkDocument(VSConstants.VSITEMID_ROOT, out document);
this.RenameNestedProjectInParentProject(Path.GetFileNameWithoutExtension(document));
// We need to redraw the caption since for some reason, by intervining to the OnChanged event the Caption is not updated.
this.ReDraw(UIHierarchyElement.Caption);
}
}
}
/// <summary>
/// Notifies a sink that a [requestedit] property is about to change and that the object is asking the sink how to proceed.
/// </summary>
/// <param name="dispid">Dispatch identifier of the property that is about to change or DISPID_UNKNOWN if multiple properties are about to change.</param>
public virtual void OnRequestEdit(int dispid)
{
}
#endregion
#region public methods
#endregion
#region overridden methods
/// <summary>
/// Get the automation object for the NestedProjectNode
/// </summary>
/// <returns>An instance of the Automation.OANestedProjectItem type if succeded</returns>
public override object GetAutomationObject()
{
//Validate that we are not disposed or the project is closing
if (this.isDisposed || this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return null;
}
return new Automation.OANestedProjectItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
/// <summary>
/// Gets properties of a given node or of the hierarchy.
/// </summary>
/// <param name="propId">Identifier of the hierarchy property</param>
/// <returns>It return an object which type is dependent on the propid.</returns>
public override object GetProperty(int propId)
{
ThreadHelper.ThrowIfNotOnUIThread();
__VSHPROPID vshPropId = (__VSHPROPID)propId;
switch (vshPropId)
{
default:
return base.GetProperty(propId);
case __VSHPROPID.VSHPROPID_Expandable:
return true;
case __VSHPROPID.VSHPROPID_BrowseObject:
case __VSHPROPID.VSHPROPID_HandlesOwnReload:
return this.DelegateGetPropertyToNested(propId);
}
}
/// <summary>
/// Gets properties whose values are GUIDs.
/// </summary>
/// <param name="propid">Identifier of the hierarchy property</param>
/// <param name="guid"> Pointer to a GUID property specified in propid</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int GetGuidProperty(int propid, out Guid guid)
{
guid = Guid.Empty;
switch ((__VSHPROPID)propid)
{
case __VSHPROPID.VSHPROPID_ProjectIDGuid:
guid = this.projectInstanceGuid;
break;
default:
return base.GetGuidProperty(propid, out guid);
}
CCITracing.TraceCall(String.Format(CultureInfo.CurrentCulture, "Guid for {0} property", propid));
if (guid.CompareTo(Guid.Empty) == 0)
{
return VSConstants.DISP_E_MEMBERNOTFOUND;
}
return VSConstants.S_OK;
}
/// <summary>
/// Determines whether the hierarchy item changed.
/// </summary>
/// <param name="itemId">Item identifier of the hierarchy item contained in VSITEMID</param>
/// <param name="punkDocData">Pointer to the IUnknown interface of the hierarchy item. </param>
/// <param name="pfDirty">TRUE if the hierarchy item changed.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int IsItemDirty(uint itemId, IntPtr punkDocData, out int pfDirty)
{
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
Debug.Assert(punkDocData != IntPtr.Zero, "docData intptr was zero");
ThreadHelper.ThrowIfNotOnUIThread();
// Get an IPersistFileFormat object from docData object
IPersistFileFormat persistFileFormat = Marshal.GetTypedObjectForIUnknown(punkDocData, typeof(IPersistFileFormat)) as IPersistFileFormat;
Debug.Assert(persistFileFormat != null, "The docData object does not implement the IPersistFileFormat interface");
// Call IsDirty on the IPersistFileFormat interface
ErrorHandler.ThrowOnFailure(persistFileFormat.IsDirty(out pfDirty));
return VSConstants.S_OK;
}
/// <summary>
/// Saves the hierarchy item to disk.
/// </summary>
/// <param name="dwSave">Flags whose values are taken from the VSSAVEFLAGS enumeration.</param>
/// <param name="silentSaveAsName">File name to be applied when dwSave is set to VSSAVE_SilentSave. </param>
/// <param name="itemid">Item identifier of the hierarchy item saved from VSITEMID. </param>
/// <param name="punkDocData">Pointer to the IUnknown interface of the hierarchy item saved.</param>
/// <param name="pfCancelled">TRUE if the save action was canceled. </param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public override int SaveItem(VSSAVEFLAGS dwSave, string silentSaveAsName, uint itemid, IntPtr punkDocData, out int pfCancelled)
{
ThreadHelper.ThrowIfNotOnUIThread();
// Don't ignore/unignore file changes
// Use Advise/Unadvise to work around rename situations
try
{
this.StopObservingNestedProjectFile();
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
Debug.Assert(punkDocData != IntPtr.Zero, "docData intptr was zero");
// Get an IPersistFileFormat object from docData object (we don't call release on punkDocData since did not increment its ref count)
IPersistFileFormat persistFileFormat = Marshal.GetTypedObjectForIUnknown(punkDocData, typeof(IPersistFileFormat)) as IPersistFileFormat;
Debug.Assert(persistFileFormat != null, "The docData object does not implement the IPersistFileFormat interface");
IVsUIShell uiShell = this.GetService(typeof(SVsUIShell)) as IVsUIShell;
string newName;
uiShell.SaveDocDataToFile(dwSave, persistFileFormat, silentSaveAsName, out newName, out pfCancelled);
// When supported do a rename of the nested project here
}
finally
{
// Succeeded or not we must hook to the file change events
// Don't ignore/unignore file changes
// Use Advise/Unadvise to work around rename situations
this.ObserveNestedProjectFile();
}
return VSConstants.S_OK;
}
/// <summary>
/// Gets the icon handle. It tries first the nested to get the icon handle. If that is not supported it will get it from
/// the image list of the nested if that is supported. If neither of these is supported a default image will be shown.
/// </summary>
/// <returns>An object representing the icon.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.VisualStudio.Shell.Interop.IVsHierarchy.GetProperty(System.UInt32,System.Int32,System.Object@)")]
public override object GetIconHandle(bool open)
{
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
ThreadHelper.ThrowIfNotOnUIThread();
object iconHandle = null;
this.nestedHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_IconHandle, out iconHandle);
if (iconHandle == null)
{
if (null == imageHandler)
{
InitImageHandler();
}
// Try to get an icon from the nested hierrachy image list.
if (imageHandler.ImageList != null)
{
object imageIndexAsObject = null;
if (this.nestedHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_IconIndex, out imageIndexAsObject) == VSConstants.S_OK &&
imageIndexAsObject != null)
{
int imageIndex = (int)imageIndexAsObject;
if (imageIndex < imageHandler.ImageList.Images.Count)
{
iconHandle = imageHandler.GetIconHandle(imageIndex);
}
}
}
if (null == iconHandle)
{
iconHandle = this.ProjectMgr.ImageHandler.GetIconHandle((int)ProjectNode.ImageName.Application);
}
}
return iconHandle;
}
/// <summary>
/// Return S_OK. Implementation of Closing a nested project is done in CloseNestedProject which is called by CloseChildren.
/// </summary>
/// <returns>S_OK</returns>
public override int Close()
{
return VSConstants.S_OK;
}
/// <summary>
/// Returns the moniker of the nested project.
/// </summary>
/// <returns></returns>
public override string GetMkDocument()
{
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
if (this.isDisposed || this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return String.Empty;
}
return this.projectPath;
}
/// <summary>
/// Called by the shell when a node has been renamed from the GUI
/// </summary>
/// <param name="label">The name of the new label.</param>
/// <returns>A success or failure value.</returns>
public override int SetEditLabel(string label)
{
int result = this.DelegateSetPropertyToNested((int)__VSHPROPID.VSHPROPID_EditLabel, label);
ThreadHelper.ThrowIfNotOnUIThread();
if (ErrorHandler.Succeeded(result))
{
this.RenameNestedProjectInParentProject(label);
}
return result;
}
/// <summary>
/// Called by the shell to get the node caption when the user tries to rename from the GUI
/// </summary>
/// <returns>the node cation</returns>
public override string GetEditLabel()
{
ThreadHelper.ThrowIfNotOnUIThread();
return (string)this.DelegateGetPropertyToNested((int)__VSHPROPID.VSHPROPID_EditLabel);
}
/// <summary>
/// This is temporary until we have support for re-adding a nested item
/// </summary>
protected override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation)
{
return false;
}
/// <summary>
/// Delegates the call to the inner hierarchy.
/// </summary>
/// <param name="reserved">Reserved parameter defined at the IVsPersistHierarchyItem2::ReloadItem parameter.</param>
protected internal override void ReloadItem(uint reserved)
{
#region precondition
if (this.isDisposed || this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
throw new InvalidOperationException();
}
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
#endregion
ThreadHelper.ThrowIfNotOnUIThread();
IVsPersistHierarchyItem2 persistHierachyItem = this.nestedHierarchy as IVsPersistHierarchyItem2;
// We are expecting that if we get called then the nestedhierarchy supports IVsPersistHierarchyItem2, since then hierrachy should support handling its own reload.
// There should be no errormessage to the user since this is an internal error, that it cannot be fixed at user level.
if (persistHierachyItem == null)
{
throw new InvalidOperationException();
}
ErrorHandler.ThrowOnFailure(persistHierachyItem.ReloadItem(VSConstants.VSITEMID_ROOT, reserved));
}
/// <summary>
/// Flag indicating that changes to a file can be ignored when item is saved or reloaded.
/// </summary>
/// <param name="ignoreFlag">Flag indicating whether or not to ignore changes (1 to ignore, 0 to stop ignoring).</param>
protected internal override void IgnoreItemFileChanges(bool ignoreFlag)
{
#region precondition
if (this.isDisposed || this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
throw new InvalidOperationException();
}
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
#endregion
this.IgnoreNestedProjectFile(ignoreFlag);
ThreadHelper.ThrowIfNotOnUIThread();
IVsPersistHierarchyItem2 persistHierachyItem = this.nestedHierarchy as IVsPersistHierarchyItem2;
// If the IVsPersistHierarchyItem2 is not implemented by the nested just return
if (persistHierachyItem == null)
{
return;
}
ErrorHandler.ThrowOnFailure(persistHierachyItem.IgnoreItemFileChanges(VSConstants.VSITEMID_ROOT, ignoreFlag ? 1 : 0));
}
/// <summary>
/// Sets the VSADDFILEFLAGS that will be used to call the IVsTrackProjectDocumentsEvents2 OnAddFiles
/// </summary>
/// <param name="files">The files to which an array of VSADDFILEFLAGS has to be specified.</param>
/// <returns></returns>
protected internal override VSADDFILEFLAGS[] GetAddFileFlags(string[] files)
{
if (files == null || files.Length == 0)
{
return new VSADDFILEFLAGS[1] { VSADDFILEFLAGS.VSADDFILEFLAGS_NoFlags };
}
VSADDFILEFLAGS[] addFileFlags = new VSADDFILEFLAGS[files.Length];
for (int i = 0; i < files.Length; i++)
{
addFileFlags[i] = VSADDFILEFLAGS.VSADDFILEFLAGS_IsNestedProjectFile;
}
return addFileFlags;
}
/// <summary>
/// Sets the VSQUERYADDFILEFLAGS that will be used to call the IVsTrackProjectDocumentsEvents2 OnQueryAddFiles
/// </summary>
/// <param name="files">The files to which an array of VSADDFILEFLAGS has to be specified.</param>
/// <returns></returns>
protected internal override VSQUERYADDFILEFLAGS[] GetQueryAddFileFlags(string[] files)
{
if (files == null || files.Length == 0)
{
return new VSQUERYADDFILEFLAGS[1] { VSQUERYADDFILEFLAGS.VSQUERYADDFILEFLAGS_NoFlags };
}
VSQUERYADDFILEFLAGS[] queryAddFileFlags = new VSQUERYADDFILEFLAGS[files.Length];
for (int i = 0; i < files.Length; i++)
{
queryAddFileFlags[i] = VSQUERYADDFILEFLAGS.VSQUERYADDFILEFLAGS_IsNestedProjectFile;
}
return queryAddFileFlags;
}
/// <summary>
/// Sets the VSREMOVEFILEFLAGS that will be used to call the IVsTrackProjectDocumentsEvents2 OnRemoveFiles
/// </summary>
/// <param name="files">The files to which an array of VSREMOVEFILEFLAGS has to be specified.</param>
/// <returns></returns>
protected internal override VSREMOVEFILEFLAGS[] GetRemoveFileFlags(string[] files)
{
if (files == null || files.Length == 0)
{
return new VSREMOVEFILEFLAGS[1] { VSREMOVEFILEFLAGS.VSREMOVEFILEFLAGS_NoFlags };
}
VSREMOVEFILEFLAGS[] removeFileFlags = new VSREMOVEFILEFLAGS[files.Length];
for (int i = 0; i < files.Length; i++)
{
removeFileFlags[i] = VSREMOVEFILEFLAGS.VSREMOVEFILEFLAGS_IsNestedProjectFile;
}
return removeFileFlags;
}
/// <summary>
/// Sets the VSQUERYREMOVEFILEFLAGS that will be used to call the IVsTrackProjectDocumentsEvents2 OnQueryRemoveFiles
/// </summary>
/// <param name="files">The files to which an array of VSQUERYREMOVEFILEFLAGS has to be specified.</param>
/// <returns></returns>
protected internal override VSQUERYREMOVEFILEFLAGS[] GetQueryRemoveFileFlags(string[] files)
{
if (files == null || files.Length == 0)
{
return new VSQUERYREMOVEFILEFLAGS[1] { VSQUERYREMOVEFILEFLAGS.VSQUERYREMOVEFILEFLAGS_NoFlags };
}
VSQUERYREMOVEFILEFLAGS[] queryRemoveFileFlags = new VSQUERYREMOVEFILEFLAGS[files.Length];
for (int i = 0; i < files.Length; i++)
{
queryRemoveFileFlags[i] = VSQUERYREMOVEFILEFLAGS.VSQUERYREMOVEFILEFLAGS_IsNestedProjectFile;
}
return queryRemoveFileFlags;
}
#endregion
#region virtual methods
/// <summary>
/// Initialize the nested hierarhy node.
/// </summary>
/// <param name="fileName">The file name of the nested project.</param>
/// <param name="destination">The location of the nested project.</param>
/// <param name="projectName">The name of the project.</param>
/// <param name="createFlags">The nested project creation flags </param>
/// <remarks>This methos should be called just after a NestedProjectNode object is created.</remarks>
public virtual void Init(string fileNameParam, string destinationParam, string projectNameParam, __VSCREATEPROJFLAGS createFlags)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (String.IsNullOrEmpty(fileNameParam))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "fileNameParam");
}
if (String.IsNullOrEmpty(destinationParam))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "destinationParam");
}
this.projectName = Path.GetFileName(fileNameParam);
this.projectPath = Path.Combine(destinationParam, this.projectName);
// get the IVsSolution interface from the global service provider
IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;
Debug.Assert(solution != null, "Could not get the IVsSolution object from the services exposed by this project");
if (solution == null)
{
throw new InvalidOperationException();
}
// Get the project type guid from project element
string typeGuidString = this.ItemNode.GetMetadataAndThrow(ProjectFileConstants.TypeGuid, new InvalidOperationException());
Guid projectFactoryGuid = Guid.Empty;
if (!String.IsNullOrEmpty(typeGuidString))
{
projectFactoryGuid = new Guid(typeGuidString);
}
// Get the project factory.
IVsProjectFactory projectFactory;
ErrorHandler.ThrowOnFailure(solution.GetProjectFactory((uint)0, new Guid[] { projectFactoryGuid }, fileNameParam, out projectFactory));
this.CreateProjectDirectory();
//Create new project using factory
int cancelled;
Guid refiid = NativeMethods.IID_IUnknown;
IntPtr projectPtr = IntPtr.Zero;
try
{
ErrorHandler.ThrowOnFailure(projectFactory.CreateProject(fileNameParam, destinationParam, projectNameParam, (uint)createFlags, ref refiid, out projectPtr, out cancelled));
if (projectPtr != IntPtr.Zero)
{
this.nestedHierarchy = Marshal.GetTypedObjectForIUnknown(projectPtr, typeof(IVsHierarchy)) as IVsHierarchy;
Debug.Assert(this.nestedHierarchy != null, "Nested hierarchy could not be created");
Debug.Assert(cancelled == 0);
}
}
finally
{
if (projectPtr != IntPtr.Zero)
{
// We created a new instance of the project, we need to call release to decrement the ref count
// the RCW (this.nestedHierarchy) still has a reference to it which will keep it alive
Marshal.Release(projectPtr);
}
}
if (cancelled != 0 && this.nestedHierarchy == null)
{
ErrorHandler.ThrowOnFailure(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
// Link into the nested VS hierarchy.
ErrorHandler.ThrowOnFailure(this.nestedHierarchy.SetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ParentHierarchy, this.ProjectMgr));
ErrorHandler.ThrowOnFailure(this.nestedHierarchy.SetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ParentHierarchyItemid, (object)(int)this.ID));
this.LockRDTEntry();
this.ConnectPropertyNotifySink();
}
/// <summary>
/// Links a nested project as a virtual project to the solution.
/// </summary>
protected internal virtual void AddVirtualProject()
{
// This is the second step in creating and adding a nested project. The inner hierarchy must have been
// already initialized at this point.
#region precondition
if (this.nestedHierarchy == null)
{
throw new InvalidOperationException();
}
#endregion
// get the IVsSolution interface from the global service provider
ThreadHelper.ThrowIfNotOnUIThread();
IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;
Debug.Assert(solution != null, "Could not get the IVsSolution object from the services exposed by this project");
if (solution == null)
{
throw new InvalidOperationException();
}
this.InitializeInstanceGuid();
// Add virtual project to solution.
ErrorHandler.ThrowOnFailure(solution.AddVirtualProjectEx(this.nestedHierarchy, this.VirtualProjectFlags, ref this.projectInstanceGuid));
// Now set up to listen on file changes on the nested project node.
this.ObserveNestedProjectFile();
}
/// <summary>
/// The method that does the cleanup.
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
// Everybody can go here.
ThreadHelper.ThrowIfNotOnUIThread();
if (!this.isDisposed)
{
try
{
// Synchronize calls to the Dispose simulteniously.
lock (Mutex)
{
if (disposing)
{
this.DisconnectPropertyNotifySink();
this.StopObservingNestedProjectFile();
// If a project cannot load it may happen that the imagehandler is not instantiated.
if (this.imageHandler != null)
{
this.imageHandler.Close();
}
}
}
}
finally
{
base.Dispose(disposing);
this.isDisposed = true;
}
}
}
/// <summary>
/// Creates the project directory if it does not exist.
/// </summary>
/// <returns></returns>
protected virtual void CreateProjectDirectory()
{
string directoryName = Path.GetDirectoryName(this.projectPath);
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
}
/// <summary>
/// Lock the RDT Entry for the nested project.
/// By default this document is marked as "Dont Save as". That means the menu File->SaveAs is disabled for the
/// nested project node.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "RDT")]
protected virtual void LockRDTEntry()
{
// Define flags for the nested project document
_VSRDTFLAGS flags = _VSRDTFLAGS.RDT_VirtualDocument | _VSRDTFLAGS.RDT_ProjSlnDocument;
// Request the RDT service
ThreadHelper.ThrowIfNotOnUIThread();
IVsRunningDocumentTable rdt = this.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
Debug.Assert(rdt != null, " Could not get running document table from the services exposed by this project");
if (rdt == null)
{
throw new InvalidOperationException();
}
// First we see if someone else has opened the requested view of the file.
uint itemid;
IntPtr docData = IntPtr.Zero;
IVsHierarchy ivsHierarchy;
uint docCookie;
IntPtr projectPtr = IntPtr.Zero;
try
{
ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)flags, this.projectPath, out ivsHierarchy, out itemid, out docData, out docCookie));
flags |= _VSRDTFLAGS.RDT_EditLock;
if (ivsHierarchy != null && docCookie != (uint)ShellConstants.VSDOCCOOKIE_NIL)
{
if (docCookie != this.DocCookie)
{
this.DocCookie = docCookie;
}
}
else
{
// get inptr for hierarchy
projectPtr = Marshal.GetIUnknownForObject(this.nestedHierarchy);
Debug.Assert(projectPtr != IntPtr.Zero, " Project pointer for the nested hierarchy has not been initialized");
ErrorHandler.ThrowOnFailure(rdt.RegisterAndLockDocument((uint)flags, this.projectPath, this.ProjectMgr, this.ID, projectPtr, out docCookie));
this.DocCookie = docCookie;
Debug.Assert(this.DocCookie != (uint)ShellConstants.VSDOCCOOKIE_NIL, "Invalid cookie when registering document in the running document table.");
//we must also set the doc cookie on the nested hier
this.SetDocCookieOnNestedHier(this.DocCookie);
}
}
finally
{
// Release all Inptr's that that were given as out pointers
if (docData != IntPtr.Zero)
{
Marshal.Release(docData);
}
if (projectPtr != IntPtr.Zero)
{
Marshal.Release(projectPtr);
}
}
}
/// <summary>
/// Unlock the RDT entry for the nested project
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "RDT")]
protected virtual void UnlockRDTEntry()
{
if (this.isDisposed || this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return;
}
// First we see if someone else has opened the requested view of the file.
ThreadHelper.ThrowIfNotOnUIThread();
IVsRunningDocumentTable rdt = this.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (rdt != null && this.DocCookie != (int)ShellConstants.VSDOCCOOKIE_NIL)
{
_VSRDTFLAGS flags = _VSRDTFLAGS.RDT_EditLock;
ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)flags, (uint)this.DocCookie));
}
this.DocCookie = (int)ShellConstants.VSDOCCOOKIE_NIL;
}
/// <summary>
/// Renames the project file in the parent project structure.
/// </summary>
/// <param name="label">The new label.</param>
protected virtual void RenameNestedProjectInParentProject(string label)
{
string existingLabel = this.Caption;
ThreadHelper.ThrowIfNotOnUIThread();
if (String.Compare(existingLabel, label, StringComparison.Ordinal) == 0)
{
return;
}
string oldFileName = this.projectPath;
string oldPath = this.Url;
try
{
this.StopObservingNestedProjectFile();
this.ProjectMgr.SuspendMSBuild();
// Check out the project file if necessary.
if (!this.ProjectMgr.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
string newFileName = label + Path.GetExtension(oldFileName);
this.SaveNestedProjectItemInProjectFile(newFileName);
string projectDirectory = Path.GetDirectoryName(oldFileName);
// update state.
this.projectName = newFileName;
this.projectPath = Path.Combine(projectDirectory, this.projectName);
// Unload and lock the RDT entries
this.UnlockRDTEntry();
this.LockRDTEntry();
// Since actually this is a rename in our hierarchy notify the tracker that a rename has happened.
this.ProjectMgr.Tracker.OnItemRenamed(oldPath, this.projectPath, VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_IsNestedProjectFile);
}
finally
{
this.ObserveNestedProjectFile();
this.ProjectMgr.ResumeMSBuild(this.ProjectMgr.ReEvaluateProjectFileTargetName);
}
}
/// <summary>
/// Saves the nested project information in the project file.
/// </summary>
/// <param name="newFileName"></param>
protected virtual void SaveNestedProjectItemInProjectFile(string newFileName)
{
string existingInclude = this.ItemNode.Item.EvaluatedInclude;
string existingRelativePath = Path.GetDirectoryName(existingInclude);
string newRelativePath = Path.Combine(existingRelativePath, newFileName);
this.ItemNode.Rename(newRelativePath);
}
#endregion
#region helper methods
/// <summary>
/// Closes a nested project and releases the nested hierrachy pointer.
/// </summary>
internal void CloseNestedProjectNode()
{
if (this.isDisposed || this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return;
}
uint itemid = VSConstants.VSITEMID_NIL;
ThreadHelper.ThrowIfNotOnUIThread();
try
{
ThreadHelper.ThrowIfNotOnUIThread();
this.DisconnectPropertyNotifySink();
IVsUIHierarchy hier;
IVsWindowFrame windowFrame;
VsShellUtilities.IsDocumentOpen(this.ProjectMgr.Site, this.projectPath, Guid.Empty, out hier, out itemid, out windowFrame);
if (itemid == VSConstants.VSITEMID_NIL)
{
this.UnlockRDTEntry();
}
IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;
if (solution == null)
{
throw new InvalidOperationException();
}
ErrorHandler.ThrowOnFailure(solution.RemoveVirtualProject(this.nestedHierarchy, 0));
}
finally
{
this.StopObservingNestedProjectFile();
// if we haven't already release the RDT cookie, do so now.
if (itemid == VSConstants.VSITEMID_NIL)
{
this.UnlockRDTEntry();
}
this.Dispose(true);
}
}
private void InitializeInstanceGuid()
{
if (this.projectInstanceGuid != Guid.Empty)
{
return;
}
Guid instanceGuid = Guid.Empty;
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
// This method should be called from the open children method, then we can safely use the IsNewProject property
ThreadHelper.ThrowIfNotOnUIThread();
if (this.ProjectMgr.IsNewProject)
{
instanceGuid = Guid.NewGuid();
this.ItemNode.SetMetadata(ProjectFileConstants.InstanceGuid, instanceGuid.ToString("B"));
this.nestedHierarchy.SetGuidProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, ref instanceGuid);
}
else
{
// Get a guid from the nested hiererachy.
Guid nestedHiererachyInstanceGuid;
this.nestedHierarchy.GetGuidProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out nestedHiererachyInstanceGuid);
// Get instance guid from the project file. If it does not exist then we create one.
string instanceGuidAsString = this.ItemNode.GetMetadata(ProjectFileConstants.InstanceGuid);
// 1. nestedHiererachyInstanceGuid is empty and instanceGuidAsString is empty then create a new one.
// 2. nestedHiererachyInstanceGuid is empty and instanceGuidAsString not empty use instanceGuidAsString and update the nested project object by calling SetGuidProperty.
// 3. nestedHiererachyInstanceGuid is not empty instanceGuidAsString is empty then use nestedHiererachyInstanceGuid and update the outer project element.
// 4. nestedHiererachyInstanceGuid is not empty instanceGuidAsString is empty then use nestedHiererachyInstanceGuid and update the outer project element.
if (nestedHiererachyInstanceGuid == Guid.Empty && String.IsNullOrEmpty(instanceGuidAsString))
{
instanceGuid = Guid.NewGuid();
}
else if (nestedHiererachyInstanceGuid == Guid.Empty && !String.IsNullOrEmpty(instanceGuidAsString))
{
instanceGuid = new Guid(instanceGuidAsString);
this.nestedHierarchy.SetGuidProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, ref instanceGuid);
}
else if (nestedHiererachyInstanceGuid != Guid.Empty)
{
instanceGuid = nestedHiererachyInstanceGuid;
// If the instanceGuidAsString is empty then creating a guid out of it would throw an exception.
if (String.IsNullOrEmpty(instanceGuidAsString) || nestedHiererachyInstanceGuid != new Guid(instanceGuidAsString))
{
this.ItemNode.SetMetadata(ProjectFileConstants.InstanceGuid, instanceGuid.ToString("B"));
}
}
}
this.projectInstanceGuid = instanceGuid;
}
private void SetDocCookieOnNestedHier(uint itemDocCookie)
{
object docCookie = (int)itemDocCookie;
ThreadHelper.ThrowIfNotOnUIThread();
try
{
ErrorHandler.ThrowOnFailure(this.nestedHierarchy.SetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ItemDocCookie, docCookie));
}
catch (NotImplementedException)
{
//we swallow this exception on purpose
}
}
private void InitImageHandler()
{
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
ThreadHelper.ThrowIfNotOnUIThread();
if (null == imageHandler)
{
imageHandler = new ImageHandler();
}
object imageListAsPointer = null;
this.nestedHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_IconImgList, out imageListAsPointer);
if (imageListAsPointer != null)
{
this.imageHandler.ImageList = Utilities.GetImageList(imageListAsPointer);
}
}
/// <summary>
/// Delegates Getproperty calls to the inner nested.
/// </summary>
/// <param name="propID">The property to delegate.</param>
/// <returns>The return of the GetProperty from nested.</returns>
private object DelegateGetPropertyToNested(int propID)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (!this.ProjectMgr.IsClosed)
{
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
object returnValue;
// Do not throw since some project types will return E_FAIL if they do not support a property.
int result = this.nestedHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, propID, out returnValue);
if (ErrorHandler.Succeeded(result))
{
return returnValue;
}
}
return null;
}
/// <summary>
/// Delegates Setproperty calls to the inner nested.
/// </summary>
/// <param name="propID">The property to delegate.</param>
/// <param name="value">The property to set.</param>
/// <returns>The return of the SetProperty from nested.</returns>
private int DelegateSetPropertyToNested(int propID, object value)
{
if (this.ProjectMgr.IsClosed)
{
return VSConstants.E_FAIL;
}
Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
ThreadHelper.ThrowIfNotOnUIThread();
// Do not throw since some project types will return E_FAIL if they do not support a property.
return this.nestedHierarchy.SetProperty(VSConstants.VSITEMID_ROOT, propID, value);
}
/// <summary>
/// Starts observing changes on this file.
/// </summary>
private void ObserveNestedProjectFile()
{
ProjectContainerNode parent = this.ProjectMgr as ProjectContainerNode;
ThreadHelper.ThrowIfNotOnUIThread();
Debug.Assert(parent != null, "The parent project for nested projects should be subclassed from ProjectContainerNode");
parent.NestedProjectNodeReloader.ObserveItem(this.GetMkDocument(), this.ID);
}
/// <summary>
/// Stops observing changes on this file.
/// </summary>
private void StopObservingNestedProjectFile()
{
ProjectContainerNode parent = this.ProjectMgr as ProjectContainerNode;
Debug.Assert(parent != null, "The parent project for nested projects should be subclassed from ProjectContainerNode");
ThreadHelper.ThrowIfNotOnUIThread();
parent.NestedProjectNodeReloader.StopObservingItem(this.GetMkDocument());
}
/// <summary>
/// Ignores observing changes on this file depending on the boolean flag.
/// </summary>
/// <param name="ignoreFlag">Flag indicating whether or not to ignore changes (1 to ignore, 0 to stop ignoring).</param>
private void IgnoreNestedProjectFile(bool ignoreFlag)
{
ProjectContainerNode parent = this.ProjectMgr as ProjectContainerNode;
ThreadHelper.ThrowIfNotOnUIThread();
Debug.Assert(parent != null, "The parent project for nested projects should be subclassed from ProjectContainerNode");
parent.NestedProjectNodeReloader.IgnoreItemChanges(this.GetMkDocument(), ignoreFlag);
}
/// <summary>
/// We need to advise property notify sink on project properties so that
/// we know when the project file is renamed through a property.
/// </summary>
private void ConnectPropertyNotifySink()
{
if (this.projectPropertyNotifySinkCookie != (uint)ShellConstants.VSCOOKIE_NIL)
{
return;
}
ThreadHelper.ThrowIfNotOnUIThread();
IConnectionPoint connectionPoint = this.GetConnectionPointFromPropertySink();
if (connectionPoint != null)
{
connectionPoint.Advise(this, out this.projectPropertyNotifySinkCookie);
}
}
/// <summary>
/// Disconnects the propertynotify sink
/// </summary>
private void DisconnectPropertyNotifySink()
{
if (this.projectPropertyNotifySinkCookie == (uint)ShellConstants.VSCOOKIE_NIL)
{
return;
}
ThreadHelper.ThrowIfNotOnUIThread();
IConnectionPoint connectionPoint = this.GetConnectionPointFromPropertySink();
if (connectionPoint != null)
{
connectionPoint.Unadvise(this.projectPropertyNotifySinkCookie);
this.projectPropertyNotifySinkCookie = (uint)ShellConstants.VSCOOKIE_NIL;
}
}
/// <summary>
/// Gets a ConnectionPoint for the IPropertyNotifySink interface.
/// </summary>
/// <returns></returns>
private IConnectionPoint GetConnectionPointFromPropertySink()
{
IConnectionPoint connectionPoint = null;
ThreadHelper.ThrowIfNotOnUIThread();
object browseObject = this.GetProperty((int)__VSHPROPID.VSHPROPID_BrowseObject);
IConnectionPointContainer connectionPointContainer = browseObject as IConnectionPointContainer;
if (connectionPointContainer != null)
{
Guid guid = typeof(IPropertyNotifySink).GUID;
connectionPointContainer.FindConnectionPoint(ref guid, out connectionPoint);
}
return connectionPoint;
}
#endregion
}
}
| |
// 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.IO;
using System.Runtime.Serialization; // For SR
using System.Text;
namespace System.Xml
{
// This wrapper does not support seek.
// Constructors consume/emit byte order mark.
// Supports: UTF-8, Unicode, BigEndianUnicode
// ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. It can be done, it would just mean more buffers.
// ASSUMPTION (Microsoft): The byte buffer is large enough to hold the declaration
// ASSUMPTION (Microsoft): The buffer manipulation methods (FillBuffer/Compare/etc.) will only be used to parse the declaration
// during construction.
internal class EncodingStreamWrapper : Stream
{
private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None }
private static readonly UTF8Encoding s_safeUTF8 = new UTF8Encoding(false, false);
private static readonly UnicodeEncoding s_safeUTF16 = new UnicodeEncoding(false, false, false);
private static readonly UnicodeEncoding s_safeBEUTF16 = new UnicodeEncoding(true, false, false);
private static readonly UTF8Encoding s_validatingUTF8 = new UTF8Encoding(false, true);
private static readonly UnicodeEncoding s_validatingUTF16 = new UnicodeEncoding(false, false, true);
private static readonly UnicodeEncoding s_validatingBEUTF16 = new UnicodeEncoding(true, false, true);
private const int BufferLength = 128;
// UTF-8 is fastpath, so that's how these are stored
// Compare methods adapt to Unicode.
private static readonly byte[] s_encodingAttr = new byte[] { (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g' };
private static readonly byte[] s_encodingUTF8 = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8' };
private static readonly byte[] s_encodingUnicode = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6' };
private static readonly byte[] s_encodingUnicodeLE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'l', (byte)'e' };
private static readonly byte[] s_encodingUnicodeBE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'b', (byte)'e' };
private SupportedEncoding _encodingCode;
private Encoding _encoding;
private Encoder _enc;
private Decoder _dec;
private bool _isReading;
private Stream _stream;
private char[] _chars;
private byte[] _bytes;
private int _byteOffset;
private int _byteCount;
private byte[] _byteBuffer = new byte[1];
// Reading constructor
public EncodingStreamWrapper(Stream stream, Encoding encoding)
{
try
{
_isReading = true;
_stream = stream;
// Decode the expected encoding
SupportedEncoding expectedEnc = GetSupportedEncoding(encoding);
// Get the byte order mark so we can determine the encoding
// May want to try to delay allocating everything until we know the BOM
SupportedEncoding declEnc = ReadBOMEncoding(encoding == null);
// Check that the expected encoding matches the decl encoding.
if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc)
ThrowExpectedEncodingMismatch(expectedEnc, declEnc);
// Fastpath: UTF-8 BOM
if (declEnc == SupportedEncoding.UTF8)
{
// Fastpath: UTF-8 BOM, No declaration
FillBuffer(2);
if (_bytes[_byteOffset + 1] != '?' || _bytes[_byteOffset] != '<')
{
return;
}
FillBuffer(BufferLength);
CheckUTF8DeclarationEncoding(_bytes, _byteOffset, _byteCount, declEnc, expectedEnc);
}
else
{
// Convert to UTF-8
EnsureBuffers();
FillBuffer((BufferLength - 1) * 2);
SetReadDocumentEncoding(declEnc);
CleanupCharBreak();
int count = _encoding.GetChars(_bytes, _byteOffset, _byteCount, _chars, 0);
_byteOffset = 0;
_byteCount = s_validatingUTF8.GetBytes(_chars, 0, count, _bytes, 0);
// Check for declaration
if (_bytes[1] == '?' && _bytes[0] == '<')
{
CheckUTF8DeclarationEncoding(_bytes, 0, _byteCount, declEnc, expectedEnc);
}
else
{
// Declaration required if no out-of-band encoding
if (expectedEnc == SupportedEncoding.None)
throw new XmlException(SR.XmlDeclarationRequired);
}
}
}
catch (DecoderFallbackException ex)
{
throw new XmlException(SR.XmlInvalidBytes, ex);
}
}
private void SetReadDocumentEncoding(SupportedEncoding e)
{
EnsureBuffers();
_encodingCode = e;
_encoding = GetEncoding(e);
}
private static Encoding GetEncoding(SupportedEncoding e)
{
switch (e)
{
case SupportedEncoding.UTF8:
return s_validatingUTF8;
case SupportedEncoding.UTF16LE:
return s_validatingUTF16;
case SupportedEncoding.UTF16BE:
return s_validatingBEUTF16;
default:
throw new XmlException(SR.XmlEncodingNotSupported);
}
}
private static Encoding GetSafeEncoding(SupportedEncoding e)
{
switch (e)
{
case SupportedEncoding.UTF8:
return s_safeUTF8;
case SupportedEncoding.UTF16LE:
return s_safeUTF16;
case SupportedEncoding.UTF16BE:
return s_safeBEUTF16;
default:
throw new XmlException(SR.XmlEncodingNotSupported);
}
}
private static string GetEncodingName(SupportedEncoding enc)
{
switch (enc)
{
case SupportedEncoding.UTF8:
return "utf-8";
case SupportedEncoding.UTF16LE:
return "utf-16LE";
case SupportedEncoding.UTF16BE:
return "utf-16BE";
default:
throw new XmlException(SR.XmlEncodingNotSupported);
}
}
private static SupportedEncoding GetSupportedEncoding(Encoding encoding)
{
if (encoding == null)
return SupportedEncoding.None;
else if (encoding.WebName == s_validatingUTF8.WebName)
return SupportedEncoding.UTF8;
else if (encoding.WebName == s_validatingUTF16.WebName)
return SupportedEncoding.UTF16LE;
else if (encoding.WebName == s_validatingBEUTF16.WebName)
return SupportedEncoding.UTF16BE;
else
throw new XmlException(SR.XmlEncodingNotSupported);
}
// Writing constructor
public EncodingStreamWrapper(Stream stream, Encoding encoding, bool emitBOM)
{
_isReading = false;
_encoding = encoding;
_stream = stream;
// Set the encoding code
_encodingCode = GetSupportedEncoding(encoding);
if (_encodingCode != SupportedEncoding.UTF8)
{
EnsureBuffers();
_dec = s_validatingUTF8.GetDecoder();
_enc = _encoding.GetEncoder();
// Emit BOM
if (emitBOM)
{
byte[] bom = _encoding.GetPreamble();
if (bom.Length > 0)
_stream.Write(bom, 0, bom.Length);
}
}
}
private SupportedEncoding ReadBOMEncoding(bool notOutOfBand)
{
int b1 = _stream.ReadByte();
int b2 = _stream.ReadByte();
int b3 = _stream.ReadByte();
int b4 = _stream.ReadByte();
// Premature end of stream
if (b4 == -1)
throw new XmlException(SR.UnexpectedEndOfFile);
int preserve;
SupportedEncoding e = ReadBOMEncoding((byte)b1, (byte)b2, (byte)b3, (byte)b4, notOutOfBand, out preserve);
EnsureByteBuffer();
switch (preserve)
{
case 1:
_bytes[0] = (byte)b4;
break;
case 2:
_bytes[0] = (byte)b3;
_bytes[1] = (byte)b4;
break;
case 4:
_bytes[0] = (byte)b1;
_bytes[1] = (byte)b2;
_bytes[2] = (byte)b3;
_bytes[3] = (byte)b4;
break;
}
_byteCount = preserve;
return e;
}
private static SupportedEncoding ReadBOMEncoding(byte b1, byte b2, byte b3, byte b4, bool notOutOfBand, out int preserve)
{
SupportedEncoding e = SupportedEncoding.UTF8; // Default
preserve = 0;
if (b1 == '<' && b2 != 0x00) // UTF-8, no BOM
{
e = SupportedEncoding.UTF8;
preserve = 4;
}
else if (b1 == 0xFF && b2 == 0xFE) // UTF-16 little endian
{
e = SupportedEncoding.UTF16LE;
preserve = 2;
}
else if (b1 == 0xFE && b2 == 0xFF) // UTF-16 big endian
{
e = SupportedEncoding.UTF16BE;
preserve = 2;
}
else if (b1 == 0x00 && b2 == '<') // UTF-16 big endian, no BOM
{
e = SupportedEncoding.UTF16BE;
if (notOutOfBand && (b3 != 0x00 || b4 != '?'))
throw new XmlException(SR.XmlDeclMissing);
preserve = 4;
}
else if (b1 == '<' && b2 == 0x00) // UTF-16 little endian, no BOM
{
e = SupportedEncoding.UTF16LE;
if (notOutOfBand && (b3 != '?' || b4 != 0x00))
throw new XmlException(SR.XmlDeclMissing);
preserve = 4;
}
else if (b1 == 0xEF && b2 == 0xBB) // UTF8 with BOM
{
// Encoding error
if (notOutOfBand && b3 != 0xBF)
throw new XmlException(SR.XmlBadBOM);
preserve = 1;
}
else // Assume UTF8
{
preserve = 4;
}
return e;
}
private void FillBuffer(int count)
{
count -= _byteCount;
while (count > 0)
{
int read = _stream.Read(_bytes, _byteOffset + _byteCount, count);
if (read == 0)
break;
_byteCount += read;
count -= read;
}
}
private void EnsureBuffers()
{
EnsureByteBuffer();
if (_chars == null)
_chars = new char[BufferLength];
}
private void EnsureByteBuffer()
{
if (_bytes != null)
return;
_bytes = new byte[BufferLength * 4];
_byteOffset = 0;
_byteCount = 0;
}
private static void CheckUTF8DeclarationEncoding(byte[] buffer, int offset, int count, SupportedEncoding e, SupportedEncoding expectedEnc)
{
byte quot = 0;
int encEq = -1;
int max = offset + Math.Min(count, BufferLength);
// Encoding should be second "=", abort at first "?"
int i = 0;
int eq = 0;
for (i = offset + 2; i < max; i++) // Skip the "<?" so we don't get caught by the first "?"
{
if (quot != 0)
{
if (buffer[i] == quot)
{
quot = 0;
}
continue;
}
if (buffer[i] == (byte)'\'' || buffer[i] == (byte)'"')
{
quot = buffer[i];
}
else if (buffer[i] == (byte)'=')
{
if (eq == 1)
{
encEq = i;
break;
}
eq++;
}
else if (buffer[i] == (byte)'?') // Not legal character in a decl before second "="
{
break;
}
}
// No encoding found
if (encEq == -1)
{
if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None)
throw new XmlException(SR.XmlDeclarationRequired);
return;
}
if (encEq < 28) // Earliest second "=" can appear
throw new XmlException(SR.XmlMalformedDecl);
// Back off whitespace
for (i = encEq - 1; IsWhitespace(buffer[i]); i--) ;
// Check for encoding attribute
if (!Compare(s_encodingAttr, buffer, i - s_encodingAttr.Length + 1))
{
if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None)
throw new XmlException(SR.XmlDeclarationRequired);
return;
}
// Move ahead of whitespace
for (i = encEq + 1; i < max && IsWhitespace(buffer[i]); i++) ;
// Find the quotes
if (buffer[i] != '\'' && buffer[i] != '"')
throw new XmlException(SR.XmlMalformedDecl);
quot = buffer[i];
int q = i;
for (i = q + 1; buffer[i] != quot && i < max; ++i) ;
if (buffer[i] != quot)
throw new XmlException(SR.XmlMalformedDecl);
int encStart = q + 1;
int encCount = i - encStart;
// lookup the encoding
SupportedEncoding declEnc = e;
if (encCount == s_encodingUTF8.Length && CompareCaseInsensitive(s_encodingUTF8, buffer, encStart))
{
declEnc = SupportedEncoding.UTF8;
}
else if (encCount == s_encodingUnicodeLE.Length && CompareCaseInsensitive(s_encodingUnicodeLE, buffer, encStart))
{
declEnc = SupportedEncoding.UTF16LE;
}
else if (encCount == s_encodingUnicodeBE.Length && CompareCaseInsensitive(s_encodingUnicodeBE, buffer, encStart))
{
declEnc = SupportedEncoding.UTF16BE;
}
else if (encCount == s_encodingUnicode.Length && CompareCaseInsensitive(s_encodingUnicode, buffer, encStart))
{
if (e == SupportedEncoding.UTF8)
ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), s_safeUTF8.GetString(s_encodingUTF8, 0, s_encodingUTF8.Length));
}
else
{
ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), e);
}
if (e != declEnc)
ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), e);
}
private static bool CompareCaseInsensitive(byte[] key, byte[] buffer, int offset)
{
for (int i = 0; i < key.Length; i++)
{
if (key[i] == buffer[offset + i])
continue;
if (key[i] != Char.ToLowerInvariant((char)buffer[offset + i]))
return false;
}
return true;
}
private static bool Compare(byte[] key, byte[] buffer, int offset)
{
for (int i = 0; i < key.Length; i++)
{
if (key[i] != buffer[offset + i])
return false;
}
return true;
}
private static bool IsWhitespace(byte ch)
{
return ch == (byte)' ' || ch == (byte)'\n' || ch == (byte)'\t' || ch == (byte)'\r';
}
internal static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding)
{
if (count < 4)
throw new XmlException(SR.UnexpectedEndOfFile);
try
{
int preserve;
ArraySegment<byte> seg;
SupportedEncoding expectedEnc = GetSupportedEncoding(encoding);
SupportedEncoding declEnc = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding == null, out preserve);
if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc)
ThrowExpectedEncodingMismatch(expectedEnc, declEnc);
offset += 4 - preserve;
count -= 4 - preserve;
// Fastpath: UTF-8
char[] chars;
byte[] bytes;
Encoding localEnc;
if (declEnc == SupportedEncoding.UTF8)
{
// Fastpath: No declaration
if (buffer[offset + 1] != '?' || buffer[offset] != '<')
{
seg = new ArraySegment<byte>(buffer, offset, count);
return seg;
}
CheckUTF8DeclarationEncoding(buffer, offset, count, declEnc, expectedEnc);
seg = new ArraySegment<byte>(buffer, offset, count);
return seg;
}
// Convert to UTF-8
localEnc = GetSafeEncoding(declEnc);
int inputCount = Math.Min(count, BufferLength * 2);
chars = new char[localEnc.GetMaxCharCount(inputCount)];
int ccount = localEnc.GetChars(buffer, offset, inputCount, chars, 0);
bytes = new byte[s_validatingUTF8.GetMaxByteCount(ccount)];
int bcount = s_validatingUTF8.GetBytes(chars, 0, ccount, bytes, 0);
// Check for declaration
if (bytes[1] == '?' && bytes[0] == '<')
{
CheckUTF8DeclarationEncoding(bytes, 0, bcount, declEnc, expectedEnc);
}
else
{
// Declaration required if no out-of-band encoding
if (expectedEnc == SupportedEncoding.None)
throw new XmlException(SR.XmlDeclarationRequired);
}
seg = new ArraySegment<byte>(s_validatingUTF8.GetBytes(GetEncoding(declEnc).GetChars(buffer, offset, count)));
return seg;
}
catch (DecoderFallbackException e)
{
throw new XmlException(SR.XmlInvalidBytes, e);
}
}
private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc)
{
throw new XmlException(SR.Format(SR.XmlExpectedEncoding, GetEncodingName(expEnc), GetEncodingName(actualEnc)));
}
private static void ThrowEncodingMismatch(string declEnc, SupportedEncoding enc)
{
ThrowEncodingMismatch(declEnc, GetEncodingName(enc));
}
private static void ThrowEncodingMismatch(string declEnc, string docEnc)
{
throw new XmlException(SR.Format(SR.XmlEncodingMismatch, declEnc, docEnc));
}
// This stream wrapper does not support duplex
public override bool CanRead
{
get
{
if (!_isReading)
return false;
return _stream.CanRead;
}
}
// The encoding conversion and buffering breaks seeking.
public override bool CanSeek
{
get
{
return false;
}
}
// This stream wrapper does not support duplex
public override bool CanWrite
{
get
{
if (_isReading)
return false;
return _stream.CanWrite;
}
}
// The encoding conversion and buffering breaks seeking.
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
protected override void Dispose(bool disposing)
{
if (_stream.CanWrite)
{
Flush();
}
_stream.Dispose();
base.Dispose(disposing);
}
public override void Flush()
{
_stream.Flush();
}
public override int ReadByte()
{
if (_byteCount == 0 && _encodingCode == SupportedEncoding.UTF8)
return _stream.ReadByte();
if (Read(_byteBuffer, 0, 1) == 0)
return -1;
return _byteBuffer[0];
}
public override int Read(byte[] buffer, int offset, int count)
{
try
{
if (_byteCount == 0)
{
if (_encodingCode == SupportedEncoding.UTF8)
return _stream.Read(buffer, offset, count);
// No more bytes than can be turned into characters
_byteOffset = 0;
_byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2);
// Check for end of stream
if (_byteCount == 0)
return 0;
// Fix up incomplete chars
CleanupCharBreak();
// Change encoding
int charCount = _encoding.GetChars(_bytes, 0, _byteCount, _chars, 0);
_byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0);
}
// Give them bytes
if (_byteCount < count)
count = _byteCount;
Buffer.BlockCopy(_bytes, _byteOffset, buffer, offset, count);
_byteOffset += count;
_byteCount -= count;
return count;
}
catch (DecoderFallbackException ex)
{
throw new XmlException(SR.XmlInvalidBytes, ex);
}
}
private void CleanupCharBreak()
{
int max = _byteOffset + _byteCount;
// Read on 2 byte boundaries
if ((_byteCount % 2) != 0)
{
int b = _stream.ReadByte();
if (b < 0)
throw new XmlException(SR.UnexpectedEndOfFile);
_bytes[max++] = (byte)b;
_byteCount++;
}
// Don't cut off a surrogate character
int w;
if (_encodingCode == SupportedEncoding.UTF16LE)
{
w = _bytes[max - 2] + (_bytes[max - 1] << 8);
}
else
{
w = _bytes[max - 1] + (_bytes[max - 2] << 8);
}
if ((w & 0xDC00) != 0xDC00 && w >= 0xD800 && w <= 0xDBFF) // First 16-bit number of surrogate pair
{
int b1 = _stream.ReadByte();
int b2 = _stream.ReadByte();
if (b2 < 0)
throw new XmlException(SR.UnexpectedEndOfFile);
_bytes[max++] = (byte)b1;
_bytes[max++] = (byte)b2;
_byteCount += 2;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void WriteByte(byte b)
{
if (_encodingCode == SupportedEncoding.UTF8)
{
_stream.WriteByte(b);
return;
}
_byteBuffer[0] = b;
Write(_byteBuffer, 0, 1);
}
public override void Write(byte[] buffer, int offset, int count)
{
// Optimize UTF-8 case
if (_encodingCode == SupportedEncoding.UTF8)
{
_stream.Write(buffer, offset, count);
return;
}
while (count > 0)
{
int size = _chars.Length < count ? _chars.Length : count;
int charCount = _dec.GetChars(buffer, offset, size, _chars, 0, false);
_byteCount = _enc.GetBytes(_chars, 0, charCount, _bytes, 0, false);
_stream.Write(_bytes, 0, _byteCount);
offset += size;
count -= size;
}
}
// Delegate properties
public override bool CanTimeout { get { return _stream.CanTimeout; } }
public override long Length { get { return _stream.Length; } }
public override int ReadTimeout
{
get { return _stream.ReadTimeout; }
set { _stream.ReadTimeout = value; }
}
public override int WriteTimeout
{
get { return _stream.WriteTimeout; }
set { _stream.WriteTimeout = value; }
}
// Delegate methods
public override void SetLength(long value)
{
throw new NotSupportedException();
}
}
// Add format exceptions
// Do we need to modify the stream position/Seek to account for the buffer?
// ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing.
}
| |
#region "Copyright"
/*
FOR FURTHER DETAILS ABOUT LICENSING, PLEASE VISIT "LICENSE.txt" INSIDE THE SAGEFRAME FOLDER
*/
#endregion
#region "References"
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
#endregion
namespace SageFrame
{
/// <summary>
/// Enitity class for image captcha.
/// </summary>
public class CaptchaImage
{
// Public properties (all read-only).
/// <summary>
/// Returns Captcha text
/// </summary>
public string Text
{
get { return this.text; }
}
/// <summary>
/// Returns bitmap image value.
/// </summary>
public Bitmap Image
{
get { return this.image; }
}
/// <summary>
/// Returns the width of the image.
/// </summary>
public int Width
{
get { return this.width; }
}
/// <summary>
/// Returns height of the image.
/// </summary>
public int Height
{
get { return this.height; }
}
// Internal properties.
private string text;
private int width;
private int height;
private string familyName;
private Bitmap image;
// For generating random numbers.
private Random random = new Random();
/// <summary>
/// Initializes a new instance of the CaptchaImage class using the specified text, width and height.
/// </summary>
/// <param name="s">Image name.</param>
/// <param name="width">Image width.</param>
/// <param name="height">Image height.</param>
public CaptchaImage(string s, int width, int height)
{
this.text = s;
this.SetDimensions(width, height);
this.GenerateImage();
}
/// <summary>
/// Initializes a new instance of the CaptchaImage class using the specified text, width, height and font family.
/// </summary>
/// <param name="s">Image name.</param>
/// <param name="width">Image width.</param>
/// <param name="height">Image height.</param>
/// <param name="familyName">Font family name.</param>
public CaptchaImage(string s, int width, int height, string familyName)
{
this.text = s;
this.SetDimensions(width, height);
this.SetFamilyName(familyName);
this.GenerateImage();
}
/// <summary>
/// This member overrides Object.Finalize.
/// </summary>
~CaptchaImage()
{
Dispose(false);
}
/// <summary>
/// Releases all resources used by this object.
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}
/// <summary>
/// Custom Dispose method to clean up unmanaged resources.
/// </summary>
/// <param name="disposing">set true if disposing.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
// Dispose of the bitmap.
this.image.Dispose();
}
/// <summary>
/// Sets the image width and height.
/// </summary>
/// <param name="width">Image width.</param>
/// <param name="height">Image height.</param>
private void SetDimensions(int width, int height)
{
// Check the width and height.
if (width <= 0)
throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");
if (height <= 0)
throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");
this.width = width;
this.height = height;
}
/// <summary>
/// Sets the font used for the image text.
/// </summary>
/// <param name="familyName">Font family name.</param>
private void SetFamilyName(string familyName)
{
// If the named font is not installed, default to a system font.
try
{
Font font = new Font(this.familyName, 12F);
this.familyName = familyName;
font.Dispose();
}
catch
{
this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
}
}
/// <summary>
/// Creates the bitmap image.
/// </summary>
private void GenerateImage()
{
// Create a new 32-bit bitmap image.
Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format48bppRgb);
// Create a graphics object for drawing.
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, this.width, this.height);
// Fill in the background.
HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);
g.FillRectangle(hatchBrush, rect);
// Set up the text font.
SizeF size;
float fontSize = rect.Height + 1;
Font font;
// Adjust the font size until the text fits within the image.
float fontWidth = rect.Width;
do
{
fontSize--;
font = new Font(this.familyName, fontSize, FontStyle.Bold);
size = g.MeasureString(this.text, font);
} while (size.Width > fontWidth);
// Set up the text format.
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
// Create a path using the text and warp it randomly.
GraphicsPath path = new GraphicsPath();
//Size fSize = new Size();
//fSize.Height = int.Parse(Math.Abs(rect.Height*0.9).ToString());
//fSize.Width = int.Parse(Math.Abs(rect.Width * 0.9).ToString());
//PointF poinf = new PointF();
//poinf.X = float.Parse(Math.Abs(rect.Width * 0.9).ToString());
//poinf.Y = float.Parse(Math.Abs(rect.Height * 0.9).ToString());
path.AddString(this.text, font.FontFamily, (int)font.Style, font.Size, rect, format);
float v = 4F;
PointF[] points =
{
new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)
};
Matrix matrix = new Matrix();
matrix.Translate(0F, 0F);
path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);
// Draw the text.
hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);
g.FillPath(hatchBrush, path);
// Add some random noise.
int m = Math.Max(rect.Width, rect.Height);
for (int i = 0; i < (int)(rect.Width * rect.Height / 30F); i++)
{
int x = this.random.Next(rect.Width);
int y = this.random.Next(rect.Height);
int w = this.random.Next(m / 50);
int h = this.random.Next(m / 50);
g.FillEllipse(hatchBrush, x, y, w, h);
}
// Clean up.
font.Dispose();
hatchBrush.Dispose();
g.Dispose();
// Set the image.
this.image = bitmap;
}
}
}
| |
// 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.Text;
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
public class DebugNameFormatter : TypeNameFormatter<DebugNameFormatter.Void, DebugNameFormatter.FormatOptions>
{
public static readonly DebugNameFormatter Instance = new DebugNameFormatter();
public override Void AppendName(StringBuilder sb, ArrayType type, FormatOptions options)
{
AppendName(sb, type.ElementType, options);
if (!type.IsSzArray && type.Rank == 1)
{
sb.Append("[*]");
}
else
{
sb.Append('[');
sb.Append(',', type.Rank - 1);
sb.Append(']');
}
return Void.Value;
}
public override Void AppendName(StringBuilder sb, ByRefType type, FormatOptions options)
{
AppendName(sb, type.ParameterType, options);
sb.Append('&');
return Void.Value;
}
public override Void AppendName(StringBuilder sb, PointerType type, FormatOptions options)
{
AppendName(sb, type.ParameterType, options);
sb.Append('*');
return Void.Value;
}
public override Void AppendName(StringBuilder sb, FunctionPointerType type, FormatOptions options)
{
MethodSignature signature = type.Signature;
sb.Append("(*");
AppendName(sb, signature.ReturnType, options);
sb.Append(")(");
for (int i = 0; i < signature.Length; i++)
{
if (i > 0)
sb.Append(',');
AppendName(sb, signature[i], options);
}
sb.Append(')');
return Void.Value;
}
public override Void AppendName(StringBuilder sb, GenericParameterDesc type, FormatOptions options)
{
sb.Append(type.Name);
return Void.Value;
}
public override Void AppendName(StringBuilder sb, SignatureMethodVariable type, FormatOptions options)
{
sb.Append("!!");
sb.Append(type.Index);
return Void.Value;
}
public override Void AppendName(StringBuilder sb, SignatureTypeVariable type, FormatOptions options)
{
sb.Append("!");
sb.Append(type.Index);
return Void.Value;
}
protected override Void AppendNameForNestedType(StringBuilder sb, DefType nestedType, DefType containingType, FormatOptions options)
{
if ((options & FormatOptions.NamespaceQualify) != 0)
{
AppendName(sb, containingType, options);
sb.Append('+');
}
sb.Append(nestedType.Name);
return Void.Value;
}
protected override Void AppendNameForNamespaceType(StringBuilder sb, DefType type, FormatOptions options)
{
// Shortcut some of the well known types
switch (type.Category)
{
case TypeFlags.Void:
sb.Append("void");
return Void.Value;
case TypeFlags.Boolean:
sb.Append("bool");
return Void.Value;
case TypeFlags.Char:
sb.Append("char");
return Void.Value;
case TypeFlags.SByte:
sb.Append("int8");
return Void.Value;
case TypeFlags.Byte:
sb.Append("uint8");
return Void.Value;
case TypeFlags.Int16:
sb.Append("int16");
return Void.Value;
case TypeFlags.UInt16:
sb.Append("uint16");
return Void.Value;
case TypeFlags.Int32:
sb.Append("int32");
return Void.Value;
case TypeFlags.UInt32:
sb.Append("uint32");
return Void.Value;
case TypeFlags.Int64:
sb.Append("int64");
return Void.Value;
case TypeFlags.UInt64:
sb.Append("uint64");
return Void.Value;
case TypeFlags.IntPtr:
sb.Append("native int");
return Void.Value;
case TypeFlags.UIntPtr:
sb.Append("native uint");
return Void.Value;
case TypeFlags.Single:
sb.Append("float32");
return Void.Value;
case TypeFlags.Double:
sb.Append("float64");
return Void.Value;
}
if (type.IsString)
{
sb.Append("string");
return Void.Value;
}
if (type.IsObject)
{
sb.Append("object");
return Void.Value;
}
if (((options & FormatOptions.AssemblyQualify) != 0)
&& type is MetadataType mdType
&& mdType.Module is IAssemblyDesc)
{
sb.Append('[');
// Trim the "System.Private." prefix
string assemblyName = ((IAssemblyDesc)mdType.Module).GetName().Name;
if (assemblyName.StartsWith("System.Private"))
assemblyName = "S.P" + assemblyName.Substring(14);
sb.Append(assemblyName);
sb.Append(']');
}
if ((options & FormatOptions.NamespaceQualify) != 0)
{
string ns = type.Namespace;
if (!string.IsNullOrEmpty(ns))
{
sb.Append(ns);
sb.Append('.');
}
}
sb.Append(type.Name);
return Void.Value;
}
protected override Void AppendNameForInstantiatedType(StringBuilder sb, DefType type, FormatOptions options)
{
AppendName(sb, type.GetTypeDefinition(), options);
FormatOptions parameterOptions = options & ~FormatOptions.AssemblyQualify;
sb.Append('<');
for (int i = 0; i < type.Instantiation.Length; i++)
{
if (i != 0)
sb.Append(',');
AppendName(sb, type.Instantiation[i], parameterOptions);
}
sb.Append('>');
return Void.Value;
}
public struct Void
{
public static Void Value => default(Void);
}
[Flags]
public enum FormatOptions
{
None = 0,
AssemblyQualify = 0x1,
NamespaceQualify = 0x2,
Default = AssemblyQualify | NamespaceQualify,
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.ComponentModel;
using System.Collections.Generic;
using System.Net.Security;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Xml;
public class SslStreamSecurityBindingElement : StreamUpgradeBindingElement, ITransportTokenAssertionProvider, IPolicyExportExtension
{
IdentityVerifier identityVerifier;
bool requireClientCertificate;
public SslStreamSecurityBindingElement()
{
this.requireClientCertificate = TransportDefaults.RequireClientCertificate;
}
protected SslStreamSecurityBindingElement(SslStreamSecurityBindingElement elementToBeCloned)
: base(elementToBeCloned)
{
this.identityVerifier = elementToBeCloned.identityVerifier;
this.requireClientCertificate = elementToBeCloned.requireClientCertificate;
}
public IdentityVerifier IdentityVerifier
{
get
{
if (this.identityVerifier == null)
{
this.identityVerifier = IdentityVerifier.CreateDefault();
}
return this.identityVerifier;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
this.identityVerifier = value;
}
}
[DefaultValue(TransportDefaults.RequireClientCertificate)]
public bool RequireClientCertificate
{
get
{
return this.requireClientCertificate;
}
set
{
this.requireClientCertificate = value;
}
}
public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
#pragma warning suppress 56506 // [....], BindingContext.BindingParameters cannot be null
context.BindingParameters.Add(this);
return context.BuildInnerChannelFactory<TChannel>();
}
public override bool CanBuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
#pragma warning suppress 56506 // [....], BindingContext.BindingParameters cannot be null
context.BindingParameters.Add(this);
return context.CanBuildInnerChannelFactory<TChannel>();
}
public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
#pragma warning suppress 56506 // [....], BindingContext.BindingParameters cannot be null
context.BindingParameters.Add(this);
return context.BuildInnerChannelListener<TChannel>();
}
public override bool CanBuildChannelListener<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
#pragma warning suppress 56506 // [....], BindingContext.BindingParameters cannot be null
context.BindingParameters.Add(this);
return context.CanBuildInnerChannelListener<TChannel>();
}
public override BindingElement Clone()
{
return new SslStreamSecurityBindingElement(this);
}
public override T GetProperty<T>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
if (typeof(T) == typeof(ISecurityCapabilities))
{
return (T)(object)new SecurityCapabilities(this.RequireClientCertificate, true, this.RequireClientCertificate,
ProtectionLevel.EncryptAndSign, ProtectionLevel.EncryptAndSign);
}
else if (typeof(T) == typeof(IdentityVerifier))
{
return (T)(object)this.IdentityVerifier;
}
else
{
return context.GetInnerProperty<T>();
}
}
public override StreamUpgradeProvider BuildClientStreamUpgradeProvider(BindingContext context)
{
return SslStreamSecurityUpgradeProvider.CreateClientProvider(this, context);
}
public override StreamUpgradeProvider BuildServerStreamUpgradeProvider(BindingContext context)
{
return SslStreamSecurityUpgradeProvider.CreateServerProvider(this, context);
}
internal static void ImportPolicy(MetadataImporter importer, PolicyConversionContext policyContext)
{
XmlElement assertion = PolicyConversionContext.FindAssertion(policyContext.GetBindingAssertions(),
TransportPolicyConstants.SslTransportSecurityName, TransportPolicyConstants.DotNetFramingNamespace, true);
if (assertion != null)
{
SslStreamSecurityBindingElement sslBindingElement = new SslStreamSecurityBindingElement();
XmlReader reader = new XmlNodeReader(assertion);
reader.ReadStartElement();
sslBindingElement.RequireClientCertificate = reader.IsStartElement(
TransportPolicyConstants.RequireClientCertificateName,
TransportPolicyConstants.DotNetFramingNamespace);
if (sslBindingElement.RequireClientCertificate)
{
reader.ReadElementString();
}
policyContext.BindingElements.Add(sslBindingElement);
}
}
#region ITransportTokenAssertionProvider Members
public XmlElement GetTransportTokenAssertion()
{
XmlDocument document = new XmlDocument();
XmlElement assertion =
document.CreateElement(TransportPolicyConstants.DotNetFramingPrefix,
TransportPolicyConstants.SslTransportSecurityName,
TransportPolicyConstants.DotNetFramingNamespace);
if (this.requireClientCertificate)
{
assertion.AppendChild(document.CreateElement(TransportPolicyConstants.DotNetFramingPrefix,
TransportPolicyConstants.RequireClientCertificateName,
TransportPolicyConstants.DotNetFramingNamespace));
}
return assertion;
}
#endregion
void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
{
if (exporter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exporter");
}
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
SecurityBindingElement.ExportPolicyForTransportTokenAssertionProviders(exporter, context);
}
internal override bool IsMatch(BindingElement b)
{
if (b == null)
{
return false;
}
SslStreamSecurityBindingElement ssl = b as SslStreamSecurityBindingElement;
if (ssl == null)
{
return false;
}
return this.requireClientCertificate == ssl.requireClientCertificate;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeIdentityVerifier()
{
// IdentifyVerifier.CreateDefault() grabs the static instance of nested DefaultIdentityVerifier.
// DefaultIdentityVerifier can't be serialized directly because it's nested.
return (!object.ReferenceEquals(this.IdentityVerifier, IdentityVerifier.CreateDefault()));
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.WinHttpHandlerUnitTests
{
public class WinHttpHandlerTest
{
private const string FakeProxy = "http://proxy.contoso.com";
private readonly ITestOutputHelper _output;
public WinHttpHandlerTest(ITestOutputHelper output)
{
_output = output;
TestControl.ResetAll();
}
[Fact]
public void Ctor_ExpectedDefaultPropertyValues()
{
var handler = new WinHttpHandler();
Assert.Equal(SslProtocolSupport.DefaultSslProtocols, handler.SslProtocols);
Assert.Equal(true, handler.AutomaticRedirection);
Assert.Equal(50, handler.MaxAutomaticRedirections);
Assert.Equal(DecompressionMethods.Deflate | DecompressionMethods.GZip, handler.AutomaticDecompression);
Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy);
Assert.Equal(null, handler.CookieContainer);
Assert.Equal(null, handler.ServerCertificateValidationCallback);
Assert.Equal(false, handler.CheckCertificateRevocationList);
Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOption);
X509Certificate2Collection certs = handler.ClientCertificates;
Assert.True(certs.Count == 0);
Assert.Equal(false, handler.PreAuthenticate);
Assert.Equal(null, handler.ServerCredentials);
Assert.Equal(WindowsProxyUsePolicy.UseWinHttpProxy, handler.WindowsProxyUsePolicy);
Assert.Equal(CredentialCache.DefaultCredentials, handler.DefaultProxyCredentials);
Assert.Equal(null, handler.Proxy);
Assert.Equal(Int32.MaxValue, handler.MaxConnectionsPerServer);
Assert.Equal(TimeSpan.FromSeconds(60), handler.ConnectTimeout);
Assert.Equal(TimeSpan.FromSeconds(30), handler.SendTimeout);
Assert.Equal(TimeSpan.FromSeconds(30), handler.ReceiveHeadersTimeout);
Assert.Equal(TimeSpan.FromSeconds(30), handler.ReceiveDataTimeout);
Assert.Equal(64 * 1024, handler.MaxResponseHeadersLength);
Assert.Equal(64 * 1024, handler.MaxResponseDrainSize);
}
[Fact]
public void AutomaticRedirection_SetFalseAndGet_ValueIsFalse()
{
var handler = new WinHttpHandler();
handler.AutomaticRedirection = false;
Assert.False(handler.AutomaticRedirection);
}
[Fact]
public void AutomaticRedirection_SetTrue_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.AutomaticRedirection = true; });
Assert.Equal(
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP,
APICallHistory.WinHttpOptionRedirectPolicy);
}
[Fact]
public void AutomaticRedirection_SetFalse_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.AutomaticRedirection = false; });
Assert.Equal(
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER,
APICallHistory.WinHttpOptionRedirectPolicy);
}
[Fact]
public void CheckCertificateRevocationList_SetTrue_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.CheckCertificateRevocationList = true; });
Assert.True(APICallHistory.WinHttpOptionEnableSslRevocation.Value);
}
[Fact]
public void CheckCertificateRevocationList_SetFalse_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.CheckCertificateRevocationList = false; });
Assert.Equal(false, APICallHistory.WinHttpOptionEnableSslRevocation.HasValue);
}
[Fact]
public void ConnectTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.ConnectTimeout = TimeSpan.FromMinutes(-10); });
}
[Fact]
public void ConnectTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ConnectTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); });
}
[Fact]
public void ConnectTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.ConnectTimeout = TimeSpan.FromSeconds(0); });
}
[Fact]
public void ConnectTimeout_SetInfiniteValue_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.ConnectTimeout = Timeout.InfiniteTimeSpan;
}
[Fact]
public void CookieContainer_WhenCreated_ReturnsNull()
{
var handler = new WinHttpHandler();
Assert.Null(handler.CookieContainer);
}
[Fact]
public async void CookieUsePolicy_UseSpecifiedCookieContainerAndNullContainer_ThrowsInvalidOperationException()
{
var handler = new WinHttpHandler();
Assert.Null(handler.CookieContainer);
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
[Fact]
public void CookieUsePolicy_SetUsingInvalidEnum_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.CookieUsePolicy = (CookieUsePolicy)100; });
}
[Fact]
public void CookieUsePolicy_WhenCreated_ReturnsUseInternalCookieStoreOnly()
{
var handler = new WinHttpHandler();
Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy);
}
[Fact]
public void CookieUsePolicy_SetIgnoreCookies_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies;
}
[Fact]
public void CookieUsePolicy_SetUseInternalCookieStoreOnly_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
}
[Fact]
public void CookieUsePolicy_SetUseSpecifiedCookieContainer_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
}
[Fact]
public void CookieUsePolicy_SetIgnoreCookies_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies; });
Assert.True(APICallHistory.WinHttpOptionDisableCookies.Value);
}
[Fact]
public void CookieUsePolicy_SetUseInternalCookieStoreOnly_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly; });
Assert.Equal(false, APICallHistory.WinHttpOptionDisableCookies.HasValue);
}
[Fact]
public void CookieUsePolicy_SetUseSpecifiedCookieContainerAndContainer_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate {
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
handler.CookieContainer = new CookieContainer();
});
Assert.Equal(true, APICallHistory.WinHttpOptionDisableCookies.HasValue);
}
[Fact]
public void WindowsProxyUsePolicy_SetUsingInvalidEnum_ThrowArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.WindowsProxyUsePolicy = (WindowsProxyUsePolicy)100; });
}
[Fact]
public void WindowsProxyUsePolicy_SetDoNotUseProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy;
}
[Fact]
public void WindowsProxyUsePolicy_SetUseWinHttpProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
}
[Fact]
public void WindowsProxyUsePolicy_SetUseWinWinInetProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
}
[Fact]
public void WindowsProxyUsePolicy_SetUseCustomProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
}
[Fact]
public async Task WindowsProxyUsePolicy_UseNonNullProxyAndIncorrectWindowsProxyUsePolicy_ThrowsInvalidOperationException()
{
var handler = new WinHttpHandler();
handler.Proxy = new CustomProxy(false);
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy;
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
[Fact]
public async Task WindowsProxyUsePolicy_UseCustomProxyAndNullProxy_ThrowsInvalidOperationException()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = null;
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
[Fact]
public void MaxAutomaticRedirections_SetZero_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxAutomaticRedirections = 0; });
}
[Fact]
public void MaxAutomaticRedirections_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxAutomaticRedirections = -1; });
}
[Fact]
public void MaxAutomaticRedirections_SetValidValue_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
int redirections = 35;
SendRequestHelper.Send(handler, delegate { handler.MaxAutomaticRedirections = redirections; });
Assert.Equal((uint)redirections, APICallHistory.WinHttpOptionMaxHttpAutomaticRedirects);
}
[Fact]
public void MaxConnectionsPerServer_SetZero_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxConnectionsPerServer = 0; });
}
[Fact]
public void MaxConnectionsPerServer_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxConnectionsPerServer = -1; });
}
[Fact]
public void MaxConnectionsPerServer_SetPositiveValue_Success()
{
var handler = new WinHttpHandler();
handler.MaxConnectionsPerServer = 1;
}
[Fact]
public void ReceiveDataTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveDataTimeout = TimeSpan.FromMinutes(-10); });
}
[Fact]
public void ReceiveDataTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveDataTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); });
}
[Fact]
public void ReceiveDataTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.ReceiveDataTimeout = TimeSpan.FromSeconds(0); });
}
[Fact]
public void ReceiveDataTimeout_SetInfiniteValue_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.ReceiveDataTimeout = Timeout.InfiniteTimeSpan;
}
[Fact]
public void ReceiveHeadersTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveHeadersTimeout = TimeSpan.FromMinutes(-10); });
}
[Fact]
public void ReceiveHeadersTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveHeadersTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); });
}
[Fact]
public void ReceiveHeadersTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveHeadersTimeout = TimeSpan.FromSeconds(0); });
}
[Fact]
public void ReceiveHeadersTimeout_SetInfiniteValue_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.ConnectTimeout = Timeout.InfiniteTimeSpan;
}
[Theory]
[ClassData(typeof(SslProtocolSupport.UnsupportedSslProtocolsTestData))]
public void SslProtocols_SetUsingUnsupported_Throws(SslProtocols protocol)
{
var handler = new WinHttpHandler();
Assert.Throws<NotSupportedException>(() => { handler.SslProtocols = protocol; });
}
[Theory]
[ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))]
public void SslProtocols_SetUsingSupported_Success(SslProtocols protocol)
{
var handler = new WinHttpHandler();
handler.SslProtocols = protocol;
}
[Fact]
public void SslProtocols_SetUsingNone_Throws()
{
var handler = new WinHttpHandler();
Assert.Throws<NotSupportedException>(() => { handler.SslProtocols = SslProtocols.None; });
}
[Fact]
public void SslProtocols_SetUsingInvalidEnum_Throws()
{
var handler = new WinHttpHandler();
Assert.Throws<NotSupportedException>(() => { handler.SslProtocols = (SslProtocols)4096; });
}
[Fact]
public void SslProtocols_SetUsingValidEnums_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.SslProtocols =
SslProtocols.Tls |
SslProtocols.Tls11 |
SslProtocols.Tls12;
});
uint expectedProtocols =
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 |
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 |
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
Assert.Equal(expectedProtocols, APICallHistory.WinHttpOptionSecureProtocols);
}
[Fact]
public async Task GetAsync_MultipleRequestsReusingSameClient_Success()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
HttpResponseMessage response = await client.GetAsync(TestServer.FakeServerEndpoint);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
response = await client.GetAsync(TestServer.FakeServerEndpoint);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
response = await client.GetAsync(TestServer.FakeServerEndpoint);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
client.Dispose();
}
[Fact]
public async Task SendAsync_ReadFromStreamingServer_PartialDataRead()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
TestServer.DataAvailablePercentage = 0.25;
int bytesRead;
byte[] buffer = new byte[TestServer.ExpectedResponseBody.Length];
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var stream = await response.Content.ReadAsStreamAsync();
bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
_output.WriteLine("bytesRead={0}", bytesRead);
}
client.Dispose();
Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length");
}
[Fact]
public async Task SendAsync_ReadAllDataFromStreamingServer_AllDataRead()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
TestServer.DataAvailablePercentage = 0.25;
int totalBytesRead = 0;
int bytesRead;
byte[] buffer = new byte[TestServer.ExpectedResponseBody.Length];
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var stream = await response.Content.ReadAsStreamAsync();
do
{
bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
_output.WriteLine("bytesRead={0}", bytesRead);
totalBytesRead += bytesRead;
} while (bytesRead != 0);
}
client.Dispose();
Assert.Equal(buffer.Length, totalBytesRead);
}
[Fact]
public async Task SendAsync_PostContentWithContentLengthAndChunkedEncodingHeaders_Success()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
client.DefaultRequestHeaders.TransferEncodingChunked = true;
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var content = new StringContent(TestServer.ExpectedResponseBody);
Assert.True(content.Headers.ContentLength.HasValue);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
}
[Fact]
public async Task SendAsync_PostNoContentObjectWithChunkedEncodingHeader_ExpectInvalidOperationException()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
client.DefaultRequestHeaders.TransferEncodingChunked = true;
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
[Fact]
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsDeflateCompressed_ExpectedResponse()
{
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
TestServer.SetResponse(DecompressionMethods.Deflate, TestServer.ExpectedResponseBody);
});
Assert.Null(response.Content.Headers.ContentLength);
string responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(0, response.Content.Headers.ContentEncoding.Count);
Assert.Equal(TestServer.ExpectedResponseBody, responseBody);
}
[Fact]
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsGZipCompressed_ExpectedResponse()
{
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
TestServer.SetResponse(DecompressionMethods.GZip, TestServer.ExpectedResponseBody);
});
Assert.Null(response.Content.Headers.ContentLength);
string responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(0, response.Content.Headers.ContentEncoding.Count);
Assert.Equal(TestServer.ExpectedResponseBody, responseBody);
}
[Fact]
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsNotCompressed_ExpectedResponse()
{
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.NotNull(response.Content.Headers.ContentLength);
string responseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(TestServer.ExpectedResponseBody, responseBody);
}
[Fact]
public void SendAsync_AutomaticProxySupportAndUseWinInetSettings_ExpectedWinHttpSessionProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, APICallHistory.SessionProxySettings.AccessType);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectSetting_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.AutoDetect = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithEmptySettings_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithManualSettingsOnly_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.Proxy = FakeProxy;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithMissingRegistrySettings_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.RegistryKeyMissing = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectButPACFileNotDetectedOnNetwork_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
TestControl.PACFileNotDetectedOnNetwork = true;
FakeRegistry.WinInetProxySettings.AutoDetect = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.RequestProxySettings.AccessType);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectSettingAndManualSettingButPACFileNotFoundOnNetwork_ExpectedWinHttpProxySettings()
{
const string manualProxy = FakeProxy;
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.AutoDetect = true;
FakeRegistry.WinInetProxySettings.Proxy = manualProxy;
TestControl.PACFileNotDetectedOnNetwork = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
// Both AutoDetect and manual proxy are specified. If AutoDetect fails to find
// the PAC file on the network, then we should fall back to manual setting.
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType);
Assert.Equal(manualProxy, APICallHistory.RequestProxySettings.Proxy);
}
[Fact]
public void SendAsync_UseNoProxy_ExpectedWinHttpProxySettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy; });
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
}
[Fact]
public void SendAsync_UseCustomProxyWithNoBypass_ExpectedWinHttpProxySettings()
{
var handler = new WinHttpHandler();
var customProxy = new CustomProxy(false);
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = customProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType);
Assert.Equal(FakeProxy, APICallHistory.RequestProxySettings.Proxy);
}
[Fact]
public void SendAsync_UseCustomProxyWithBypass_ExpectedWinHttpProxySettings()
{
var handler = new WinHttpHandler();
var customProxy = new CustomProxy(true);
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = customProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.RequestProxySettings.AccessType);
}
[Fact]
public void SendAsync_AutomaticProxySupportAndUseDefaultWebProxy_ExpectedWinHttpSessionProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = new FakeDefaultWebProxy();
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, APICallHistory.SessionProxySettings.AccessType);
}
[Fact]
public async Task SendAsync_SlowPostRequestWithTimedCancellation_ExpectTaskCanceledException()
{
var handler = new WinHttpHandler();
TestControl.WinHttpReceiveResponse.Delay = 5000;
CancellationTokenSource cts = new CancellationTokenSource(50);
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
var content = new StringContent(new String('a', 1000));
request.Content = content;
await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token));
}
[Fact]
public async Task SendAsync_SlowGetRequestWithTimedCancellation_ExpectTaskCanceledException()
{
var handler = new WinHttpHandler();
TestControl.WinHttpReceiveResponse.Delay = 5000;
CancellationTokenSource cts = new CancellationTokenSource(50);
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token));
}
[Fact]
public async Task SendAsync_RequestWithCanceledToken_ExpectTaskCanceledException()
{
var handler = new WinHttpHandler();
CancellationTokenSource cts = new CancellationTokenSource();
cts.Cancel();
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token));
}
[Fact]
public async Task SendAsync_WinHttpOpenReturnsError_ExpectHttpRequestException()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
TestControl.WinHttpOpen.ErrorWithApiCall = true;
Exception ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(request));
Assert.Equal(typeof(WinHttpException), ex.InnerException.GetType());
}
[Fact]
public void SendAsync_MultipleCallsWithDispose_NoHandleLeaksManuallyVerifiedUsingLogging()
{
WinHttpHandler handler;
HttpResponseMessage response;
for (int i = 0; i < 50; i++)
{
handler = new WinHttpHandler();
response = SendRequestHelper.Send(handler, () => { });
response.Dispose();
handler.Dispose();
}
}
[Fact]
public void SendAsync_MultipleCallsWithoutDispose_NoHandleLeaksManuallyVerifiedUsingLogging()
{
WinHttpHandler handler;
HttpResponseMessage response;
for (int i = 0; i < 50; i++)
{
handler = new WinHttpHandler();
response = SendRequestHelper.Send(handler, () => { });
}
}
public class CustomProxy : IWebProxy
{
private const string DefaultDomain = "domain";
private const string DefaultUsername = "username";
private const string DefaultPassword = "password";
private bool bypassAll;
private NetworkCredential networkCredential;
public CustomProxy(bool bypassAll)
{
this.bypassAll = bypassAll;
this.networkCredential = new NetworkCredential(CustomProxy.DefaultUsername, CustomProxy.DefaultPassword, CustomProxy.DefaultDomain);
}
public string UsernameWithDomain
{
get
{
return CustomProxy.DefaultDomain + "\\" + CustomProxy.DefaultUsername;
}
}
public string Password
{
get
{
return CustomProxy.DefaultPassword;
}
}
public NetworkCredential NetworkCredential
{
get
{
return this.networkCredential;
}
}
ICredentials IWebProxy.Credentials
{
get
{
return this.networkCredential;
}
set
{
}
}
Uri IWebProxy.GetProxy(Uri destination)
{
return new Uri(FakeProxy);
}
bool IWebProxy.IsBypassed(Uri host)
{
return this.bypassAll;
}
}
public class FakeDefaultWebProxy : IWebProxy
{
private ICredentials _credentials = null;
public FakeDefaultWebProxy()
{
}
public ICredentials Credentials
{
get
{
return _credentials;
}
set
{
_credentials = value;
}
}
// This is a sentinel object representing the internal default system proxy that a developer would
// use when accessing the System.Net.WebRequest.DefaultWebProxy property (from the System.Net.Requests
// package). It can't support the GetProxy or IsBypassed methods. WinHttpHandler will handle this
// exception and use the appropriate system default proxy.
public Uri GetProxy(Uri destination)
{
throw new PlatformNotSupportedException();
}
public bool IsBypassed(Uri host)
{
throw new PlatformNotSupportedException();
}
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// EmailPlan
/// </summary>
[DataContract]
public partial class EmailPlan : IEquatable<EmailPlan>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="EmailPlan" /> class.
/// </summary>
/// <param name="additionalCustomers">additionalCustomers.</param>
/// <param name="additionalEmails">additionalEmails.</param>
/// <param name="additionalFee">additionalFee.</param>
/// <param name="allowListImport">allowListImport.</param>
/// <param name="allowTrackingEmails">allowTrackingEmails.</param>
/// <param name="customerTiers">customerTiers.</param>
/// <param name="initialSendingLimits">initialSendingLimits.</param>
/// <param name="planCustomers">planCustomers.</param>
/// <param name="planEmails">planEmails.</param>
/// <param name="planName">planName.</param>
/// <param name="planNameFormatted">planNameFormatted.</param>
/// <param name="requireOrderWithinLastDays">requireOrderWithinLastDays.</param>
/// <param name="revenuePercent">revenuePercent.</param>
/// <param name="spamPercentLimit">spamPercentLimit.</param>
/// <param name="totalCustomers">totalCustomers.</param>
/// <param name="totalEmails">totalEmails.</param>
/// <param name="upgradeTo">upgradeTo.</param>
public EmailPlan(int? additionalCustomers = default(int?), int? additionalEmails = default(int?), decimal? additionalFee = default(decimal?), bool? allowListImport = default(bool?), bool? allowTrackingEmails = default(bool?), List<EmailPlanAdditional> customerTiers = default(List<EmailPlanAdditional>), int? initialSendingLimits = default(int?), int? planCustomers = default(int?), int? planEmails = default(int?), string planName = default(string), string planNameFormatted = default(string), int? requireOrderWithinLastDays = default(int?), int? revenuePercent = default(int?), int? spamPercentLimit = default(int?), int? totalCustomers = default(int?), int? totalEmails = default(int?), int? upgradeTo = default(int?))
{
this.AdditionalCustomers = additionalCustomers;
this.AdditionalEmails = additionalEmails;
this.AdditionalFee = additionalFee;
this.AllowListImport = allowListImport;
this.AllowTrackingEmails = allowTrackingEmails;
this.CustomerTiers = customerTiers;
this.InitialSendingLimits = initialSendingLimits;
this.PlanCustomers = planCustomers;
this.PlanEmails = planEmails;
this.PlanName = planName;
this.PlanNameFormatted = planNameFormatted;
this.RequireOrderWithinLastDays = requireOrderWithinLastDays;
this.RevenuePercent = revenuePercent;
this.SpamPercentLimit = spamPercentLimit;
this.TotalCustomers = totalCustomers;
this.TotalEmails = totalEmails;
this.UpgradeTo = upgradeTo;
}
/// <summary>
/// Gets or Sets AdditionalCustomers
/// </summary>
[DataMember(Name="additional_customers", EmitDefaultValue=false)]
public int? AdditionalCustomers { get; set; }
/// <summary>
/// Gets or Sets AdditionalEmails
/// </summary>
[DataMember(Name="additional_emails", EmitDefaultValue=false)]
public int? AdditionalEmails { get; set; }
/// <summary>
/// Gets or Sets AdditionalFee
/// </summary>
[DataMember(Name="additional_fee", EmitDefaultValue=false)]
public decimal? AdditionalFee { get; set; }
/// <summary>
/// Gets or Sets AllowListImport
/// </summary>
[DataMember(Name="allow_list_import", EmitDefaultValue=false)]
public bool? AllowListImport { get; set; }
/// <summary>
/// Gets or Sets AllowTrackingEmails
/// </summary>
[DataMember(Name="allow_tracking_emails", EmitDefaultValue=false)]
public bool? AllowTrackingEmails { get; set; }
/// <summary>
/// Gets or Sets CustomerTiers
/// </summary>
[DataMember(Name="customer_tiers", EmitDefaultValue=false)]
public List<EmailPlanAdditional> CustomerTiers { get; set; }
/// <summary>
/// Gets or Sets InitialSendingLimits
/// </summary>
[DataMember(Name="initial_sending_limits", EmitDefaultValue=false)]
public int? InitialSendingLimits { get; set; }
/// <summary>
/// Gets or Sets PlanCustomers
/// </summary>
[DataMember(Name="plan_customers", EmitDefaultValue=false)]
public int? PlanCustomers { get; set; }
/// <summary>
/// Gets or Sets PlanEmails
/// </summary>
[DataMember(Name="plan_emails", EmitDefaultValue=false)]
public int? PlanEmails { get; set; }
/// <summary>
/// Gets or Sets PlanName
/// </summary>
[DataMember(Name="plan_name", EmitDefaultValue=false)]
public string PlanName { get; set; }
/// <summary>
/// Gets or Sets PlanNameFormatted
/// </summary>
[DataMember(Name="plan_name_formatted", EmitDefaultValue=false)]
public string PlanNameFormatted { get; set; }
/// <summary>
/// Gets or Sets RequireOrderWithinLastDays
/// </summary>
[DataMember(Name="require_order_within_last_days", EmitDefaultValue=false)]
public int? RequireOrderWithinLastDays { get; set; }
/// <summary>
/// Gets or Sets RevenuePercent
/// </summary>
[DataMember(Name="revenue_percent", EmitDefaultValue=false)]
public int? RevenuePercent { get; set; }
/// <summary>
/// Gets or Sets SpamPercentLimit
/// </summary>
[DataMember(Name="spam_percent_limit", EmitDefaultValue=false)]
public int? SpamPercentLimit { get; set; }
/// <summary>
/// Gets or Sets TotalCustomers
/// </summary>
[DataMember(Name="total_customers", EmitDefaultValue=false)]
public int? TotalCustomers { get; set; }
/// <summary>
/// Gets or Sets TotalEmails
/// </summary>
[DataMember(Name="total_emails", EmitDefaultValue=false)]
public int? TotalEmails { get; set; }
/// <summary>
/// Gets or Sets UpgradeTo
/// </summary>
[DataMember(Name="upgrade_to", EmitDefaultValue=false)]
public int? UpgradeTo { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class EmailPlan {\n");
sb.Append(" AdditionalCustomers: ").Append(AdditionalCustomers).Append("\n");
sb.Append(" AdditionalEmails: ").Append(AdditionalEmails).Append("\n");
sb.Append(" AdditionalFee: ").Append(AdditionalFee).Append("\n");
sb.Append(" AllowListImport: ").Append(AllowListImport).Append("\n");
sb.Append(" AllowTrackingEmails: ").Append(AllowTrackingEmails).Append("\n");
sb.Append(" CustomerTiers: ").Append(CustomerTiers).Append("\n");
sb.Append(" InitialSendingLimits: ").Append(InitialSendingLimits).Append("\n");
sb.Append(" PlanCustomers: ").Append(PlanCustomers).Append("\n");
sb.Append(" PlanEmails: ").Append(PlanEmails).Append("\n");
sb.Append(" PlanName: ").Append(PlanName).Append("\n");
sb.Append(" PlanNameFormatted: ").Append(PlanNameFormatted).Append("\n");
sb.Append(" RequireOrderWithinLastDays: ").Append(RequireOrderWithinLastDays).Append("\n");
sb.Append(" RevenuePercent: ").Append(RevenuePercent).Append("\n");
sb.Append(" SpamPercentLimit: ").Append(SpamPercentLimit).Append("\n");
sb.Append(" TotalCustomers: ").Append(TotalCustomers).Append("\n");
sb.Append(" TotalEmails: ").Append(TotalEmails).Append("\n");
sb.Append(" UpgradeTo: ").Append(UpgradeTo).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as EmailPlan);
}
/// <summary>
/// Returns true if EmailPlan instances are equal
/// </summary>
/// <param name="input">Instance of EmailPlan to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(EmailPlan input)
{
if (input == null)
return false;
return
(
this.AdditionalCustomers == input.AdditionalCustomers ||
(this.AdditionalCustomers != null &&
this.AdditionalCustomers.Equals(input.AdditionalCustomers))
) &&
(
this.AdditionalEmails == input.AdditionalEmails ||
(this.AdditionalEmails != null &&
this.AdditionalEmails.Equals(input.AdditionalEmails))
) &&
(
this.AdditionalFee == input.AdditionalFee ||
(this.AdditionalFee != null &&
this.AdditionalFee.Equals(input.AdditionalFee))
) &&
(
this.AllowListImport == input.AllowListImport ||
(this.AllowListImport != null &&
this.AllowListImport.Equals(input.AllowListImport))
) &&
(
this.AllowTrackingEmails == input.AllowTrackingEmails ||
(this.AllowTrackingEmails != null &&
this.AllowTrackingEmails.Equals(input.AllowTrackingEmails))
) &&
(
this.CustomerTiers == input.CustomerTiers ||
this.CustomerTiers != null &&
this.CustomerTiers.SequenceEqual(input.CustomerTiers)
) &&
(
this.InitialSendingLimits == input.InitialSendingLimits ||
(this.InitialSendingLimits != null &&
this.InitialSendingLimits.Equals(input.InitialSendingLimits))
) &&
(
this.PlanCustomers == input.PlanCustomers ||
(this.PlanCustomers != null &&
this.PlanCustomers.Equals(input.PlanCustomers))
) &&
(
this.PlanEmails == input.PlanEmails ||
(this.PlanEmails != null &&
this.PlanEmails.Equals(input.PlanEmails))
) &&
(
this.PlanName == input.PlanName ||
(this.PlanName != null &&
this.PlanName.Equals(input.PlanName))
) &&
(
this.PlanNameFormatted == input.PlanNameFormatted ||
(this.PlanNameFormatted != null &&
this.PlanNameFormatted.Equals(input.PlanNameFormatted))
) &&
(
this.RequireOrderWithinLastDays == input.RequireOrderWithinLastDays ||
(this.RequireOrderWithinLastDays != null &&
this.RequireOrderWithinLastDays.Equals(input.RequireOrderWithinLastDays))
) &&
(
this.RevenuePercent == input.RevenuePercent ||
(this.RevenuePercent != null &&
this.RevenuePercent.Equals(input.RevenuePercent))
) &&
(
this.SpamPercentLimit == input.SpamPercentLimit ||
(this.SpamPercentLimit != null &&
this.SpamPercentLimit.Equals(input.SpamPercentLimit))
) &&
(
this.TotalCustomers == input.TotalCustomers ||
(this.TotalCustomers != null &&
this.TotalCustomers.Equals(input.TotalCustomers))
) &&
(
this.TotalEmails == input.TotalEmails ||
(this.TotalEmails != null &&
this.TotalEmails.Equals(input.TotalEmails))
) &&
(
this.UpgradeTo == input.UpgradeTo ||
(this.UpgradeTo != null &&
this.UpgradeTo.Equals(input.UpgradeTo))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AdditionalCustomers != null)
hashCode = hashCode * 59 + this.AdditionalCustomers.GetHashCode();
if (this.AdditionalEmails != null)
hashCode = hashCode * 59 + this.AdditionalEmails.GetHashCode();
if (this.AdditionalFee != null)
hashCode = hashCode * 59 + this.AdditionalFee.GetHashCode();
if (this.AllowListImport != null)
hashCode = hashCode * 59 + this.AllowListImport.GetHashCode();
if (this.AllowTrackingEmails != null)
hashCode = hashCode * 59 + this.AllowTrackingEmails.GetHashCode();
if (this.CustomerTiers != null)
hashCode = hashCode * 59 + this.CustomerTiers.GetHashCode();
if (this.InitialSendingLimits != null)
hashCode = hashCode * 59 + this.InitialSendingLimits.GetHashCode();
if (this.PlanCustomers != null)
hashCode = hashCode * 59 + this.PlanCustomers.GetHashCode();
if (this.PlanEmails != null)
hashCode = hashCode * 59 + this.PlanEmails.GetHashCode();
if (this.PlanName != null)
hashCode = hashCode * 59 + this.PlanName.GetHashCode();
if (this.PlanNameFormatted != null)
hashCode = hashCode * 59 + this.PlanNameFormatted.GetHashCode();
if (this.RequireOrderWithinLastDays != null)
hashCode = hashCode * 59 + this.RequireOrderWithinLastDays.GetHashCode();
if (this.RevenuePercent != null)
hashCode = hashCode * 59 + this.RevenuePercent.GetHashCode();
if (this.SpamPercentLimit != null)
hashCode = hashCode * 59 + this.SpamPercentLimit.GetHashCode();
if (this.TotalCustomers != null)
hashCode = hashCode * 59 + this.TotalCustomers.GetHashCode();
if (this.TotalEmails != null)
hashCode = hashCode * 59 + this.TotalEmails.GetHashCode();
if (this.UpgradeTo != null)
hashCode = hashCode * 59 + this.UpgradeTo.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// .Text WebLog
//
// .Text is an open source weblog system started by Scott Watermasysk.
// Blog: http://ScottWater.com/blog
// RSS: http://scottwater.com/blog/rss.aspx
// Email: [email protected]
//
// For updated news and information please visit http://scottwater.com/dottext and subscribe to
// the Rss feed @ http://scottwater.com/dottext/rss.aspx
//
// On its release (on or about August 1, 2003) this application is licensed under the BSD. However, I reserve the
// right to change or modify this at any time. The most recent and up to date license can always be fount at:
// http://ScottWater.com/License.txt
//
// Please direct all code related questions to:
// GotDotNet Workspace: http://www.gotdotnet.com/Community/Workspaces/workspace.aspx?id=e99fccb3-1a8c-42b5-90ee-348f6b77c407
// Yahoo Group http://groups.yahoo.com/group/DotText/
//
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections;
using System.IO;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Serialization;
using Dottext.Framework;
using Dottext.Framework.Components;
namespace Dottext.Web.Admin
{
public class OpmlProvider
{
protected OpmlProvider()
{
//
}
public static XmlDocument Export(LinkCollection items)
{
#region DEP: writer
// StringWriter sw = new StringWriter();
//
// XmlWriter writer = new XmlTextWriter(sw);
//
// writer.WriteStartDocument();
//// writer.WriteAttributeString("encoding", "utf-8");
//
// writer.WriteStartElement("opml");
// writer.WriteElementString("head", String.Empty);
// writer.WriteStartElement("body");
//
//// foreach (OpmlItem currentItem in items)
//// {
//// WriteOpmlItem(currentItem, writer);
//// }
//
// foreach (Link currentItem in items)
// {
// writer.WriteStartElement("outline");
// writer.WriteAttributeString("title", currentItem.Title);
// writer.WriteAttributeString("description", currentItem.Title);
// writer.WriteAttributeString("htmlurl", currentItem.Url);
// writer.WriteAttributeString("xmlurl", currentItem.Rss);
// writer.WriteEndElement();
// }
//
// writer.WriteEndElement(); // body
// writer.WriteEndElement(); // opml
// writer.WriteEndDocument();
//
// writer.Close();
#endregion
XmlDocument doc = new XmlDocument();
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(declaration);
XmlNode rootNode = doc.CreateElement("opml");
doc.AppendChild(rootNode);
XmlNode headNode = doc.CreateElement("head");
rootNode.AppendChild(headNode);
XmlNode bodyNode = doc.CreateElement("body");
rootNode.AppendChild(bodyNode);
foreach (Link currentItem in items)
{
XmlNode outline = doc.CreateElement("outline");
XmlAttribute title = doc.CreateAttribute("title");
title.Value = currentItem.Title;
outline.Attributes.Append(title);
XmlAttribute description = doc.CreateAttribute("description");
description.Value = currentItem.Title;
outline.Attributes.Append(description);
XmlAttribute htmlurl = doc.CreateAttribute("htmlurl");
htmlurl.Value = currentItem.Url;
outline.Attributes.Append(htmlurl);
XmlAttribute xmlurl = doc.CreateAttribute("xmlurl");
xmlurl.Value = currentItem.Rss;
outline.Attributes.Append(xmlurl);
bodyNode.AppendChild(outline);
}
return doc;
//doc.LoadXml(sw.ToString());
//return doc.CreateNavigator();
}
public static void WriteOpmlItem(OpmlItem item, XmlWriter writer)
{
item.RenderOpml(writer);
foreach (OpmlItem childItem in item.ChildItems)
WriteOpmlItem(childItem, writer);
}
public static OpmlItemCollection Import(Stream fileStream)
{
OpmlItemCollection _currentBatch = new OpmlItemCollection();
XmlReader reader = new XmlTextReader(fileStream);
XPathDocument doc = new XPathDocument(reader);
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator outlineItems = nav.Select("/opml/body/outline");
while (outlineItems.MoveNext())
{
_currentBatch.AddRange(DeserializeItem(outlineItems.Current));
}
return _currentBatch;
}
public static OpmlItem[] DeserializeItem(XPathNavigator nav)
{
ArrayList items = new ArrayList();
if (nav.HasAttributes)
{
string title = nav.GetAttribute("title", "");
if (String.Empty == title)
title = nav.GetAttribute("text", "");
string description = nav.GetAttribute("description", "");
string htmlUrl = nav.GetAttribute("htmlurl", "");
if (String.Empty == htmlUrl)
htmlUrl = nav.GetAttribute("htmlUrl", "");
string xmlUrl = nav.GetAttribute("xmlurl", "");
if (String.Empty == xmlUrl)
xmlUrl = nav.GetAttribute("xmlUrl", "");
OpmlItem currentItem = null;
if (String.Empty != title && String.Empty != htmlUrl)
currentItem = new OpmlItem(title, description, xmlUrl, htmlUrl);
if (null != currentItem)
items.Add(currentItem);
}
if (nav.HasChildren)
{
XPathNodeIterator childItems = nav.SelectChildren("outline", "");
while (childItems.MoveNext())
{
OpmlItem[] children = DeserializeItem(childItems.Current);
if (null != children)
items.InsertRange(items.Count, children);
}
}
OpmlItem[] result = new OpmlItem[items.Count];
items.CopyTo(result);
return result;
}
}
[
Serializable,
XmlRoot(ElementName = "outline", IsNullable=true)
]
public class OpmlItem
{
private string _title;
private string _description;
private string _xmlurl;
private string _htmlurl;
private OpmlItemCollection _childItems;
public OpmlItem()
{
_childItems = new OpmlItemCollection(0);
}
public OpmlItem(string title, string description, string xmlUrl, string htmlUrl)
: this()
{
_title = title;
_description = description;
_xmlurl = xmlUrl;
_htmlurl = htmlUrl;
}
[XmlAttribute("title")]
public string Title
{
get { return _title; }
set { _title = value; }
}
[XmlAttribute("description")]
public string Description
{
get { return _description; }
set { _description = value; }
}
[XmlAttribute("xmlurl")]
public string XmlUrl
{
get { return _xmlurl; }
set { _xmlurl = value; }
}
[XmlAttribute("htmlurl")]
public string HtmlUrl
{
get { return _htmlurl; }
set { _htmlurl = value; }
}
public OpmlItemCollection ChildItems
{
get { return _childItems; }
set { _childItems = value; }
}
internal void RenderOpml(XmlWriter writer)
{
writer.WriteStartElement("outline");
writer.WriteAttributeString("title", this.Title);
writer.WriteAttributeString("description", this.Description);
writer.WriteAttributeString("htmlurl", this.HtmlUrl);
writer.WriteAttributeString("xmlurl", this.XmlUrl);
writer.WriteEndElement();
}
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, 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.
//
using System;
using NLog.Common;
using NLog.Config;
using NLog.Targets;
using NLog.Targets.Wrappers;
using NLog.UnitTests.Common;
using NLog.UnitTests.Targets.Wrappers;
namespace NLog.UnitTests.LayoutRenderers
{
using System.Security.Principal;
using System.Threading;
using Xunit;
public class IdentityTests : NLogTestBase
{
#if MONO
[Fact(Skip = "MONO on Travis not supporting WindowsIdentity")]
#else
[Fact]
#endif
public void WindowsIdentityTest()
{
var userDomainName = Environment.GetEnvironmentVariable("USERDOMAIN") ?? string.Empty;
var userName = Environment.GetEnvironmentVariable("USERNAME") ?? string.Empty;
if (!string.IsNullOrEmpty(userDomainName))
userName = userDomainName + "\\" + userName;
AssertLayoutRendererOutput("${windows-identity}", userName);
}
[Fact]
public void IdentityTest1()
{
var oldPrincipal = Thread.CurrentPrincipal;
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("SOMEDOMAIN\\SomeUser", "CustomAuth"), new[] { "Role1", "Role2" });
try
{
AssertLayoutRendererOutput("${identity}", "auth:CustomAuth:SOMEDOMAIN\\SomeUser");
AssertLayoutRendererOutput("${identity:authtype=false}", "auth:SOMEDOMAIN\\SomeUser");
AssertLayoutRendererOutput("${identity:authtype=false:isauthenticated=false}", "SOMEDOMAIN\\SomeUser");
AssertLayoutRendererOutput("${identity:fsnormalize=true}", "auth_CustomAuth_SOMEDOMAIN_SomeUser");
}
finally
{
Thread.CurrentPrincipal = oldPrincipal;
}
}
/// <summary>
/// Test writing ${identity} async
/// </summary>
[Fact]
public void IdentityTest1Async()
{
var oldPrincipal = Thread.CurrentPrincipal;
try
{
ConfigurationItemFactory.Default.Targets
.RegisterDefinition("CSharpEventTarget", typeof(CSharpEventTarget));
LogManager.Configuration = CreateConfigurationFromString(@"<?xml version='1.0' encoding='utf-8' ?>
<nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
internalLogLevel='Debug'
throwExceptions='true' >
<targets async='true'>
<target name='target1' xsi:type='CSharpEventTarget' layout='${identity}' />
</targets>
<rules>
<logger name='*' writeTo='target1' />
</rules>
</nlog>
");
try
{
var continuationHit = new ManualResetEvent(false);
string rendered = null;
var threadId = Thread.CurrentThread.ManagedThreadId;
var asyncThreadId = threadId;
LogEventInfo lastLogEvent = null;
var asyncTarget = LogManager.Configuration.FindTargetByName<AsyncTargetWrapper>("target1");
Assert.NotNull(asyncTarget);
var target = asyncTarget.WrappedTarget as CSharpEventTarget;
Assert.NotNull(target);
target.BeforeWrite += (logevent, rendered1, asyncThreadId1) =>
{
//clear in current thread before write
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("ANOTHER user", "type"), null);
};
target.EventWritten += (logevent, rendered1, asyncThreadId1) =>
{
rendered = rendered1;
asyncThreadId = asyncThreadId1;
lastLogEvent = logevent;
continuationHit.Set();
};
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("SOMEDOMAIN\\SomeUser", "CustomAuth"), new[] { "Role1", "Role2" });
var logger = LogManager.GetCurrentClassLogger();
logger.Debug("test write");
Assert.True(continuationHit.WaitOne());
Assert.NotNull(lastLogEvent);
//should be written in another thread.
Assert.NotEqual(threadId, asyncThreadId);
Assert.Equal("auth:CustomAuth:SOMEDOMAIN\\SomeUser", rendered);
}
finally
{
LogManager.Configuration.Close();
}
}
finally
{
InternalLogger.Reset();
Thread.CurrentPrincipal = oldPrincipal;
}
}
[Fact]
public void IdentityTest2()
{
var oldPrincipal = Thread.CurrentPrincipal;
Thread.CurrentPrincipal = new GenericPrincipal(new NotAuthenticatedIdentity(), new[] { "role1" });
try
{
AssertLayoutRendererOutput("${identity}", "notauth::");
}
finally
{
Thread.CurrentPrincipal = oldPrincipal;
}
}
/// <summary>
/// Mock object for IsAuthenticated property.
/// </summary>
private class NotAuthenticatedIdentity : GenericIdentity
{
public NotAuthenticatedIdentity()
: base("")
{
}
#region Overrides of GenericIdentity
/// <summary>
/// Gets a value indicating whether the user has been authenticated.
/// </summary>
/// <returns>
/// true if the user was has been authenticated; otherwise, false.
/// </returns>
public override bool IsAuthenticated => false;
#endregion
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MinInt32()
{
var test = new SimpleBinaryOpTest__MinInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MinInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int32> _fld1;
public Vector256<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MinInt32 testClass)
{
var result = Avx2.Min(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinInt32 testClass)
{
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx2.Min(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MinInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
}
public SimpleBinaryOpTest__MinInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Min(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Min(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Min(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Min(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int32>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Min(
Avx.LoadVector256((Int32*)(pClsVar1)),
Avx.LoadVector256((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx2.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MinInt32();
var result = Avx2.Min(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__MinInt32();
fixed (Vector256<Int32>* pFld1 = &test._fld1)
fixed (Vector256<Int32>* pFld2 = &test._fld2)
{
var result = Avx2.Min(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Min(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int32>* pFld1 = &_fld1)
fixed (Vector256<Int32>* pFld2 = &_fld2)
{
var result = Avx2.Min(
Avx.LoadVector256((Int32*)(pFld1)),
Avx.LoadVector256((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Min(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Min(
Avx.LoadVector256((Int32*)(&test._fld1)),
Avx.LoadVector256((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int32> op1, Vector256<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != Math.Min(left[0], right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != Math.Min(left[i], right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Min)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************
namespace NUnit.Core
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
/// <summary>
/// Test Class.
/// </summary>
public abstract class Test : ITest, IComparable
{
#region Fields
/// <summary>
/// TestName that identifies this test
/// </summary>
private TestName testName;
/// <summary>
/// Indicates whether the test should be executed
/// </summary>
private RunState runState;
/// <summary>
/// The reason for not running the test
/// </summary>
private string ignoreReason;
/// <summary>
/// Description for this test
/// </summary>
private string description;
/// <summary>
/// Test suite containing this test, or null
/// </summary>
private Test parent;
/// <summary>
/// List of categories applying to this test
/// </summary>
private IList categories;
/// <summary>
/// A dictionary of properties, used to add information
/// to tests without requiring the class to change.
/// </summary>
private IDictionary properties;
/// <summary>
/// The System.Type of the fixture for this test suite, if there is one
/// </summary>
private Type fixtureType;
/// <summary>
/// The fixture object, if it has been created
/// </summary>
private object fixture;
#endregion
#region Construction
/// <summary>
/// Constructs a test given its name
/// </summary>
/// <param name="name">The name of the test</param>
protected Test( string name )
{
this.testName = new TestName();
this.testName.FullName = name;
this.testName.Name = name;
this.testName.TestID = new TestID();
this.runState = RunState.Runnable;
}
/// <summary>
/// Constructs a test given the path through the
/// test hierarchy to its parent and a name.
/// </summary>
/// <param name="pathName">The parent tests full name</param>
/// <param name="name">The name of the test</param>
protected Test( string pathName, string name )
{
this.testName = new TestName();
this.testName.FullName = pathName == null || pathName == string.Empty
? name : pathName + "." + name;
this.testName.Name = name;
this.testName.TestID = new TestID();
this.runState = RunState.Runnable;
}
/// <summary>
/// Constructs a test given a TestName object
/// </summary>
/// <param name="testName">The TestName for this test</param>
protected Test( TestName testName )
{
this.testName = testName;
this.runState = RunState.Runnable;
}
/// <summary>
/// Constructs a test given a fixture type
/// </summary>
/// <param name="fixtureType">The type to use in constructiong the test</param>
protected Test( Type fixtureType )
{
this.testName = new TestName();
this.testName.FullName = fixtureType.FullName;
this.testName.Name = fixtureType.Namespace != null
? TestName.FullName.Substring( TestName.FullName.LastIndexOf( '.' ) + 1 )
: fixtureType.FullName;
this.testName.TestID = new TestID();
this.fixtureType = fixtureType;
this.RunState = RunState.Runnable;
}
/// <summary>
/// Construct a test given a MethodInfo
/// </summary>
/// <param name="method">The method to be used</param>
protected Test( MethodInfo method )
: this( method.ReflectedType )
{
this.testName.Name = method.DeclaringType == method.ReflectedType
? method.Name : method.DeclaringType.Name + "." + method.Name;
this.testName.FullName = method.ReflectedType.FullName + "." + method.Name;
}
/// <summary>
/// Sets the runner id of a test and optionally its children
/// </summary>
/// <param name="runnerID">The runner id to be used</param>
/// <param name="recursive">True if all children should get the same id</param>
public void SetRunnerID( int runnerID, bool recursive )
{
this.testName.RunnerID = runnerID;
if ( recursive && this.Tests != null )
foreach( Test child in this.Tests )
child.SetRunnerID( runnerID, true );
}
#endregion
#region ITest Members
#region Properties
/// <summary>
/// Gets the TestName of the test
/// </summary>
public TestName TestName
{
get { return testName; }
}
/// <summary>
/// Gets a string representing the kind of test
/// that this object represents, for use in display.
/// </summary>
public abstract string TestType { get; }
/// <summary>
/// Whether or not the test should be run
/// </summary>
public RunState RunState
{
get { return runState; }
set { runState = value; }
}
/// <summary>
/// Reason for not running the test, if applicable
/// </summary>
public string IgnoreReason
{
get { return ignoreReason; }
set { ignoreReason = value; }
}
/// <summary>
/// Gets a count of test cases represented by
/// or contained under this test.
/// </summary>
public virtual int TestCount
{
get { return 1; }
}
/// <summary>
/// Gets a list of categories associated with this test.
/// </summary>
public IList Categories
{
get { return categories; }
set { categories = value; }
}
/// <summary>
/// Gets a desctiption associated with this test.
/// </summary>
public String Description
{
get { return description; }
set { description = value; }
}
/// <summary>
/// Gets the property dictionary for this test
/// </summary>
public IDictionary Properties
{
get
{
if ( properties == null )
properties = new ListDictionary();
return properties;
}
set
{
properties = value;
}
}
/// <summary>
/// Indicates whether this test is a suite
/// </summary>
public abstract bool IsSuite { get; }
/// <summary>
/// Gets the parent test of this test
/// </summary>
ITest ITest.Parent
{
get { return parent; }
}
/// <summary>
/// Gets the parent as a Test object.
/// Used by the core to set the parent.
/// </summary>
public Test Parent
{
get { return parent; }
set { parent = value; }
}
/// <summary>
/// Gets this test's child tests
/// </summary>
public abstract IList Tests { get; }
/// <summary>
/// Gets the Type of the fixture used in running this test
/// </summary>
public Type FixtureType
{
get { return fixtureType; }
}
/// <summary>
/// Gets or sets a fixture object for running this test
/// </summary>
public object Fixture
{
get { return fixture; }
set { fixture = value; }
}
#endregion
#region Methods
/// <summary>
/// Gets a count of test cases that would be run using
/// the specified filter.
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public abstract int CountTestCases(ITestFilter filter);
#endregion
#endregion
#region Abstract Run Methods
/// <summary>
/// Runs the test, sending notifications to a listener.
/// </summary>
/// <param name="listener">An event listener to receive notifications</param>
/// <returns>A TestResult</returns>
public abstract TestResult Run(EventListener listener);
/// <summary>
/// Runs the test under a particular filter, sending
/// notifications to a listener.
/// </summary>
/// <param name="listener">An event listener to receive notifications</param>
/// <param name="filter">A filter used in running the test</param>
/// <returns></returns>
public abstract TestResult Run(EventListener listener, ITestFilter filter);
#endregion
#region IComparable Members
/// <summary>
/// Compares this test to another test for sorting purposes
/// </summary>
/// <param name="obj">The other test</param>
/// <returns>Value of -1, 0 or +1 depending on whether the current test is less than, equal to or greater than the other test</returns>
public int CompareTo(object obj)
{
Test other = obj as Test;
if ( other == null )
return -1;
return this.TestName.FullName.CompareTo( other.TestName.FullName );
}
#endregion
}
}
| |
/*
* 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.Reflection;
using System.Threading;
using System.Xml;
using log4net;
using Nini.Config;
using OpenSim.Framework;
namespace OpenSim
{
/// <summary>
/// Loads the Configuration files into nIni
/// </summary>
public class ConfigurationLoader
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Various Config settings the region needs to start
/// Physics Engine, Mesh Engine, GridMode, PhysicsPrim allowed, Neighbor,
/// StorageDLL, Storage Connection String, Estate connection String, Client Stack
/// Standalone settings.
/// </summary>
protected ConfigSettings m_configSettings;
/// <summary>
/// A source of Configuration data
/// </summary>
protected OpenSimConfigSource m_config;
/// <summary>
/// Grid Service Information. This refers to classes and addresses of the grid service
/// </summary>
protected NetworkServersInfo m_networkServersInfo;
/// <summary>
/// Loads the region configuration
/// </summary>
/// <param name="argvSource">Parameters passed into the process when started</param>
/// <param name="configSettings"></param>
/// <param name="networkInfo"></param>
/// <returns>A configuration that gets passed to modules</returns>
public OpenSimConfigSource LoadConfigSettings(
IConfigSource argvSource, EnvConfigSource envConfigSource, out ConfigSettings configSettings,
out NetworkServersInfo networkInfo)
{
m_configSettings = configSettings = new ConfigSettings();
m_networkServersInfo = networkInfo = new NetworkServersInfo();
bool iniFileExists = false;
IConfig startupConfig = argvSource.Configs["Startup"];
List<string> sources = new List<string>();
string masterFileName = startupConfig.GetString("inimaster", "OpenSimDefaults.ini");
if (masterFileName == "none")
masterFileName = String.Empty;
if (IsUri(masterFileName))
{
if (!sources.Contains(masterFileName))
sources.Add(masterFileName);
}
else
{
string masterFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), masterFileName));
if (masterFileName != String.Empty)
{
if (File.Exists(masterFilePath))
{
if (!sources.Contains(masterFilePath))
sources.Add(masterFilePath);
}
else
{
m_log.ErrorFormat("Master ini file {0} not found", Path.GetFullPath(masterFilePath));
Environment.Exit(1);
}
}
}
string iniFileName = startupConfig.GetString("inifile", "OpenSim.ini");
if (IsUri(iniFileName))
{
if (!sources.Contains(iniFileName))
sources.Add(iniFileName);
Application.iniFilePath = iniFileName;
}
else
{
Application.iniFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), iniFileName));
if (!File.Exists(Application.iniFilePath))
{
iniFileName = "OpenSim.xml";
Application.iniFilePath = Path.GetFullPath(Path.Combine(Util.configDir(), iniFileName));
}
if (File.Exists(Application.iniFilePath))
{
if (!sources.Contains(Application.iniFilePath))
sources.Add(Application.iniFilePath);
}
}
m_config = new OpenSimConfigSource();
m_config.Source = new IniConfigSource();
m_config.Source.Merge(DefaultConfig());
m_log.Info("[CONFIG]: Reading configuration settings");
for (int i = 0 ; i < sources.Count ; i++)
{
if (ReadConfig(m_config, sources[i]))
{
iniFileExists = true;
AddIncludes(m_config, sources);
}
}
// Override distro settings with contents of inidirectory
string iniDirName = startupConfig.GetString("inidirectory", "config");
string iniDirPath = Path.Combine(Util.configDir(), iniDirName);
if (Directory.Exists(iniDirPath))
{
m_log.InfoFormat("[CONFIG]: Searching folder {0} for config ini files", iniDirPath);
List<string> overrideSources = new List<string>();
string[] fileEntries = Directory.GetFiles(iniDirName);
foreach (string filePath in fileEntries)
{
if (Path.GetExtension(filePath).ToLower() == ".ini")
{
if (!sources.Contains(Path.GetFullPath(filePath)))
{
overrideSources.Add(Path.GetFullPath(filePath));
// put it in sources too, to avoid circularity
sources.Add(Path.GetFullPath(filePath));
}
}
}
if (overrideSources.Count > 0)
{
OpenSimConfigSource overrideConfig = new OpenSimConfigSource();
overrideConfig.Source = new IniConfigSource();
for (int i = 0 ; i < overrideSources.Count ; i++)
{
if (ReadConfig(overrideConfig, overrideSources[i]))
{
iniFileExists = true;
AddIncludes(overrideConfig, overrideSources);
}
}
m_config.Source.Merge(overrideConfig.Source);
}
}
if (sources.Count == 0)
{
m_log.FatalFormat("[CONFIG]: Could not load any configuration");
Environment.Exit(1);
}
else if (!iniFileExists)
{
m_log.FatalFormat("[CONFIG]: Could not load any configuration");
m_log.FatalFormat("[CONFIG]: Configuration exists, but there was an error loading it!");
Environment.Exit(1);
}
// Merge OpSys env vars
m_log.Info("[CONFIG]: Loading environment variables for Config");
Util.MergeEnvironmentToConfig(m_config.Source);
// Make sure command line options take precedence
m_config.Source.Merge(argvSource);
m_config.Source.ReplaceKeyValues();
ReadConfigSettings();
return m_config;
}
/// <summary>
/// Adds the included files as ini configuration files
/// </summary>
/// <param name="sources">List of URL strings or filename strings</param>
private void AddIncludes(OpenSimConfigSource configSource, List<string> sources)
{
//loop over config sources
foreach (IConfig config in configSource.Source.Configs)
{
// Look for Include-* in the key name
string[] keys = config.GetKeys();
foreach (string k in keys)
{
if (k.StartsWith("Include-"))
{
// read the config file to be included.
string file = config.GetString(k);
if (IsUri(file))
{
if (!sources.Contains(file))
sources.Add(file);
}
else
{
string basepath = Path.GetFullPath(Util.configDir());
// Resolve relative paths with wildcards
string chunkWithoutWildcards = file;
string chunkWithWildcards = string.Empty;
int wildcardIndex = file.IndexOfAny(new char[] { '*', '?' });
if (wildcardIndex != -1)
{
chunkWithoutWildcards = file.Substring(0, wildcardIndex);
chunkWithWildcards = file.Substring(wildcardIndex);
}
string path = Path.Combine(basepath, chunkWithoutWildcards);
path = Path.GetFullPath(path) + chunkWithWildcards;
string[] paths = Util.Glob(path);
// If the include path contains no wildcards, then warn the user that it wasn't found.
if (wildcardIndex == -1 && paths.Length == 0)
{
m_log.WarnFormat("[CONFIG]: Could not find include file {0}", path);
}
else
{
foreach (string p in paths)
{
if (!sources.Contains(p))
sources.Add(p);
}
}
}
}
}
}
}
/// <summary>
/// Check if we can convert the string to a URI
/// </summary>
/// <param name="file">String uri to the remote resource</param>
/// <returns>true if we can convert the string to a Uri object</returns>
bool IsUri(string file)
{
Uri configUri;
return Uri.TryCreate(file, UriKind.Absolute,
out configUri) && configUri.Scheme == Uri.UriSchemeHttp;
}
/// <summary>
/// Provide same ini loader functionality for standard ini and master ini - file system or XML over http
/// </summary>
/// <param name="iniPath">Full path to the ini</param>
/// <returns></returns>
private bool ReadConfig(OpenSimConfigSource configSource, string iniPath)
{
bool success = false;
if (!IsUri(iniPath))
{
m_log.InfoFormat("[CONFIG]: Reading configuration file {0}", Path.GetFullPath(iniPath));
configSource.Source.Merge(new IniConfigSource(iniPath));
success = true;
}
else
{
m_log.InfoFormat("[CONFIG]: {0} is a http:// URI, fetching ...", iniPath);
// The ini file path is a http URI
// Try to read it
try
{
XmlReader r = XmlReader.Create(iniPath);
XmlConfigSource cs = new XmlConfigSource(r);
configSource.Source.Merge(cs);
success = true;
}
catch (Exception e)
{
m_log.FatalFormat("[CONFIG]: Exception reading config from URI {0}\n" + e.ToString(), iniPath);
Environment.Exit(1);
}
}
return success;
}
/// <summary>
/// Setup a default config values in case they aren't present in the ini file
/// </summary>
/// <returns>A Configuration source containing the default configuration</returns>
private static IConfigSource DefaultConfig()
{
IConfigSource defaultConfig = new IniConfigSource();
{
IConfig config = defaultConfig.Configs["Startup"];
if (null == config)
config = defaultConfig.AddConfig("Startup");
config.Set("region_info_source", "filesystem");
config.Set("physics", "OpenDynamicsEngine");
config.Set("meshing", "Meshmerizer");
config.Set("physical_prim", true);
config.Set("serverside_object_permissions", true);
config.Set("storage_prim_inventories", true);
config.Set("startup_console_commands_file", String.Empty);
config.Set("shutdown_console_commands_file", String.Empty);
config.Set("DefaultScriptEngine", "XEngine");
config.Set("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
// life doesn't really work without this
config.Set("EventQueue", true);
}
{
IConfig config = defaultConfig.Configs["Network"];
if (null == config)
config = defaultConfig.AddConfig("Network");
config.Set("http_listener_port", ConfigSettings.DefaultRegionHttpPort);
}
return defaultConfig;
}
/// <summary>
/// Read initial region settings from the ConfigSource
/// </summary>
protected virtual void ReadConfigSettings()
{
IConfig startupConfig = m_config.Source.Configs["Startup"];
if (startupConfig != null)
{
m_configSettings.PhysicsEngine = startupConfig.GetString("physics");
m_configSettings.MeshEngineName = startupConfig.GetString("meshing");
m_configSettings.ClientstackDll
= startupConfig.GetString("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
}
m_networkServersInfo.loadFromConfiguration(m_config.Source);
}
}
}
| |
// 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.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using Microsoft.Build.BuildEngine.Shared;
using Microsoft.Win32;
namespace Microsoft.Build.BuildEngine
{
internal class VCWrapperProject
{
/// <summary>
/// Add a target for a VC project file into the XML doc that's being generated.
/// This is used only when building standalone VC projects
/// </summary>
/// <param name="msbuildProject"></param>
/// <param name="projectPath"></param>
/// <param name="targetName"></param>
/// <param name="subTargetName"></param>
/// <owner>RGoel</owner>
static private void AddVCBuildTarget
(
Project msbuildProject,
string projectPath,
string targetName,
string subTargetName
)
{
Target newTarget = msbuildProject.Targets.AddNewTarget(targetName);
if (subTargetName == "Publish")
{
// Well, hmmm. The VCBuild doesn't support any kind of
// a "Publish" operation. The best we can really do is offer up a
// message saying so.
SolutionWrapperProject.AddErrorWarningMessageElement(newTarget, XMakeElements.error, true, "SolutionVCProjectNoPublish");
}
else
{
SolutionWrapperProject.AddErrorWarningMessageElement(newTarget, XMakeElements.warning, true, "StandaloneVCProjectP2PRefsBroken");
string projectFullPath = Path.GetFullPath(projectPath);
AddVCBuildTaskElement(msbuildProject, newTarget, "$(VCBuildSolutionFile)", projectFullPath, subTargetName, "$(PlatformName)", "$(ConfigurationName)");
}
}
/// <summary>
/// Adds a new VCBuild task element to the specified target
/// </summary>
/// <param name="target">The target to add the VCBuild task to</param>
/// <param name="solutionPath">Path to the solution if any</param>
/// <param name="projectPath">Path to the solution if any</param>
/// <param name="vcbuildTargetName">The VCBuild target name</param>
/// <param name="platformName">The platform parameter to VCBuild</param>
/// <param name="fullConfigurationName">Configuration property value</param>
/// <returns></returns>
static internal BuildTask AddVCBuildTaskElement
(
Project msbuildProject,
Target target,
string solutionPath,
string projectPath,
string vcbuildTargetName,
string platformName,
string fullConfigurationName
)
{
// The VCBuild task (which we already shipped) has a bug - it cannot
// find vcbuild.exe when running in MSBuild 64 bit unless it's on the path.
// So, pass it here, unless some explicit path was passed.
// Note, we have to do this even if we're in a 32 bit MSBuild, because we save the .sln.cache
// file, and the next build of the solution could be a 64 bit MSBuild.
if (VCBuildLocationHint != null) // Should only be null if vcbuild truly isn't installed; in that case, let the task log its error
{
BuildTask createProperty = target.AddNewTask("CreateProperty");
createProperty.SetParameterValue("Value", VCBuildLocationHint);
createProperty.Condition = "'$(VCBuildToolPath)' == ''";
createProperty.AddOutputProperty("Value", "VCBuildToolPath");
}
BuildTask newTask = target.AddNewTask("VCBuild");
newTask.SetParameterValue("Projects", projectPath, true /* treat as literal */);
// Add the toolpath so that the user can override if necessary
newTask.SetParameterValue("ToolPath", "$(VCBuildToolPath)");
newTask.SetParameterValue("Configuration", fullConfigurationName);
if (!string.IsNullOrEmpty(platformName))
{
newTask.SetParameterValue("Platform", platformName);
}
newTask.SetParameterValue("SolutionFile", solutionPath);
if ((vcbuildTargetName != null) && (vcbuildTargetName.Length > 0))
{
newTask.SetParameterValue(vcbuildTargetName, "true");
}
// Add the override switch so that the user can supply one if necessary
newTask.SetParameterValue("Override", "$(VCBuildOverride)");
// Add any additional lib paths
newTask.SetParameterValue("AdditionalLibPaths", "$(VCBuildAdditionalLibPaths)");
// Only use new properties if we're not emitting a 2.0 project
if (!String.Equals(msbuildProject.ToolsVersion, "2.0", StringComparison.OrdinalIgnoreCase))
{
// Add any additional link library paths
newTask.SetParameterValue("AdditionalLinkLibraryPaths", "$(VCBuildAdditionalLinkLibraryPaths)");
// Add the useenv switch so that the user can supply one if necessary
// Note: "VCBuildUserEnvironment" is included for backwards-compatibility; the correct
// property name is "VCBuildUseEnvironment" to match the task parameter. When the old name is
// used the task will emit a warning.
newTask.SetParameterValue("UseEnvironment", "$(VCBuildUseEnvironment)");
}
newTask.SetParameterValue("UserEnvironment", "$(VCBuildUserEnvironment)");
// Add the additional options switches
newTask.SetParameterValue("AdditionalOptions", "$(VCBuildAdditionalOptions)");
return newTask;
}
/// <summary>
/// This method generates an XmlDocument representing an MSBuild project wrapper for a VC project
/// </summary>
/// <owner>LukaszG</owner>
static internal XmlDocument GenerateVCWrapperProject(Engine parentEngine, string vcProjectFilename, string toolsVersion)
{
string projectPath = Path.GetFullPath(vcProjectFilename);
Project msbuildProject = null;
try
{
msbuildProject = new Project(parentEngine, toolsVersion);
}
catch (InvalidOperationException)
{
BuildEventFileInfo fileInfo = new BuildEventFileInfo(projectPath);
string errorCode;
string helpKeyword;
string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "UnrecognizedToolsVersion", toolsVersion);
throw new InvalidProjectFileException(projectPath, fileInfo.Line, fileInfo.Column, fileInfo.EndLine, fileInfo.EndColumn, message, null, errorCode, helpKeyword);
}
msbuildProject.IsLoadedByHost = false;
msbuildProject.DefaultTargets = "Build";
string wrapperProjectToolsVersion = SolutionWrapperProject.DetermineWrapperProjectToolsVersion(toolsVersion);
msbuildProject.DefaultToolsVersion = wrapperProjectToolsVersion;
BuildPropertyGroup propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
propertyGroup.Condition = " ('$(Configuration)' != '') and ('$(Platform)' == '') ";
propertyGroup.AddNewProperty("ConfigurationName", "$(Configuration)");
propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
propertyGroup.Condition = " ('$(Configuration)' != '') and ('$(Platform)' != '') ";
propertyGroup.AddNewProperty("ConfigurationName", "$(Configuration)|$(Platform)");
// only use PlatformName if we only have the platform part
propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */);
propertyGroup.Condition = " ('$(Configuration)' == '') and ('$(Platform)' != '') ";
propertyGroup.AddNewProperty("PlatformName", "$(Platform)");
AddVCBuildTarget(msbuildProject, projectPath, "Build", null);
AddVCBuildTarget(msbuildProject, projectPath, "Clean", "Clean");
AddVCBuildTarget(msbuildProject, projectPath, "Rebuild", "Rebuild");
AddVCBuildTarget(msbuildProject, projectPath, "Publish", "Publish");
// Special environment variable to allow people to see the in-memory MSBuild project generated
// to represent the VC project.
if (Environment.GetEnvironmentVariable("MSBuildEmitSolution") != null)
{
msbuildProject.Save(vcProjectFilename + ".proj");
}
return msbuildProject.XmlDocument;
}
/// <summary>
/// Hint to give the VCBuild task to help it find vcbuild.exe.
/// </summary>
static private string path;
/// <summary>
/// Hint to give the VCBuild task to help it find vcbuild.exe.
/// Directory in which vcbuild.exe is found.
/// </summary>
static internal string VCBuildLocationHint
{
get
{
if (path == null)
{
path = GenerateFullPathToTool(RegistryView.Default);
if (path == null && Environment.Is64BitProcess)
{
path = GenerateFullPathToTool(RegistryView.Registry32);
}
if (path != null)
{
path = Path.GetDirectoryName(path);
}
}
return path;
}
}
// The code below is mostly copied from the VCBuild task that we shipped in 3.5.
// It is the logic it uses to find vcbuild.exe. That logic had a flaw -
// in 64 bit MSBuild, in a vanilla command window (like in Team Build) it would not
// find vcbuild.exe. We use the logic below to predict whether VCBuild will find it,
// and if it won't, we will pass the "hint" to use the 64 bit program files location.
/// <summary>
/// constants for VS9 Pro and above SKUs
/// </summary>
// root registry key for VS9
private const string vs9RegKey = @"SOFTWARE\Microsoft\VisualStudio\9.0";
// the name of the value containing disk install directory for the IDE components
// ("...\common7\ide" for layouts)
private const string vs9InstallDirValueName = "InstallDir";
// relative path from the above directory to vcbuild.exe on layouts
private const string vs9RelativePathToVCBuildLayouts = @"..\..\vc\vcpackages\vcbuild.exe";
// relative path from the above directory to vcbuild.exe on batch
private const string vs9RelativePathToVCBuildBatch = @"vcbuild.exe";
/// <summary>
/// constants for the VC9 Express SKU
/// </summary>
// root registry key for VC9
private const string vc9RegKey = @"SOFTWARE\Microsoft\VCExpress\9.0";
// the name of the value containing disk install directory for the IDE components
// ("...\common7\ide" for layouts)
private const string vc9InstallDirValueName = "InstallDir";
// relative path from the above directory to vcbuild.exe on layouts
private const string vc9RelativePathToVCBuildLayouts = @"..\..\vc\vcpackages\vcbuild.exe";
// relative path from the above directory to vcbuild.exe on batch
private const string vc9RelativePathToVCBuildBatch = @"vcbuild.exe";
// name of the tool
private const string vcbuildName = "vcbuild.exe";
/// <summary>
/// Determing the path to vcbuild.exe
/// </summary>
/// <returns>path to vcbuild.exe, or null if it's not found</returns>
private static string GenerateFullPathToTool(RegistryView registryView)
{
using (RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
{
// try VS9 professional and above SKUs first
string location = TryLocationFromRegistry(baseKey, vs9RegKey, vs9InstallDirValueName,
vs9RelativePathToVCBuildLayouts, vs9RelativePathToVCBuildBatch);
if (null != location)
{
return location;
}
// fall back to the VC Express SKU
location = TryLocationFromRegistry(baseKey, vc9RegKey, vc9InstallDirValueName,
vc9RelativePathToVCBuildLayouts, vc9RelativePathToVCBuildBatch);
if (null != location)
{
return location;
}
// finally, try looking in the system path
if (Microsoft.Build.BuildEngine.Shared.NativeMethods.FindOnPath(vcbuildName) == null)
{
// If SearchPath didn't find the file, it's not on the system path and we have no chance of finding it.
return null;
}
return null;
}
}
/// <summary>
/// Looks up a path from the registry if present, and checks whether VCBuild.exe is there.
/// </summary>
/// <param name="subKey">Registry key to open</param>
/// <param name="valueName">Value under that key to read</param>
/// <param name="messageToLogIfNotFound">Low-pri message to log if registry key isn't found</param>
/// <param name="relativePathFromValueOnLayout">Relative path from the key value to vcbuild.exe for layout installs</param>
/// <param name="relativePathFromValueOnBatch">Relative path from the key value to vcbuild.exe for batch installs</param>
/// <returns>Path to vcbuild.exe, or null if it's not found</returns>
/// <owner>danmose</owner>
private static string TryLocationFromRegistry(RegistryKey root, string subKeyName, string valueName,
string relativePathFromValueOnLayout, string relativePathFromValueOnBatch)
{
using (RegistryKey subKey = root.OpenSubKey(subKeyName))
{
if (subKey == null)
{
// We couldn't find an installation of the product we were looking for.
return null;
}
else
{
string rootDir = (string)subKey.GetValue(valueName);
if (rootDir != null)
{
// first try the location for layouts
string vcBuildPath = Path.Combine(rootDir, relativePathFromValueOnLayout);
if (File.Exists(vcBuildPath))
{
return vcBuildPath;
}
// if not found in layouts location, try the alternate dir if any,
// which contains vcbuild for batch installs
if (null != relativePathFromValueOnBatch)
{
vcBuildPath = Path.Combine(rootDir, relativePathFromValueOnBatch);
if (File.Exists(vcBuildPath))
{
return vcBuildPath;
}
}
}
}
// Didn't find it
return null;
}
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// CartSettingsShippingEstimate
/// </summary>
[DataContract]
public partial class CartSettingsShippingEstimate : IEquatable<CartSettingsShippingEstimate>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="CartSettingsShippingEstimate" /> class.
/// </summary>
/// <param name="allow3rdPartyBilling">True if this method allows the customer to use their own shipper account number.</param>
/// <param name="comment">Comment to display to the customer about this method.</param>
/// <param name="cost">cost.</param>
/// <param name="costBeforeDiscount">costBeforeDiscount.</param>
/// <param name="defaultMethod">True if this is the default method.</param>
/// <param name="discount">discount.</param>
/// <param name="discounted">True if this method is discounted because of a coupon.</param>
/// <param name="displayName">The name to display to the customer.</param>
/// <param name="estimatedDelivery">Date of the estimated delivery (or range).</param>
/// <param name="liftGateOption">True if a lift gate option for this method should be offered to the customer.</param>
/// <param name="name">Shipping method name.</param>
/// <param name="tax">tax.</param>
/// <param name="totalTax">totalTax.</param>
public CartSettingsShippingEstimate(bool? allow3rdPartyBilling = default(bool?), string comment = default(string), Currency cost = default(Currency), Currency costBeforeDiscount = default(Currency), bool? defaultMethod = default(bool?), Currency discount = default(Currency), bool? discounted = default(bool?), string displayName = default(string), string estimatedDelivery = default(string), bool? liftGateOption = default(bool?), string name = default(string), Currency tax = default(Currency), Currency totalTax = default(Currency))
{
this.Allow3rdPartyBilling = allow3rdPartyBilling;
this.Comment = comment;
this.Cost = cost;
this.CostBeforeDiscount = costBeforeDiscount;
this.DefaultMethod = defaultMethod;
this.Discount = discount;
this.Discounted = discounted;
this.DisplayName = displayName;
this.EstimatedDelivery = estimatedDelivery;
this.LiftGateOption = liftGateOption;
this.Name = name;
this.Tax = tax;
this.TotalTax = totalTax;
}
/// <summary>
/// True if this method allows the customer to use their own shipper account number
/// </summary>
/// <value>True if this method allows the customer to use their own shipper account number</value>
[DataMember(Name="allow_3rd_party_billing", EmitDefaultValue=false)]
public bool? Allow3rdPartyBilling { get; set; }
/// <summary>
/// Comment to display to the customer about this method
/// </summary>
/// <value>Comment to display to the customer about this method</value>
[DataMember(Name="comment", EmitDefaultValue=false)]
public string Comment { get; set; }
/// <summary>
/// Gets or Sets Cost
/// </summary>
[DataMember(Name="cost", EmitDefaultValue=false)]
public Currency Cost { get; set; }
/// <summary>
/// Gets or Sets CostBeforeDiscount
/// </summary>
[DataMember(Name="cost_before_discount", EmitDefaultValue=false)]
public Currency CostBeforeDiscount { get; set; }
/// <summary>
/// True if this is the default method
/// </summary>
/// <value>True if this is the default method</value>
[DataMember(Name="default_method", EmitDefaultValue=false)]
public bool? DefaultMethod { get; set; }
/// <summary>
/// Gets or Sets Discount
/// </summary>
[DataMember(Name="discount", EmitDefaultValue=false)]
public Currency Discount { get; set; }
/// <summary>
/// True if this method is discounted because of a coupon
/// </summary>
/// <value>True if this method is discounted because of a coupon</value>
[DataMember(Name="discounted", EmitDefaultValue=false)]
public bool? Discounted { get; set; }
/// <summary>
/// The name to display to the customer
/// </summary>
/// <value>The name to display to the customer</value>
[DataMember(Name="display_name", EmitDefaultValue=false)]
public string DisplayName { get; set; }
/// <summary>
/// Date of the estimated delivery (or range)
/// </summary>
/// <value>Date of the estimated delivery (or range)</value>
[DataMember(Name="estimated_delivery", EmitDefaultValue=false)]
public string EstimatedDelivery { get; set; }
/// <summary>
/// True if a lift gate option for this method should be offered to the customer
/// </summary>
/// <value>True if a lift gate option for this method should be offered to the customer</value>
[DataMember(Name="lift_gate_option", EmitDefaultValue=false)]
public bool? LiftGateOption { get; set; }
/// <summary>
/// Shipping method name
/// </summary>
/// <value>Shipping method name</value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Tax
/// </summary>
[DataMember(Name="tax", EmitDefaultValue=false)]
public Currency Tax { get; set; }
/// <summary>
/// Gets or Sets TotalTax
/// </summary>
[DataMember(Name="total_tax", EmitDefaultValue=false)]
public Currency TotalTax { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class CartSettingsShippingEstimate {\n");
sb.Append(" Allow3rdPartyBilling: ").Append(Allow3rdPartyBilling).Append("\n");
sb.Append(" Comment: ").Append(Comment).Append("\n");
sb.Append(" Cost: ").Append(Cost).Append("\n");
sb.Append(" CostBeforeDiscount: ").Append(CostBeforeDiscount).Append("\n");
sb.Append(" DefaultMethod: ").Append(DefaultMethod).Append("\n");
sb.Append(" Discount: ").Append(Discount).Append("\n");
sb.Append(" Discounted: ").Append(Discounted).Append("\n");
sb.Append(" DisplayName: ").Append(DisplayName).Append("\n");
sb.Append(" EstimatedDelivery: ").Append(EstimatedDelivery).Append("\n");
sb.Append(" LiftGateOption: ").Append(LiftGateOption).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Tax: ").Append(Tax).Append("\n");
sb.Append(" TotalTax: ").Append(TotalTax).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as CartSettingsShippingEstimate);
}
/// <summary>
/// Returns true if CartSettingsShippingEstimate instances are equal
/// </summary>
/// <param name="input">Instance of CartSettingsShippingEstimate to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CartSettingsShippingEstimate input)
{
if (input == null)
return false;
return
(
this.Allow3rdPartyBilling == input.Allow3rdPartyBilling ||
(this.Allow3rdPartyBilling != null &&
this.Allow3rdPartyBilling.Equals(input.Allow3rdPartyBilling))
) &&
(
this.Comment == input.Comment ||
(this.Comment != null &&
this.Comment.Equals(input.Comment))
) &&
(
this.Cost == input.Cost ||
(this.Cost != null &&
this.Cost.Equals(input.Cost))
) &&
(
this.CostBeforeDiscount == input.CostBeforeDiscount ||
(this.CostBeforeDiscount != null &&
this.CostBeforeDiscount.Equals(input.CostBeforeDiscount))
) &&
(
this.DefaultMethod == input.DefaultMethod ||
(this.DefaultMethod != null &&
this.DefaultMethod.Equals(input.DefaultMethod))
) &&
(
this.Discount == input.Discount ||
(this.Discount != null &&
this.Discount.Equals(input.Discount))
) &&
(
this.Discounted == input.Discounted ||
(this.Discounted != null &&
this.Discounted.Equals(input.Discounted))
) &&
(
this.DisplayName == input.DisplayName ||
(this.DisplayName != null &&
this.DisplayName.Equals(input.DisplayName))
) &&
(
this.EstimatedDelivery == input.EstimatedDelivery ||
(this.EstimatedDelivery != null &&
this.EstimatedDelivery.Equals(input.EstimatedDelivery))
) &&
(
this.LiftGateOption == input.LiftGateOption ||
(this.LiftGateOption != null &&
this.LiftGateOption.Equals(input.LiftGateOption))
) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.Tax == input.Tax ||
(this.Tax != null &&
this.Tax.Equals(input.Tax))
) &&
(
this.TotalTax == input.TotalTax ||
(this.TotalTax != null &&
this.TotalTax.Equals(input.TotalTax))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Allow3rdPartyBilling != null)
hashCode = hashCode * 59 + this.Allow3rdPartyBilling.GetHashCode();
if (this.Comment != null)
hashCode = hashCode * 59 + this.Comment.GetHashCode();
if (this.Cost != null)
hashCode = hashCode * 59 + this.Cost.GetHashCode();
if (this.CostBeforeDiscount != null)
hashCode = hashCode * 59 + this.CostBeforeDiscount.GetHashCode();
if (this.DefaultMethod != null)
hashCode = hashCode * 59 + this.DefaultMethod.GetHashCode();
if (this.Discount != null)
hashCode = hashCode * 59 + this.Discount.GetHashCode();
if (this.Discounted != null)
hashCode = hashCode * 59 + this.Discounted.GetHashCode();
if (this.DisplayName != null)
hashCode = hashCode * 59 + this.DisplayName.GetHashCode();
if (this.EstimatedDelivery != null)
hashCode = hashCode * 59 + this.EstimatedDelivery.GetHashCode();
if (this.LiftGateOption != null)
hashCode = hashCode * 59 + this.LiftGateOption.GetHashCode();
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
if (this.Tax != null)
hashCode = hashCode * 59 + this.Tax.GetHashCode();
if (this.TotalTax != null)
hashCode = hashCode * 59 + this.TotalTax.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SphinxDemo.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);
}
}
}
}
| |
#region License
//L
// 2007 - 2013 Copyright Northwestern University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
//L
#endregion
using System.Text;
using AnatomicEntity = aim_dotnet.AnatomicEntity;
using AnatomicEntityCharacteristic = aim_dotnet.AnatomicEntityCharacteristic;
using ImagingObservation = aim_dotnet.ImagingObservation;
using ImagingObservationCharacteristic = aim_dotnet.ImagingObservationCharacteristic;
using Inference = aim_dotnet.Inference;
using Calculation = aim_dotnet.Calculation;
namespace AIM.Annotation
{
public class CodeUtils
{
private const string COLLAPSED_VALID_TERM_CODING_SCHEME_DESIGNATOR = "AIM3-COMPAT";
public static AnatomicEntity ToAnatomicEntity(StandardCodeSequence codeSequence, string label)
{
return codeSequence == null
? null
: new AnatomicEntity
{
CodeValue = codeSequence.CodeValue,
CodeMeaning = codeSequence.CodeMeaning,
CodingSchemeDesignator = codeSequence.CodingSchemeDesignator,
CodingSchemeVersion = codeSequence.CodingSchemeVersion,
Label = label
};
}
public static AnatomicEntityCharacteristic ToAnatomicEntityCharacteristic(StandardCodeSequence codeSequence, string label)
{
return codeSequence == null
? null
: new AnatomicEntityCharacteristic
{
CodeValue = codeSequence.CodeValue,
CodeMeaning = codeSequence.CodeMeaning,
CodingSchemeDesignator = codeSequence.CodingSchemeDesignator,
CodingSchemeVersion = codeSequence.CodingSchemeVersion,
Label = label
};
}
public static ImagingObservation ToImagingObservation(StandardCodeSequence codeSequence, string label)
{
return codeSequence == null
? null
: new ImagingObservation
{
CodeValue = codeSequence.CodeValue,
CodeMeaning = codeSequence.CodeMeaning,
CodingSchemeDesignator = codeSequence.CodingSchemeDesignator,
CodingSchemeVersion = codeSequence.CodingSchemeVersion,
Label = label
};
}
public static ImagingObservationCharacteristic ToImagingObservationCharacteristic(StandardCodeSequence codeSequence, string label)
{
return codeSequence == null
? null
: new ImagingObservationCharacteristic
{
CodeValue = codeSequence.CodeValue,
CodeMeaning = codeSequence.CodeMeaning,
CodingSchemeDesignator = codeSequence.CodingSchemeDesignator,
CodingSchemeVersion = codeSequence.CodingSchemeVersion,
Label = label
};
}
public static Inference ToInference(StandardCodeSequence codeSequence)
{
return codeSequence == null
? null
: new Inference
{
CodeValue = codeSequence.CodeValue,
CodeMeaning = codeSequence.CodeMeaning,
CodingSchemeDesignator = codeSequence.CodingSchemeDesignator,
CodingSchemeVersion = codeSequence.CodingSchemeVersion
};
}
public static Calculation ToCalculation(StandardCodeSequence codeSequence)
{
return codeSequence == null
? null
: new Calculation
{
CodeValue = codeSequence.CodeValue,
CodeMeaning = codeSequence.CodeMeaning,
CodingSchemeDesignator = codeSequence.CodingSchemeDesignator,
CodingSchemeVersion = codeSequence.CodingSchemeVersion
};
}
public static StandardCodeSequence ToStandardCodeSequence(AnatomicEntity anatomicEntity)
{
return anatomicEntity == null
? null
:
new StandardCodeSequence(anatomicEntity.CodeValue, anatomicEntity.CodeMeaning, anatomicEntity.CodingSchemeDesignator,
anatomicEntity.CodingSchemeVersion);
}
public static StandardCodeSequence ToStandardCodeSequence(AnatomicEntityCharacteristic anatomicEntityCharacteristic)
{
return anatomicEntityCharacteristic == null
? null
:
new StandardCodeSequence(anatomicEntityCharacteristic.CodeValue, anatomicEntityCharacteristic.CodeMeaning,
anatomicEntityCharacteristic.CodingSchemeDesignator,
anatomicEntityCharacteristic.CodingSchemeVersion);
}
public static StandardCodeSequence ToStandardCodeSequence(ImagingObservation imagingObservation)
{
return imagingObservation == null
? null
:
new StandardCodeSequence(imagingObservation.CodeValue, imagingObservation.CodeMeaning, imagingObservation.CodingSchemeDesignator,
imagingObservation.CodingSchemeVersion);
}
public static StandardCodeSequence ToStandardCodeSequence(ImagingObservationCharacteristic imagingObservationCharacteristic)
{
return imagingObservationCharacteristic == null
? null
:
new StandardCodeSequence(imagingObservationCharacteristic.CodeValue, imagingObservationCharacteristic.CodeMeaning, imagingObservationCharacteristic.CodingSchemeDesignator,
imagingObservationCharacteristic.CodingSchemeVersion);
}
public static StandardCodeSequence ToStandardCodeSequence(Inference inference)
{
return inference == null
? null
:
new StandardCodeSequence(inference.CodeValue, inference.CodeMeaning, inference.CodingSchemeDesignator,
inference.CodingSchemeVersion);
}
private static readonly char[] HEX_DIGIT = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
/// <summary>
/// Create 8 char alphanumeric string from a given string
/// of alphanumerical <paramref name="val"/> string
/// </summary>
public static string ToHex(string val)
{
var valToInt = val.GetHashCode();
var ch8 = new char[8];
for (var i = 8; --i >= 0; valToInt >>= 4)
{
ch8[i] = HEX_DIGIT[valToInt & 0xf];
}
return new string(ch8);
}
/// <summary>
/// Recursively flattens a hierarchy of valid terms into a single StandardCodeSequence
/// by concatenating the codeValue and codeMeaning fields.
/// </summary>
/// <param name="standardValidTerm"></param>
/// <returns></returns>
private static StandardCodeSequence CollapseStandardValidTerm(StandardValidTerm standardValidTerm)
{
var codeValue = standardValidTerm.StandardCodeSequence.CodeValue;
var codingSchemeDesignator = standardValidTerm.StandardCodeSequence.CodingSchemeDesignator;
var codingSchemeVersion = standardValidTerm.StandardCodeSequence.CodingSchemeVersion;
var codeMeaning = standardValidTerm.StandardCodeSequence.CodeMeaning;
const string delimiter = ", ";
if (standardValidTerm.StandardValidTerms.Count > 0)
codingSchemeDesignator = COLLAPSED_VALID_TERM_CODING_SCHEME_DESIGNATOR;
foreach (var childStandardValidTerm in standardValidTerm.StandardValidTerms)
{
var standardCodeSequence = CollapseStandardValidTerm(childStandardValidTerm);
if (!string.IsNullOrEmpty(standardCodeSequence.CodeValue))
codeValue += delimiter + standardCodeSequence.CodeValue;
if (!string.IsNullOrEmpty(standardCodeSequence.CodeMeaning))
codeMeaning += delimiter + standardCodeSequence.CodeMeaning;
}
return new StandardCodeSequence(codeValue, codeMeaning, codingSchemeDesignator, codingSchemeVersion);
}
/// <summary>
/// Returns a StandardCodeSequence from a recursively collapsed or flatted StandardValidTerm.
/// </summary>
/// <param name="standardValidTerm"></param>
/// <returns></returns>
public static StandardCodeSequence ToStandardCodeSequence(StandardValidTerm standardValidTerm)
{
const int codeValueLength = 16;
const int codeMeaningLength = 64;
var standardCodeSequence = CollapseStandardValidTerm(standardValidTerm);
var codeValue = standardCodeSequence.CodeValue;
var codeMeaning = standardCodeSequence.CodeMeaning;
var codingSchemeDesignator = standardCodeSequence.CodingSchemeDesignator;
var codingSchemeVersion = standardCodeSequence.CodingSchemeVersion;
if (standardValidTerm.StandardValidTerms.Count > 0)
{
codeValue = ToHex(codeValue);
if (codeValue.Length > codeValueLength)
codeValue = codeValue.Substring(0, codeValueLength);
if (codeMeaning.Length > codeMeaningLength)
codeMeaning = codeMeaning.Substring(0, codeMeaningLength);
}
return new StandardCodeSequence(
codeValue,
codeMeaning,
codingSchemeDesignator,
codingSchemeVersion);
}
/// <summary>
/// Recursevely traverses given <paramref name="validTerm"/> and appends Code Meanings to the given <paramref name="sb"/>.
/// This effectively flattens <paramref name="validTerm"/> to a string.
/// </summary>
/// <param name="validTerm">Standard Valid Term to traverse</param>
/// <param name="sb">String Builder taht receives the values</param>
public static StringBuilder ToStringBuilder(StandardValidTerm validTerm, StringBuilder sb)
{
if (validTerm == null || sb == null)
return sb;
if (sb.Length > 0)
sb.Append(" ");
sb.Append(validTerm.StandardCodeSequence.CodeMeaning);
foreach (var standardValidTerm in validTerm.StandardValidTerms)
ToStringBuilder(standardValidTerm, sb);
return sb;
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.Common
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using Microsoft.Protocols.TestTools;
/// <summary>
/// A Class represent the XML schema validation function.
/// </summary>
public static class SchemaValidation
{
/// <summary>
/// The result of schema validation.
/// </summary>
private static ValidationResult validationResult;
/// <summary>
/// A list of schema which is used to construct schema validation reader.
/// </summary>
private static List<string> schemaList = new List<string>();
/// <summary>
/// The raw XMl response from server.
/// </summary>
private static XmlElement rawResponseXml;
/// <summary>
/// The raw XMl request to server.
/// </summary>
private static XmlElement rawRequestXml;
/// <summary>
/// The warning results of XML schema validation.
/// </summary>
private static List<ValidationEventArgs> xmlValidationWarnings;
/// <summary>
/// The error results of XML schema validation.
/// </summary>
private static List<ValidationEventArgs> xmlValidationErrors;
/// <summary>
/// Gets the validationResult of schema.
/// </summary>
public static ValidationResult ValidationResult
{
get
{
return validationResult;
}
}
/// <summary>
/// Gets the error results of XML schema validation.
/// </summary>
public static List<ValidationEventArgs> XmlValidationErrors
{
get
{
return xmlValidationErrors;
}
}
/// <summary>
/// Gets the warnings results of XML schema validation.
/// </summary>
public static List<ValidationEventArgs> XmlValidationWarnings
{
get
{
return xmlValidationWarnings;
}
}
/// <summary>
/// Gets or sets the operated raw XMl response from protocol SUT.
/// </summary>
public static XmlElement LastRawResponseXml
{
get
{
return rawResponseXml;
}
set
{
rawResponseXml = value;
}
}
/// <summary>
/// Gets or sets the raw Request Xml send to protocol SUT.
/// </summary>
public static XmlElement LastRawRequestXml
{
get
{
return rawRequestXml;
}
set
{
rawRequestXml = value;
}
}
/// <summary>
/// Validate a piece of Xml fragment.
/// </summary>
/// <param name="xmlValue">Xml fragment string.</param>
/// <returns>A return represents the validation result of the specified Xml fragment string.</returns>
public static ValidationResult ValidateXml(string xmlValue)
{
InitSchemaList();
InitValidateRecoder();
DoValidation(xmlValue);
return validationResult;
}
/// <summary>
/// This method is used to generate xml validation result information by using
/// the record errors and warnings.
/// </summary>
/// <returns>Return the xml validation result string which contains the errors and warning information.</returns>
public static string GenerateValidationResult()
{
StringBuilder sb = new StringBuilder();
if (XmlValidationWarnings.Count != 0)
{
sb.Append("The xml validation warnings:");
sb.Append(Environment.NewLine);
foreach (ValidationEventArgs warning in XmlValidationWarnings)
{
sb.Append(warning.Message);
sb.Append(Environment.NewLine);
}
}
if (XmlValidationErrors.Count != 0)
{
sb.Append("The xml validation errors:");
foreach (ValidationEventArgs error in XmlValidationErrors)
{
sb.Append(error.Message);
sb.Append(Environment.NewLine);
}
}
return sb.ToString();
}
/// <summary>
/// Initialize the validate recorder.
/// </summary>
private static void InitValidateRecoder()
{
// Initialize the result as "Success", if there are any validation error, this value will be changed by call back method.
validationResult = ValidationResult.Success;
if (null == xmlValidationWarnings)
{
xmlValidationWarnings = new List<ValidationEventArgs>();
}
xmlValidationWarnings.Clear();
if (null == xmlValidationErrors)
{
xmlValidationErrors = new List<ValidationEventArgs>();
}
xmlValidationErrors.Clear();
}
/// <summary>
/// Validate special xml.
/// </summary>
/// <param name="xmlString">The xml string.</param>
private static void DoValidation(string xmlString)
{
XmlReaderSettings validationSettings = new XmlReaderSettings();
foreach (string eachSchema in schemaList)
{
StringReader schemaReader = null;
try
{
schemaReader = new StringReader(eachSchema);
using (XmlReader xsdXmlReader = XmlReader.Create(schemaReader))
{
string targetNameSpace = GetTargetNamespace(eachSchema);
if (string.IsNullOrEmpty(targetNameSpace))
{
validationSettings.Schemas.Add(null, xsdXmlReader);
}
else
{
validationSettings.Schemas.Add(targetNameSpace, xsdXmlReader);
}
}
}
finally
{
if (schemaReader != null)
{
schemaReader.Dispose();
}
}
}
validationSettings.ValidationType = ValidationType.Schema;
validationSettings.ConformanceLevel = ConformanceLevel.Document;
validationSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
validationSettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
StringReader reader = null;
try
{
reader = new StringReader(xmlString);
using (XmlReader validationReader = XmlReader.Create(reader, validationSettings))
{
while (validationReader.Read())
{
}
}
}
finally
{
if (reader != null)
{
reader.Dispose();
}
}
}
/// <summary>
/// This method is a callback function which is used to record the schema validation errors and warnings.
/// </summary>
/// <param name="sender">An object instance which represents the sender of the events.</param>
/// <param name="args">The ValidationEventArgs contains validation result.</param>
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
validationResult = ValidationResult.Warning;
xmlValidationWarnings.Add(args);
}
else
{
validationResult = ValidationResult.Error;
xmlValidationErrors.Add(args);
}
}
/// <summary>
/// This method is used to get the target namespace from a schema string.
/// </summary>
/// <param name="fullSchema">The schema string</param>
/// <returns>A return value represents the target namespace value</returns>
private static string GetTargetNamespace(string fullSchema)
{
XmlDocument xd = new XmlDocument();
xd.LoadXml(fullSchema);
XmlAttributeCollection attributeList = xd.DocumentElement.Attributes;
foreach (XmlAttribute attribute in attributeList)
{
if (attribute.Name.Equals("targetNamespace", StringComparison.OrdinalIgnoreCase))
{
return attribute.Value;
}
}
return string.Empty;
}
/// <summary>
/// This method is used to initialize the schema definitions list which is used to set the schema validation settings.
/// </summary>
private static void InitSchemaList()
{
schemaList.Clear();
// In the current stage, only one WSDL exists.
schemaList.AddRange(GetSchemaStringFromWsdlFile("MS-FSSHTTP-FSSHTTPB.wsdl"));
}
/// <summary>
/// A method used to get the schema definitions from full WSDL file. It is designed to read schema definition from full WSDL file.
/// </summary>
/// <param name="schemaLoadPath">A parameter represents a full WSDL file path where the schema definitions should be loaded.</param>
/// <returns>A return value represents the schema definitions.</returns>
private static string[] GetSchemaStringFromWsdlFile(string schemaLoadPath)
{
List<string> schemas = new List<string>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(schemaLoadPath);
XmlNodeList wsdlTypes = xmlDoc.GetElementsByTagName("wsdl:types");
XmlNodeList wsdlDefinitions = xmlDoc.GetElementsByTagName("wsdl:definitions");
if (wsdlTypes != null && wsdlTypes.Count == 1)
{
foreach (XmlNode schemaElement in wsdlTypes[0].ChildNodes)
{
if (schemaElement.NodeType != XmlNodeType.Comment)
{
foreach (XmlAttribute attribute in wsdlDefinitions[0].Attributes)
{
if (attribute.Prefix == "xmlns" && schemaElement.Attributes.GetNamedItem(attribute.Name) == null)
{
XmlAttribute namespaceAttribute = (XmlAttribute)attribute.Clone();
schemaElement.Attributes.Append(namespaceAttribute);
}
}
schemas.Add(schemaElement.OuterXml);
}
}
}
return schemas.ToArray();
}
}
}
| |
//
// SmartPlaylistSource.cs
//
// Author:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2006-2007 Gabriel Burt
// Copyright (C) 2007 Novell, 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 System.Collections;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.Query;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.Query;
using Banshee.Sources;
using Banshee.Database;
using Banshee.Playlist;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
#pragma warning disable 0169
namespace Banshee.SmartPlaylist
{
public class SmartPlaylistSource : AbstractPlaylistSource, IUnmapableSource
{
private static List<SmartPlaylistSource> playlists = new List<SmartPlaylistSource> ();
private static uint timeout_id = 0;
static SmartPlaylistSource () {
Migrator.MigrateAll ();
ServiceManager.SourceManager.SourceAdded += HandleSourceAdded;
ServiceManager.SourceManager.SourceRemoved += HandleSourceRemoved;
}
private static string generic_name = Catalog.GetString ("Smart Playlist");
private static string properties_label = Catalog.GetString ("Edit Smart Playlist");
private QueryOrder query_order;
private QueryLimit limit;
private IntegerQueryValue limit_value;
private List<SmartPlaylistSource> dependencies = new List<SmartPlaylistSource>();
#region Properties
// Source override
public override bool HasProperties {
get { return true; }
}
public override bool CanAddTracks {
get { return false; }
}
public override bool CanRemoveTracks {
get { return false; }
}
// AbstractPlaylistSource overrides
protected override string SourceTable {
get { return "CoreSmartPlaylists"; }
}
protected override string SourcePrimaryKey {
get { return "SmartPlaylistID"; }
}
protected override string TrackJoinTable {
get { return "CoreSmartPlaylistEntries"; }
}
protected override bool CachesJoinTableEntries {
get { return false; }
}
// Custom properties
private List<QueryField> relevant_fields = new List<QueryField> ();
private QueryNode condition;
public QueryNode ConditionTree {
get { return condition; }
set {
condition = value;
relevant_fields.Clear ();
if (condition != null) {
condition_sql = condition.ToSql (BansheeQuery.FieldSet);
//until bug in DB layer is fixed, escape String.Format chars
condition_sql = condition_sql.Replace ("{", "{{").Replace ("}", "}}");
condition_xml = condition.ToXml (BansheeQuery.FieldSet);
foreach (QueryTermNode term in condition.GetTerms ()) {
if (!relevant_fields.Contains (term.Field))
relevant_fields.Add (term.Field);
}
} else {
condition_sql = null;
condition_xml = null;
}
}
}
private string additional_conditions;
public void AddCondition (string part)
{
if (!String.IsNullOrEmpty (part)) {
additional_conditions = additional_conditions == null ? part : String.Format ("{0} AND {1}", additional_conditions, part);
}
}
private string condition_sql;
public virtual string ConditionSql {
get { return condition_sql; }
protected set { condition_sql = value; }
}
private string condition_xml;
public string ConditionXml {
get { return condition_xml; }
set {
condition_xml = value;
ConditionTree = XmlQueryParser.Parse (condition_xml, BansheeQuery.FieldSet);
}
}
public QueryOrder QueryOrder {
get { return query_order; }
set {
query_order = value;
if (value != null && value.Field != null) {
Properties.Set<string> ("TrackListSortField", value.Field.Name);
Properties.Set<bool> ("TrackListSortAscending", value.Ascending);
} else {
Properties.Remove ("TrackListSortField");
Properties.Remove ("TrackListSortAscending");
}
}
}
public IntegerQueryValue LimitValue {
get { return limit_value; }
set { limit_value = value; }
}
public QueryLimit Limit {
get { return limit; }
set { limit = value; }
}
protected string OrderSql {
get { return !IsLimited || QueryOrder == null ? null : QueryOrder.ToSql (); }
}
protected string LimitSql {
get { return IsLimited ? Limit.ToSql (LimitValue) : null; }
}
public bool IsLimited {
get {
return (Limit != null && LimitValue != null && !LimitValue.IsEmpty && QueryOrder != null);
}
}
public bool IsHiddenWhenEmpty { get; private set; }
public override bool HasDependencies {
get { return dependencies.Count > 0; }
}
// FIXME scan ConditionTree for date fields
// FIXME even better, scan for date fields and see how fine-grained they are;
// eg if set to Last Added < 2 weeks ago, don't need a timer going off
// every 1 minute - every hour or two would suffice. Just change this
// property to a TimeSpan, rename it TimeDependentResolution or something
public bool TimeDependent {
get { return false; }
}
#endregion
#region Constructors
public SmartPlaylistSource (string name, PrimarySource parent) : base (generic_name, name, parent)
{
SetProperties ();
}
public SmartPlaylistSource (string name, QueryNode condition, QueryOrder order, QueryLimit limit, IntegerQueryValue limit_value, PrimarySource parent)
: this (name, condition, order, limit, limit_value, false, parent)
{
}
public SmartPlaylistSource (string name, QueryNode condition, QueryOrder order, QueryLimit limit, IntegerQueryValue limit_value, bool hiddenWhenEmpty, PrimarySource parent)
: this (name, parent)
{
ConditionTree = condition;
QueryOrder = order;
Limit = limit;
LimitValue = limit_value;
IsHiddenWhenEmpty = hiddenWhenEmpty;
UpdateDependencies ();
}
// For existing smart playlists that we're loading from the database
protected SmartPlaylistSource (long dbid, string name, string condition_xml, string order_by, string limit_number, string limit_criterion, PrimarySource parent, int count, bool is_temp, bool hiddenWhenEmpty) :
base (generic_name, name, dbid, -1, 0, parent, is_temp)
{
ConditionXml = condition_xml;
QueryOrder = BansheeQuery.FindOrder (order_by);
Limit = BansheeQuery.FindLimit (limit_criterion);
LimitValue = new IntegerQueryValue ();
LimitValue.ParseUserQuery (limit_number);
SavedCount = count;
IsHiddenWhenEmpty = hiddenWhenEmpty;
SetProperties ();
UpdateDependencies ();
}
private void SetProperties ()
{
Properties.SetString ("Icon.Name", "source-smart-playlist");
Properties.SetString ("SourcePropertiesActionLabel", properties_label);
Properties.SetString ("UnmapSourceActionLabel", Catalog.GetString ("Delete Smart Playlist"));
}
#endregion
#region Public Methods
public void ListenToPlaylists ()
{
}
public bool DependsOn (SmartPlaylistSource source)
{
dependencies.Contains (source);
return false;
}
#endregion
#region Private Methods
private void UpdateDependencies ()
{
foreach (SmartPlaylistSource s in dependencies) {
s.Updated -= OnDependencyUpdated;
}
dependencies.Clear ();
if (ConditionTree != null) {
foreach (SmartPlaylistQueryValue value in ConditionTree.SearchForValues<SmartPlaylistQueryValue> ()) {
SmartPlaylistSource playlist = value.ObjectValue;
if (playlist != null) {
playlist.Updated += OnDependencyUpdated;
dependencies.Add (playlist);
}
}
}
}
private void OnDependencyUpdated (object sender, EventArgs args)
{
Reload ();
}
#endregion
#region AbstractPlaylist overrides
protected override void AfterInitialized ()
{
base.AfterInitialized ();
if (PrimarySource != null) {
PrimarySource.TracksAdded += HandleTracksAdded;
PrimarySource.TracksChanged += HandleTracksChanged;
PrimarySource.TracksDeleted += HandleTracksDeleted;
}
if (IsHiddenWhenEmpty) {
RefreshAndReload ();
}
}
protected override void Create ()
{
DbId = ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
INSERT INTO CoreSmartPlaylists
(Name, Condition, OrderBy, LimitNumber, LimitCriterion, PrimarySourceID, IsTemporary, IsHiddenWhenEmpty)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
Name, ConditionXml,
QueryOrder != null ? QueryOrder.Name : null,
IsLimited ? LimitValue.ToSql () : null,
IsLimited ? Limit.Name : null,
PrimarySourceId, IsTemporary, IsHiddenWhenEmpty
));
UpdateDependencies ();
}
protected override void Update ()
{
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
UPDATE CoreSmartPlaylists
SET Name = ?,
Condition = ?,
OrderBy = ?,
LimitNumber = ?,
LimitCriterion = ?,
CachedCount = ?,
IsTemporary = ?,
IsHiddenWhenEmpty = ?
WHERE SmartPlaylistID = ?",
Name, ConditionXml,
IsLimited ? QueryOrder.Name : null,
IsLimited ? LimitValue.ToSql () : null,
IsLimited ? Limit.Name : null,
Count, IsTemporary, IsHiddenWhenEmpty, DbId
));
UpdateDependencies ();
}
protected override bool NeedsReloadWhenFieldChanged (Hyena.Query.QueryField field)
{
if (base.NeedsReloadWhenFieldChanged (field))
return true;
if (QueryOrder != null && QueryOrder.Field == field)
return true;
if (relevant_fields.Contains (field))
return true;
return false;
}
#endregion
#region DatabaseSource overrides
public void RefreshAndReload ()
{
Refresh ();
Reload ();
}
private bool refreshed = false;
public override void Reload ()
{
if (!refreshed) {
Refresh ();
} else {
// Don't set this on the first refresh
Properties.Set<bool> ("NotifyWhenAdded", IsHiddenWhenEmpty);
}
base.Reload ();
if (IsHiddenWhenEmpty && Parent != null) {
bool contains_me = Parent.ContainsChildSource (this);
int count = Count;
if (count == 0 && contains_me) {
Parent.RemoveChildSource (this);
} else if (count > 0 && !contains_me) {
Parent.AddChildSource (this);
}
}
}
public void Refresh ()
{
// Wipe the member list clean and repopulate it
string reload_str = String.Format (
@"DELETE FROM CoreSmartPlaylistEntries WHERE SmartPlaylistID = {0};
INSERT INTO CoreSmartPlaylistEntries
(EntryID, SmartPlaylistID, TrackID)
SELECT NULL, {0} as SmartPlaylistID, TrackId FROM {1}
WHERE {2} AND CoreTracks.PrimarySourceID = {3}
{4} {5} {6}",
DbId, DatabaseTrackInfo.Provider.From, DatabaseTrackInfo.Provider.Where,
PrimarySourceId, PrependCondition ("AND"), OrderSql, LimitSql
);
ServiceManager.DbConnection.Execute (reload_str);
// If the smart playlist is limited by file size or media duration, limit it here
if (IsLimited && !Limit.RowBased) {
// Identify where the cut off mark is
HyenaSqliteCommand limit_command = new HyenaSqliteCommand (String.Format (
@"SELECT EntryID, {0}
FROM CoreTracks, CoreSmartPlaylistEntries
WHERE SmartPlaylistID = {1} AND CoreSmartPlaylistEntries.TrackID = CoreTracks.TrackID
ORDER BY EntryID",
Limit.Column, DbId
));
long limit = LimitValue.IntValue * Limit.Factor;
long sum = 0;
long? cut_off_id = null;
using (IDataReader reader = ServiceManager.DbConnection.Query (limit_command)) {
while (reader.Read ()) {
sum += Convert.ToInt64 (reader[1]);
if (sum > limit) {
cut_off_id = Convert.ToInt64 (reader[0]);
break;
}
}
}
// Remove the playlist entries after the cut off
if (cut_off_id != null) {
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (
"DELETE FROM CoreSmartPlaylistEntries WHERE SmartPlaylistID = ? AND EntryID >= ?",
DbId, cut_off_id
));
}
}
refreshed = true;
}
#endregion
#region IUnmapableSource Implementation
public bool Unmap ()
{
if (DbId != null) {
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
BEGIN TRANSACTION;
DELETE FROM CoreSmartPlaylists WHERE SmartPlaylistID = ?;
DELETE FROM CoreSmartPlaylistEntries WHERE SmartPlaylistID = ?;
COMMIT TRANSACTION",
DbId, DbId
));
}
ThreadAssist.ProxyToMain (Remove);
return true;
}
public bool CanRefresh {
get { return QueryOrder == BansheeQuery.RandomOrder; }
}
protected override void HandleTracksAdded (Source sender, TrackEventArgs args)
{
if (args.When > last_added) {
last_added = args.When;
RefreshAndReload ();
}
}
protected override void HandleTracksChanged (Source sender, TrackEventArgs args)
{
if (args.When > last_updated) {
if (NeedsReloadWhenFieldsChanged (args.ChangedFields)) {
last_updated = args.When;
RefreshAndReload ();
} else {
InvalidateCaches ();
}
}
}
protected override void HandleTracksDeleted (Source sender, TrackEventArgs args)
{
if (args.When > last_removed) {
last_removed = args.When;
RefreshAndReload ();
/*if (ServiceManager.DbConnection.Query<int> (count_removed_command, last_removed) > 0) {
if (Limit == null) {
//track_model.UpdateAggregates ();
//OnUpdated ();
Reload ();
} else {
Reload ();
}
}*/
}
}
public override bool SetParentSource (Source parent)
{
base.SetParentSource (parent);
if (IsHiddenWhenEmpty && Count == 0) {
return false;
}
return true;
}
#endregion
private string PrependCondition (string with)
{
string sql = String.IsNullOrEmpty (ConditionSql) ? " " : String.Format ("{0} ({1})", with, ConditionSql);
if (!String.IsNullOrEmpty (additional_conditions)) {
sql = String.IsNullOrEmpty (sql) ? additional_conditions : String.Format ("{0} AND ({1})", sql, additional_conditions);
}
return sql;
}
public static IEnumerable<SmartPlaylistSource> LoadAll (PrimarySource parent)
{
ClearTemporary ();
using (HyenaDataReader reader = new HyenaDataReader (ServiceManager.DbConnection.Query (
@"SELECT SmartPlaylistID, Name, Condition, OrderBy, LimitNumber, LimitCriterion, PrimarySourceID, CachedCount, IsTemporary, IsHiddenWhenEmpty
FROM CoreSmartPlaylists WHERE PrimarySourceID = ?", parent.DbId))) {
while (reader.Read ()) {
SmartPlaylistSource playlist = null;
try {
playlist = new SmartPlaylistSource (
reader.Get<long> (0), reader.Get<string> (1),
reader.Get<string> (2), reader.Get<string> (3),
reader.Get<string> (4), reader.Get<string> (5),
parent, reader.Get<int> (7), reader.Get<bool> (8),
reader.Get<bool> (9)
);
} catch (Exception e) {
Log.Warning ("Ignoring Smart Playlist", String.Format ("Caught error: {0}", e), false);
}
if (playlist != null) {
yield return playlist;
}
}
}
}
private static void ClearTemporary ()
{
ServiceManager.DbConnection.Execute (@"
BEGIN TRANSACTION;
DELETE FROM CoreSmartPlaylistEntries WHERE SmartPlaylistID IN (SELECT SmartPlaylistID FROM CoreSmartPlaylists WHERE IsTemporary = 1);
DELETE FROM CoreSmartPlaylists WHERE IsTemporary = 1;
COMMIT TRANSACTION"
);
}
private static void HandleSourceAdded (SourceEventArgs args)
{
SmartPlaylistSource playlist = args.Source as SmartPlaylistSource;
if (playlist == null)
return;
StartTimer (playlist);
playlists.Add (playlist);
SortPlaylists();
}
private static void HandleSourceRemoved (SourceEventArgs args)
{
SmartPlaylistSource playlist = args.Source as SmartPlaylistSource;
if (playlist == null)
return;
playlists.Remove (playlist);
StopTimer();
}
private static void StartTimer (SmartPlaylistSource playlist)
{
// Check if the playlist is time-dependent, and if it is,
// start the auto-refresh timer.
if (timeout_id == 0 && playlist.TimeDependent) {
Log.Information (
"Starting Smart Playlist Auto-Refresh",
"Time-dependent smart playlist added, so starting one-minute auto-refresh timer.",
false
);
timeout_id = GLib.Timeout.Add(1000*60, OnTimerBeep);
}
}
private static void StopTimer ()
{
// If the timer is going and there are no more time-dependent playlists,
// stop the timer.
if (timeout_id != 0) {
foreach (SmartPlaylistSource p in playlists) {
if (p.TimeDependent) {
return;
}
}
// No more time-dependent playlists, so remove the timer
Log.Information (
"Stopping timer",
"There are no time-dependent smart playlists, so stopping auto-refresh timer.",
false
);
GLib.Source.Remove (timeout_id);
timeout_id = 0;
}
}
private static bool OnTimerBeep ()
{
foreach (SmartPlaylistSource p in playlists) {
if (p.TimeDependent) {
p.Reload();
}
}
// Keep the timer going
return true;
}
private static void SortPlaylists () {
playlists.Sort (new DependencyComparer ());
}
public static SmartPlaylistSource GetById (long dbId)
{
// TODO use a dictionary
foreach (SmartPlaylistSource sp in playlists) {
if (sp.DbId == dbId) {
return sp;
}
}
return null;
}
}
public class DependencyComparer : IComparer<SmartPlaylistSource> {
public int Compare(SmartPlaylistSource a, SmartPlaylistSource b)
{
if (b.DependsOn (a)) {
return -1;
} else if (a.DependsOn (b)) {
return 1;
} else {
return 0;
}
}
}
}
#pragma warning restore 0169
| |
#region --- OpenTK.OpenAL License ---
/* AlcFunctions.cs
* C header: \OpenAL 1.1 SDK\include\Alc.h
* Spec: http://www.openal.org/openal_webstf/specs/OpenAL11Specification.pdf
* Copyright (c) 2008 Christoph Brandtner and Stefanos Apostolopoulos
* See license.txt for license details
* http://www.OpenTK.net */
#endregion
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
/* Type Mapping
// 8-bit boolean
typedef char ALCboolean;
* byte
// character
typedef char ALCchar;
* byte
// signed 8-bit 2's complement integer
typedef char ALCbyte;
* byte
// unsigned 8-bit integer
typedef unsigned char ALCubyte;
* ubyte
// signed 16-bit 2's complement integer
typedef short ALCshort;
* short
// unsigned 16-bit integer
typedef unsigned short ALCushort;
* ushort
// unsigned 32-bit integer
typedef unsigned int ALCuint;
* uint
// signed 32-bit 2's complement integer
typedef int ALCint;
* int
// non-negative 32-bit binary integer size
typedef int ALCsizei;
* int
// enumerated 32-bit value
typedef int ALCenum;
* int
// 32-bit IEEE754 floating-point
typedef float ALCfloat;
* float
// 64-bit IEEE754 floating-point
typedef double ALCdouble;
* double
// void type (for opaque pointers only)
typedef void ALCvoid;
* void
* ALCdevice
* ALCcontext *context
* IntPtr
*/
using MonoMac.OpenGL;
namespace MonoMac.OpenAL
{
/// <summary>Alc = Audio Library Context</summary>
public static class Alc
{
#region Constants
private const string Lib = AL.Lib;
private const CallingConvention Style = CallingConvention.Cdecl;
#endregion Constants
#region Context Management
#region CreateContext
[DllImport(Alc.Lib, EntryPoint = "alcCreateContext", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity]
unsafe static extern IntPtr sys_CreateContext([In] IntPtr device, [In] int* attrlist);
/// <summary>This function creates a context using a specified device.</summary>
/// <param name="device">a pointer to a device</param>
/// <param name="attrlist">a pointer to a set of attributes: ALC_FREQUENCY, ALC_MONO_SOURCES, ALC_REFRESH, ALC_STEREO_SOURCES, ALC_SYNC</param>
/// <returns>Returns a pointer to the new context (NULL on failure). The attribute list can be NULL, or a zero terminated list of integer pairs composed of valid ALC attribute tokens and requested values.</returns>
[CLSCompliant(false)]
unsafe public static ContextHandle CreateContext([In] IntPtr device, [In] int* attrlist)
{
return new ContextHandle(sys_CreateContext(device, attrlist));
}
// ALC_API ALCcontext * ALC_APIENTRY alcCreateContext( ALCdevice *device, const ALCint* attrlist );
/// <summary>This function creates a context using a specified device.</summary>
/// <param name="device">a pointer to a device</param>
/// <param name="attriblist">an array of a set of attributes: ALC_FREQUENCY, ALC_MONO_SOURCES, ALC_REFRESH, ALC_STEREO_SOURCES, ALC_SYNC</param>
/// <returns>Returns a pointer to the new context (NULL on failure).</returns>
/// <remarks>The attribute list can be NULL, or a zero terminated list of integer pairs composed of valid ALC attribute tokens and requested values.</remarks>
public static ContextHandle CreateContext(IntPtr device, int[] attriblist)
{
unsafe
{
fixed (int* attriblist_ptr = attriblist)
{
return CreateContext(device, attriblist_ptr);
}
}
}
#endregion
[DllImport(Alc.Lib, EntryPoint = "alcMakeContextCurrent", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity()]
static extern bool MakeContextCurrent(IntPtr context);
/// <summary>This function makes a specified context the current context.</summary>
/// <param name="context">A pointer to the new context.</param>
/// <returns>Returns True on success, or False on failure.</returns>
public static bool MakeContextCurrent(ContextHandle context)
{
return MakeContextCurrent(context.Handle);
}
// ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent( ALCcontext *context );
[DllImport(Alc.Lib, EntryPoint = "alcProcessContext", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity()]
static extern void ProcessContext(IntPtr context);
/// <summary>This function tells a context to begin processing. When a context is suspended, changes in OpenAL state will be accepted but will not be processed. alcSuspendContext can be used to suspend a context, and then all the OpenAL state changes can be applied at once, followed by a call to alcProcessContext to apply all the state changes immediately. In some cases, this procedure may be more efficient than application of properties in a non-suspended state. In some implementations, process and suspend calls are each a NOP.</summary>
/// <param name="context">a pointer to the new context</param>
public static void ProcessContext(ContextHandle context)
{
ProcessContext(context.Handle);
}
// ALC_API void ALC_APIENTRY alcProcessContext( ALCcontext *context );
[DllImport(Alc.Lib, EntryPoint = "alcSuspendContext", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity()]
static extern void SuspendContext(IntPtr context);
/// <summary>This function suspends processing on a specified context. When a context is suspended, changes in OpenAL state will be accepted but will not be processed. A typical use of alcSuspendContext would be to suspend a context, apply all the OpenAL state changes at once, and then call alcProcessContext to apply all the state changes at once. In some cases, this procedure may be more efficient than application of properties in a non-suspended state. In some implementations, process and suspend calls are each a NOP.</summary>
/// <param name="context">a pointer to the context to be suspended.</param>
public static void SuspendContext(ContextHandle context)
{
SuspendContext(context.Handle);
}
// ALC_API void ALC_APIENTRY alcSuspendContext( ALCcontext *context );
[DllImport(Alc.Lib, EntryPoint = "alcDestroyContext", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity()]
static extern void DestroyContext(IntPtr context);
/// <summary>This function destroys a context.</summary>
/// <param name="context">a pointer to the new context.</param>
public static void DestroyContext(ContextHandle context)
{
DestroyContext(context.Handle);
}
// ALC_API void ALC_APIENTRY alcDestroyContext( ALCcontext *context );
[DllImport(Alc.Lib, EntryPoint = "alcGetCurrentContext", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity()]
private static extern IntPtr sys_GetCurrentContext();
/// <summary>This function retrieves the current context.</summary>
/// <returns>Returns a pointer to the current context.</returns>
public static ContextHandle GetCurrentContext()
{
return new ContextHandle(sys_GetCurrentContext());
}
// ALC_API ALCcontext * ALC_APIENTRY alcGetCurrentContext( void );
[DllImport(Alc.Lib, EntryPoint = "alcGetContextsDevice", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity()]
static extern IntPtr GetContextsDevice(IntPtr context);
/// <summary>This function retrieves a context's device pointer.</summary>
/// <param name="context">a pointer to a context.</param>
/// <returns>Returns a pointer to the specified context's device.</returns>
public static IntPtr GetContextsDevice(ContextHandle context)
{
return GetContextsDevice(context.Handle);
}
// ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice( ALCcontext *context );
#endregion Context Management
#region Device Management
/// <summary>This function opens a device by name.</summary>
/// <param name="devicename">a null-terminated string describing a device.</param>
/// <returns>Returns a pointer to the opened device. The return value will be NULL if there is an error.</returns>
[DllImport(Alc.Lib, EntryPoint = "alcOpenDevice", ExactSpelling = true, CallingConvention = Alc.Style, CharSet = CharSet.Ansi), SuppressUnmanagedCodeSecurity()]
public static extern IntPtr OpenDevice([In] string devicename);
// ALC_API ALCdevice * ALC_APIENTRY alcOpenDevice( const ALCchar *devicename );
/// <summary>This function closes a device by name.</summary>
/// <param name="device">a pointer to an opened device</param>
/// <returns>True will be returned on success or False on failure. Closing a device will fail if the device contains any contexts or buffers.</returns>
[DllImport(Alc.Lib, EntryPoint = "alcCloseDevice", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity()]
public static extern bool CloseDevice([In] IntPtr device);
// ALC_API ALCboolean ALC_APIENTRY alcCloseDevice( ALCdevice *device );
#endregion Device Management
#region Error support.
/// <summary>This function retrieves the current context error state.</summary>
/// <param name="device">a pointer to the device to retrieve the error state from</param>
/// <returns>Errorcode Int32.</returns>
[DllImport(Alc.Lib, EntryPoint = "alcGetError", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity()]
public static extern AlcError GetError([In] IntPtr device);
// ALC_API ALCenum ALC_APIENTRY alcGetError( ALCdevice *device );
#endregion Error support.
#region Extension support.
/// <summary>This function queries if a specified context extension is available.</summary>
/// <param name="device">a pointer to the device to be queried for an extension.</param>
/// <param name="extname">a null-terminated string describing the extension.</param>
/// <returns>Returns True if the extension is available, False if the extension is not available.</returns>
[DllImport(Alc.Lib, EntryPoint = "alcIsExtensionPresent", ExactSpelling = true, CallingConvention = Alc.Style, CharSet = CharSet.Ansi), SuppressUnmanagedCodeSecurity()]
public static extern bool IsExtensionPresent([In] IntPtr device, [In] string extname);
// ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent( ALCdevice *device, const ALCchar *extname );
/// <summary>This function retrieves the address of a specified context extension function.</summary>
/// <param name="device">a pointer to the device to be queried for the function.</param>
/// <param name="funcname">a null-terminated string describing the function.</param>
/// <returns>Returns the address of the function, or NULL if it is not found.</returns>
[DllImport(Alc.Lib, EntryPoint = "alcGetProcAddress", ExactSpelling = true, CallingConvention = Alc.Style, CharSet = CharSet.Ansi), SuppressUnmanagedCodeSecurity()]
public static extern IntPtr GetProcAddress([In] IntPtr device, [In] string funcname);
// ALC_API void * ALC_APIENTRY alcGetProcAddress( ALCdevice *device, const ALCchar *funcname );
/// <summary>This function retrieves the enum value for a specified enumeration name.</summary>
/// <param name="device">a pointer to the device to be queried.</param>
/// <param name="enumname">a null terminated string describing the enum value.</param>
/// <returns>Returns the enum value described by the enumName string. This is most often used for querying an enum value for an ALC extension.</returns>
[DllImport(Alc.Lib, EntryPoint = "alcGetEnumValue", ExactSpelling = true, CallingConvention = Alc.Style, CharSet = CharSet.Ansi), SuppressUnmanagedCodeSecurity()]
public static extern int GetEnumValue([In] IntPtr device, [In] string enumname);
// ALC_API ALCenum ALC_APIENTRY alcGetEnumValue( ALCdevice *device, const ALCchar *enumname );
#endregion Extension support.
#region Query functions
[DllImport(Alc.Lib, EntryPoint = "alcGetString", ExactSpelling = true, CallingConvention = Alc.Style, CharSet = CharSet.Ansi), SuppressUnmanagedCodeSecurity()]
private static extern IntPtr GetStringPrivate([In] IntPtr device, AlcGetString param);
// ALC_API const ALCchar * ALC_APIENTRY alcGetString( ALCdevice *device, ALCenum param );
/// <summary>This function returns pointers to strings related to the context.</summary>
/// <remarks>
/// ALC_DEFAULT_DEVICE_SPECIFIER will return the name of the default output device.
/// ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER will return the name of the default capture device.
/// ALC_DEVICE_SPECIFIER will return the name of the specified output device if a pointer is supplied, or will return a list of all available devices if a NULL device pointer is supplied. A list is a pointer to a series of strings separated by NULL characters, with the list terminated by two NULL characters. See Enumeration Extension for more details.
/// ALC_CAPTURE_DEVICE_SPECIFIER will return the name of the specified capture device if a pointer is supplied, or will return a list of all available devices if a NULL device pointer is supplied.
/// ALC_EXTENSIONS returns a list of available context extensions, with each extension separated by a space and the list terminated by a NULL character.
/// </remarks>
/// <param name="device">a pointer to the device to be queried.</param>
/// <param name="param">an attribute to be retrieved: ALC_DEFAULT_DEVICE_SPECIFIER, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER, ALC_DEVICE_SPECIFIER, ALC_CAPTURE_DEVICE_SPECIFIER, ALC_EXTENSIONS</param>
/// <returns>A string containing the name of the Device.</returns>
public static string GetString(IntPtr device, AlcGetString param)
{
return Marshal.PtrToStringAnsi(GetStringPrivate(device, param));
}
/// <summary>This function returns a List of strings related to the context.</summary>
/// <remarks>
/// ALC_DEVICE_SPECIFIER will return the name of the specified output device if a pointer is supplied, or will return a list of all available devices if a NULL device pointer is supplied. A list is a pointer to a series of strings separated by NULL characters, with the list terminated by two NULL characters. See Enumeration Extension for more details.
/// ALC_CAPTURE_DEVICE_SPECIFIER will return the name of the specified capture device if a pointer is supplied, or will return a list of all available devices if a NULL device pointer is supplied.
/// ALC_EXTENSIONS returns a list of available context extensions, with each extension separated by a space and the list terminated by a NULL character.
/// </remarks>
/// <param name="device">a pointer to the device to be queried.</param>
/// <param name="param">an attribute to be retrieved: ALC_DEVICE_SPECIFIER, ALC_CAPTURE_DEVICE_SPECIFIER, ALC_ALL_DEVICES_SPECIFIER</param>
/// <returns>A List of strings containing the names of the Devices.</returns>
public static IList<string> GetString(IntPtr device, AlcGetStringList param)
{
List<string> result = new List<string>();
IntPtr t = GetStringPrivate(IntPtr.Zero, (AlcGetString)param);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
byte b;
int offset = 0;
do
{
b = Marshal.ReadByte(t, offset++);
if (b != 0)
sb.Append((char)b);
if (b == 0)
{
result.Add(sb.ToString());
if (Marshal.ReadByte(t, offset) == 0) // offset already properly increased through ++
break; // 2x null
else
sb.Remove(0, sb.Length); // 1x null
}
} while (true);
return (IList<string>)result;
}
[DllImport(Alc.Lib, EntryPoint = "alcGetIntegerv", ExactSpelling = true, CallingConvention = Alc.Style, CharSet = CharSet.Ansi), SuppressUnmanagedCodeSecurity()]
unsafe static extern void GetInteger(IntPtr device, AlcGetInteger param, int size, int* data);
// ALC_API void ALC_APIENTRY alcGetIntegerv( ALCdevice *device, ALCenum param, ALCsizei size, ALCint *buffer );
/// <summary>This function returns integers related to the context.</summary>
/// <param name="device">a pointer to the device to be queried.</param>
/// <param name="param">an attribute to be retrieved: ALC_MAJOR_VERSION, ALC_MINOR_VERSION, ALC_ATTRIBUTES_SIZE, ALC_ALL_ATTRIBUTES</param>
/// <param name="size">the size of the destination buffer provided, in number of integers.</param>
/// <param name="data">a pointer to the buffer to be returned</param>
public static void GetInteger(IntPtr device, AlcGetInteger param, int size, out int data)
{
unsafe
{
fixed (int* data_ptr = &data)
{
GetInteger(device, param, size, data_ptr);
}
}
}
/// <summary>This function returns integers related to the context.</summary>
/// <param name="device">a pointer to the device to be queried.</param>
/// <param name="param">an attribute to be retrieved: ALC_MAJOR_VERSION, ALC_MINOR_VERSION, ALC_ATTRIBUTES_SIZE, ALC_ALL_ATTRIBUTES</param>
/// <param name="size">the size of the destination buffer provided, in number of integers.</param>
/// <param name="data">a pointer to the buffer to be returned</param>
public static void GetInteger(IntPtr device, AlcGetInteger param, int size, int[] data)
{
unsafe
{
fixed (int* data_ptr = data)
{
GetInteger(device, param, size, data_ptr);
}
}
}
#endregion Query functions
#region Capture functions
/// <summary>This function opens a capture device by name. </summary>
/// <param name="devicename">a pointer to a device name string.</param>
/// <param name="frequency">the frequency that the buffer should be captured at.</param>
/// <param name="format">the requested capture buffer format.</param>
/// <param name="buffersize">the size of the capture buffer in samples, not bytes.</param>
/// <returns>Returns the capture device pointer, or NULL on failure.</returns>
[CLSCompliant(false), DllImport(Alc.Lib, EntryPoint = "alcCaptureOpenDevice", ExactSpelling = true, CallingConvention = Alc.Style, CharSet = CharSet.Ansi), SuppressUnmanagedCodeSecurity()]
public static extern IntPtr CaptureOpenDevice(string devicename, uint frequency, ALFormat format, int buffersize);
/// <summary>This function opens a capture device by name. </summary>
/// <param name="devicename">a pointer to a device name string.</param>
/// <param name="frequency">the frequency that the buffer should be captured at.</param>
/// <param name="format">the requested capture buffer format.</param>
/// <param name="buffersize">the size of the capture buffer in samples, not bytes.</param>
/// <returns>Returns the capture device pointer, or NULL on failure.</returns>
[DllImport(Alc.Lib, EntryPoint = "alcCaptureOpenDevice", ExactSpelling = true, CallingConvention = Alc.Style, CharSet = CharSet.Ansi), SuppressUnmanagedCodeSecurity()]
public static extern IntPtr CaptureOpenDevice(string devicename, int frequency, ALFormat format, int buffersize);
// ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice( const ALCchar *devicename, ALCuint frequency, ALCenum format, ALCsizei buffersize );
/// <summary>This function closes the specified capture device.</summary>
/// <param name="device">a pointer to a capture device.</param>
/// <returns>Returns True if the close operation was successful, False on failure.</returns>
[DllImport(Alc.Lib, EntryPoint = "alcCaptureCloseDevice", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity()]
public static extern bool CaptureCloseDevice([In] IntPtr device);
// ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice( ALCdevice *device );
/// <summary>This function begins a capture operation.</summary>
/// <remarks>alcCaptureStart will begin recording to an internal ring buffer of the size specified when opening the capture device. The application can then retrieve the number of samples currently available using the ALC_CAPTURE_SAPMPLES token with alcGetIntegerv. When the application determines that enough samples are available for processing, then it can obtain them with a call to alcCaptureSamples.</remarks>
/// <param name="device">a pointer to a capture device.</param>
[DllImport(Alc.Lib, EntryPoint = "alcCaptureStart", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity()]
public static extern void CaptureStart([In] IntPtr device);
// ALC_API void ALC_APIENTRY alcCaptureStart( ALCdevice *device );
/// <summary>This function stops a capture operation.</summary>
/// <param name="device">a pointer to a capture device.</param>
[DllImport(Alc.Lib, EntryPoint = "alcCaptureStop", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity()]
public static extern void CaptureStop([In] IntPtr device);
// ALC_API void ALC_APIENTRY alcCaptureStop( ALCdevice *device );
/// <summary>This function completes a capture operation, and does not block.</summary>
/// <param name="device">a pointer to a capture device.</param>
/// <param name="buffer">a pointer to a buffer, which must be large enough to accommodate the number of samples.</param>
/// <param name="samples">the number of samples to be retrieved.</param>
[DllImport(Alc.Lib, EntryPoint = "alcCaptureSamples", ExactSpelling = true, CallingConvention = Alc.Style), SuppressUnmanagedCodeSecurity()]
public static extern void CaptureSamples(IntPtr device, IntPtr buffer, int samples);
// ALC_API void ALC_APIENTRY alcCaptureSamples( ALCdevice *device, ALCvoid *buffer, ALCsizei samples );
/// <summary>This function completes a capture operation, and does not block.</summary>
/// <param name="device">a pointer to a capture device.</param>
/// <param name="buffer">a reference to a buffer, which must be large enough to accommodate the number of samples.</param>
/// <param name="samples">the number of samples to be retrieved.</param>
public static void CaptureSamples<T>(IntPtr device, ref T buffer, int samples)
where T : struct
{
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
try
{
CaptureSamples(device, handle.AddrOfPinnedObject(), samples);
}
finally
{
handle.Free();
}
}
/// <summary>This function completes a capture operation, and does not block.</summary>
/// <param name="device">a pointer to a capture device.</param>
/// <param name="buffer">a buffer, which must be large enough to accommodate the number of samples.</param>
/// <param name="samples">the number of samples to be retrieved.</param>
public static void CaptureSamples<T>(IntPtr device, T[] buffer, int samples)
where T : struct
{
CaptureSamples(device, ref buffer[0], samples);
}
/// <summary>This function completes a capture operation, and does not block.</summary>
/// <param name="device">a pointer to a capture device.</param>
/// <param name="buffer">a buffer, which must be large enough to accommodate the number of samples.</param>
/// <param name="samples">the number of samples to be retrieved.</param>
public static void CaptureSamples<T>(IntPtr device, T[,] buffer, int samples)
where T : struct
{
CaptureSamples(device, ref buffer[0, 0], samples);
}
/// <summary>This function completes a capture operation, and does not block.</summary>
/// <param name="device">a pointer to a capture device.</param>
/// <param name="buffer">a buffer, which must be large enough to accommodate the number of samples.</param>
/// <param name="samples">the number of samples to be retrieved.</param>
public static void CaptureSamples<T>(IntPtr device, T[, ,] buffer, int samples)
where T : struct
{
CaptureSamples(device, ref buffer[0, 0, 0], samples);
}
#endregion Capture functions
}
}
| |
using System;
using System.Globalization;
using Xwt.Backends;
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.ObjCRuntime;
namespace Xwt.Mac
{
public class SpinButtonBackend : ViewBackend<MacSpinButton, ISpinButtonEventSink>, ISpinButtonBackend
{
public override void Initialize ()
{
ViewObject = new MacSpinButton ();
}
protected new ISpinButtonEventSink EventSink {
get { return (ISpinButtonEventSink)base.EventSink; }
}
public override void EnableEvent (object eventId)
{
}
public override void DisableEvent (object eventId)
{
}
public double ClimbRate {
get { return Widget.ClimbRate; }
set { Widget.ClimbRate = value; }
}
public int Digits {
get { return Widget.Digits; }
set { Widget.Digits = value; }
}
public double Value {
get { return Widget.Value; }
set { Widget.Value = value; }
}
public string Text {
get { return Widget.Text; }
set { Widget.Text = value; }
}
public bool Wrap {
get { return Widget.Wrap; }
set { Widget.Wrap = value; }
}
public double MinimumValue {
get { return Widget.MinimumValue; }
set { Widget.MinimumValue = value; }
}
public double MaximumValue {
get { return Widget.MaximumValue; }
set { Widget.MaximumValue = value; }
}
public double IncrementValue {
get { return Widget.IncrementValue; }
set { Widget.IncrementValue = value; }
}
public void SetButtonStyle (ButtonStyle style)
{
Widget.SetButtonStyle (style);
}
string indeterminateMessage = String.Empty;
public string IndeterminateMessage {
get { return indeterminateMessage; }
set {
indeterminateMessage = value;
if (IsIndeterminate)
Text = indeterminateMessage;
}
}
bool isIndeterminate = false;
public bool IsIndeterminate {
get { return isIndeterminate; }
set {
isIndeterminate = value;
if (value)
Text = indeterminateMessage;
}
}
}
public class MacSpinButton : NSView, IViewObject
{
NSStepper stepper;
NSTextField input;
class RelativeTextField : NSTextField
{
NSView reference;
public RelativeTextField (NSView reference)
{
this.reference = reference;
}
public override void ResizeWithOldSuperviewSize (System.Drawing.SizeF oldSize)
{
base.ResizeWithOldSuperviewSize (oldSize);
SetFrameSize (new System.Drawing.SizeF (reference.Frame.Left - 6, Frame.Size.Height));
}
}
public MacSpinButton ()
{
stepper = new NSStepper ();
input = new RelativeTextField (stepper);
input.StringValue = stepper.DoubleValue.ToString("N");
input.Alignment = NSTextAlignment.Right;
stepper.Activated += HandleValueOutput;
input.Changed += HandleValueInput;
SetFrameSize (new System.Drawing.SizeF (55, 22));
stepper.Frame = new System.Drawing.RectangleF (new System.Drawing.PointF (36, 0), new System.Drawing.SizeF (19, 22));
input.Frame = new System.Drawing.RectangleF (new System.Drawing.PointF (4, 0), new System.Drawing.SizeF (26, 22));
AutoresizesSubviews = true;
stepper.AutoresizingMask = NSViewResizingMask.MinXMargin | NSViewResizingMask.MinYMargin;
input.AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.MaxXMargin | NSViewResizingMask.MaxYMargin;
AddSubview (input);
AddSubview (stepper);
}
void HandleValueOutput (object sender, EventArgs e)
{
HandleValueOutput ();
Backend.ApplicationContext.InvokeUserCode (delegate {
((SpinButtonBackend)Backend).EventSink.ValueChanged();
});
}
void HandleValueOutput ()
{
var outputArgs = new WidgetEventArgs ();
Backend.ApplicationContext.InvokeUserCode (delegate {
((SpinButtonBackend)Backend).EventSink.ValueOutput(outputArgs);
});
if (!outputArgs.Handled)
input.StringValue = stepper.DoubleValue.ToString("N" + Digits);
}
void HandleValueInput (object sender, EventArgs e)
{
var argsInput = new SpinButtonInputEventArgs ();
Backend.ApplicationContext.InvokeUserCode (delegate {
((SpinButtonBackend)Backend).EventSink.ValueInput(argsInput);
});
double new_val = double.NaN;
if (argsInput.Handled)
new_val = argsInput.NewValue;
else {
var numberStyle = NumberStyles.Float;
if (Digits == 0)
numberStyle = NumberStyles.Integer;
if (!double.TryParse (input.StringValue, numberStyle, CultureInfo.CurrentCulture, out new_val))
new_val = double.NaN;
}
if (stepper.DoubleValue == new_val)
return;
if (double.IsNaN (new_val)) { // reset to previous input
HandleValueOutput ();
return;
}
stepper.DoubleValue = new_val;
if (!argsInput.Handled)
input.StringValue = stepper.DoubleValue.ToString ("N" + Digits);
Backend.ApplicationContext.InvokeUserCode (delegate {
((SpinButtonBackend)Backend).EventSink.ValueChanged ();
});
}
public double ClimbRate {
get { return stepper.Increment; }
set { stepper.Increment = value; }
}
int digits;
public int Digits {
get { return digits; }
set {
digits = value;
HandleValueOutput ();
}
}
public double Value {
get { return stepper.DoubleValue; }
set {
stepper.DoubleValue = value;
HandleValueOutput ();
}
}
public string Text {
get { return input.StringValue; }
set { input.StringValue = value; }
}
public bool Wrap {
get { return stepper.ValueWraps; }
set { stepper.ValueWraps = value; }
}
public double MinimumValue {
get { return stepper.MinValue; }
set {
stepper.MinValue = value;
HandleValueOutput ();
}
}
public double MaximumValue {
get { return stepper.MaxValue; }
set {
stepper.MaxValue = value;
HandleValueOutput ();
}
}
public double IncrementValue {
get { return stepper.Increment; }
set { stepper.Increment = value; }
}
public void SetButtonStyle (ButtonStyle style)
{
switch (style) {
case ButtonStyle.Borderless:
case ButtonStyle.Flat:
input.Bordered = false;
break;
default:
input.Bordered = true;
break;
}
}
public ViewBackend Backend { get; set; }
public NSView View {
get { return this; }
}
public void EnableEvent (Xwt.Backends.ButtonEvent ev)
{
}
public void DisableEvent (Xwt.Backends.ButtonEvent ev)
{
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using EspaceClient.BackOffice.Domaine.Criterias;
using EspaceClient.BackOffice.Domaine.Results;
using EspaceClient.BackOffice.Silverlight.Business.Depots;
using EspaceClient.BackOffice.Silverlight.Business.Interfaces;
using EspaceClient.BackOffice.Silverlight.Business.Loader;
using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Modularity;
using EspaceClient.BackOffice.Silverlight.ViewModels.Helper.GestionClient.Contact;
using EspaceClient.BackOffice.Silverlight.ViewModels.Messages;
using EspaceClient.BackOffice.Silverlight.ViewModels.ModelBuilders.GestionClient.Contact;
using nRoute.Components;
using nRoute.Components.Composition;
using OGDC.Silverlight.Toolkit.Services.Services;
using EspaceClient.BackOffice.Silverlight.ViewModels.ModelBuilders.GestionClient.Contact.Details;
using EspaceClient.BackOffice.Silverlight.ViewModels.Helper.GestionClient.Contact;
namespace EspaceClient.BackOffice.Silverlight.ViewModels.GestionClient.Contact.Tabs
{
/// <summary>
/// ViewModel de la vue <see cref="SearchView"/>
/// </summary>
public class SearchViewModel : TabBase
{
private readonly IResourceWrapper _resourceWrapper;
private readonly IDepotContact _contact;
private readonly IMessenging _messengingService;
private readonly IApplicationContext _applicationContext;
private readonly ILoaderReferentiel _referentiel;
private readonly IModelBuilderDetails _builderDetails;
private ObservableCollection<ContactResult> _searchResult;
private bool _searchOverflow;
private ICommand _searchCommand;
private ICommand _resetCommand;
private ICommand _doubleClickCommand;
private SearchContactCriteriasDto _criteres;
private bool _isLoading;
[ResolveConstructor]
public SearchViewModel(
IResourceWrapper resourceWrapper,
IMessenging messengingService,
IDepotContact contact,
IModelBuilderDetails builderDetails,
IApplicationContext applicationContext,
ILoaderReferentiel referentiel)
: base(applicationContext, messengingService)
{
_resourceWrapper = resourceWrapper;
_messengingService = messengingService;
_applicationContext = applicationContext;
_referentiel = referentiel;
_contact = contact;
_builderDetails = builderDetails;
InitializeCommands();
InitializeUI();
OnSearch();
}
public ObservableCollection<ContactResult> SearchResult
{
get
{
return _searchResult;
}
set
{
if (_searchResult != value)
{
_searchResult = value;
NotifyPropertyChanged(() => SearchResult);
}
}
}
public bool SearchOverflow
{
get
{
return _searchOverflow;
}
set
{
if (_searchOverflow != value)
{
_searchOverflow = value;
NotifyPropertyChanged(() => SearchOverflow);
}
}
}
public bool IsLoading
{
get
{
return _isLoading;
}
set
{
if (_isLoading != value)
{
_isLoading = value;
NotifyPropertyChanged(() => IsLoading);
}
}
}
#region Commands
/// <summary>
/// Command de recherche des personnes.
/// </summary>
public ICommand SearchCommand
{
get { return _searchCommand; }
}
/// <summary>
/// Command de recherche des personnes.
/// </summary>
public ICommand ResetCommand
{
get { return _resetCommand; }
}
public ICommand DoubleClickCommand
{
get
{
return _doubleClickCommand;
}
}
#endregion
private void InitializeCommands()
{
_searchCommand = new ActionCommand(OnSearch);
_doubleClickCommand = new ActionCommand<ContactResult>(OnDoubleClickCommand);
_resetCommand = new ActionCommand(OnReset);
}
private void OnReset()
{
InitializeUI();
}
private void InitializeUI()
{
SearchResult = new ObservableCollection<ContactResult>();
SearchOverflow = false;
IsLoading = false;
}
private void OnSearch()
{
if (IsLoading)
return;
_contact.Search(
r =>
{
foreach (var P in r)
SearchResult.Add(P);
IsLoading = false;
}, error => _messengingService.Publish(new ErrorMessage(error)));
SearchResult.Clear();
IsLoading = true;
}
private void OnDoubleClickCommand(ContactResult selectedContact)
{
if (selectedContact != null)
{
EspaceClient.BackOffice.Silverlight.ViewModels.Helper.GestionClient.Contact.ContactHelper.AddContactTab(selectedContact.ID, _messengingService, _contact, _builderDetails, _referentiel);
}
}
public override void OnRefreshTab<EntityType>(long id, Action<EntityType> callback)
{
throw new NotImplementedException();
}
protected override void OnRefreshTabCompleted(Action callback)
{
throw new NotImplementedException();
}
}
}
| |
namespace SampleApp
{
partial class DataTableTreeExample
{
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DataTableTreeExample));
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.treeViewAdv1 = new Aga.Controls.Tree.TreeViewAdv();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.addNodeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.nodeTextBox1 = new Aga.Controls.Tree.NodeControls.NodeTextBox();
this.nodeStateIcon1 = new Aga.Controls.Tree.NodeControls.NodeStateIcon();
this.panel1 = new System.Windows.Forms.Panel();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.ID = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ParentID = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Label = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Data = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.label1 = new System.Windows.Forms.Label();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.contextMenuStrip1.SuspendLayout();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.treeViewAdv1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.panel1);
this.splitContainer1.Panel2.Controls.Add(this.dataGridView1);
this.splitContainer1.Size = new System.Drawing.Size(830, 528);
this.splitContainer1.SplitterDistance = 298;
this.splitContainer1.TabIndex = 0;
//
// treeViewAdv1
//
this.treeViewAdv1.BackColor = System.Drawing.SystemColors.Window;
this.treeViewAdv1.ContextMenuStrip = this.contextMenuStrip1;
this.treeViewAdv1.Cursor = System.Windows.Forms.Cursors.Default;
this.treeViewAdv1.DefaultToolTipProvider = null;
this.treeViewAdv1.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeViewAdv1.DragDropMarkColor = System.Drawing.Color.Black;
this.treeViewAdv1.LineColor = System.Drawing.SystemColors.ControlDark;
this.treeViewAdv1.Location = new System.Drawing.Point(0, 0);
this.treeViewAdv1.Model = null;
this.treeViewAdv1.Name = "treeViewAdv1";
this.treeViewAdv1.NodeControls.Add(this.nodeTextBox1);
this.treeViewAdv1.NodeControls.Add(this.nodeStateIcon1);
this.treeViewAdv1.SelectedNode = null;
this.treeViewAdv1.Size = new System.Drawing.Size(298, 528);
this.treeViewAdv1.TabIndex = 0;
this.treeViewAdv1.Text = "treeViewAdv1";
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.addNodeToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(153, 48);
//
// addNodeToolStripMenuItem
//
this.addNodeToolStripMenuItem.Name = "addNodeToolStripMenuItem";
this.addNodeToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.addNodeToolStripMenuItem.Text = "Add Node";
this.addNodeToolStripMenuItem.Click += new System.EventHandler(this.addNode_Click);
//
// nodeTextBox1
//
this.nodeTextBox1.IncrementalSearchEnabled = true;
this.nodeTextBox1.LeftMargin = 3;
this.nodeTextBox1.ParentColumn = null;
//
// nodeStateIcon1
//
this.nodeStateIcon1.LeftMargin = 1;
this.nodeStateIcon1.ParentColumn = null;
//
// panel1
//
this.panel1.Controls.Add(this.label1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel1.Location = new System.Drawing.Point(0, 428);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(528, 100);
this.panel1.TabIndex = 1;
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ID,
this.ParentID,
this.Label,
this.Data});
this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView1.Location = new System.Drawing.Point(0, 0);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(528, 528);
this.dataGridView1.TabIndex = 0;
this.dataGridView1.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this.dataGridView1_RowsAdded);
//
// ID
//
this.ID.HeaderText = "ID";
this.ID.Name = "ID";
//
// ParentID
//
this.ParentID.HeaderText = "ParentID";
this.ParentID.Name = "ParentID";
//
// Label
//
this.Label.HeaderText = "Label";
this.Label.Name = "Label";
//
// Data
//
this.Data.HeaderText = "Data";
this.Data.Name = "Data";
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
this.imageList1.Images.SetKeyName(0, "");
this.imageList1.Images.SetKeyName(1, "");
this.imageList1.Images.SetKeyName(2, "");
this.imageList1.Images.SetKeyName(3, "");
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(59, 34);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(174, 13);
this.label1.TabIndex = 0;
this.label1.Text = "right click on a folder to add a node";
//
// DataTableTreeExample
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.splitContainer1);
this.Name = "DataTableTreeExample";
this.Size = new System.Drawing.Size(830, 528);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.contextMenuStrip1.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private Aga.Controls.Tree.TreeViewAdv treeViewAdv1;
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.DataGridViewTextBoxColumn ID;
private System.Windows.Forms.DataGridViewTextBoxColumn ParentID;
private System.Windows.Forms.DataGridViewTextBoxColumn Label;
private System.Windows.Forms.DataGridViewTextBoxColumn Data;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem addNodeToolStripMenuItem;
private System.Windows.Forms.ImageList imageList1;
private Aga.Controls.Tree.NodeControls.NodeTextBox nodeTextBox1;
private Aga.Controls.Tree.NodeControls.NodeStateIcon nodeStateIcon1;
private System.Windows.Forms.Label label1;
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Debugging
{
using System;
using System.Text;
public sealed class DebugInfo
{
public static DebugInfo[] SharedEmptyArray = new DebugInfo[0];
//
// State
//
public String SrcFileName;
public String MethodName;
public int BeginLineNumber;
public int BeginColumn;
public int EndLineNumber;
public int EndColumn;
//
// Constructor Methods
//
public DebugInfo( String srcFileName,
int beginLineNumber,
int beginColumn,
int endLineNumber,
int endColumn ) :
this( srcFileName, null, beginLineNumber, beginColumn, endLineNumber, endColumn )
{
}
public DebugInfo( String srcFileName ,
String methodName ,
int beginLineNumber ,
int beginColumn ,
int endLineNumber ,
int endColumn )
{
this.SrcFileName = srcFileName;
this.MethodName = methodName;
this.BeginLineNumber = beginLineNumber;
this.BeginColumn = beginColumn;
this.EndLineNumber = endLineNumber;
this.EndColumn = endColumn;
}
private DebugInfo( String srcFileName ,
String methodName ,
int lineNumber )
{
SetMarkerForLine( srcFileName, methodName, lineNumber );
}
// To prevent problems with assembly circular dependencies
// this is of type System.Object, but ultimately at this point, should
// always be a Microsoft.Zelig.Runtime.TypeSystem.MethodRepresentation
// This is used in conversion to LLVM debug information, particularly
// when handling inlined code. For IL instructions that had no debug
// information or compiler generated IR operators this will be null.
public object Scope { get; set; }
//
// Equality Methods
//
public override bool Equals( object obj )
{
if(obj is DebugInfo)
{
DebugInfo other = (DebugInfo)obj;
if(this.SrcFileName == other.SrcFileName &&
this.MethodName == other.MethodName &&
this.BeginLineNumber == other.BeginLineNumber &&
this.BeginColumn == other.BeginColumn &&
this.EndLineNumber == other.EndLineNumber &&
this.EndColumn == other.EndColumn )
{
return true;
}
}
return false;
}
public override int GetHashCode()
{
Byte[] crcData = System.Text.UTF8Encoding.UTF8.GetBytes(SrcFileName);
return (int)CRC32.Compute( crcData, (uint)this.BeginLineNumber );
}
//
// Helper Methods
//
public static DebugInfo CreateMarkerForLine( string srcFileName ,
string methodName ,
int lineNumber )
{
return new DebugInfo( srcFileName, methodName, lineNumber );
}
public void SetMarkerForLine( string srcFileName ,
string methodName ,
int lineNumber )
{
this.SrcFileName = srcFileName;
this.MethodName = methodName;
this.BeginLineNumber = lineNumber;
this.BeginColumn = int.MinValue;
this.EndLineNumber = lineNumber;
this.EndColumn = int.MaxValue;
}
public DebugInfo ComputeIntersection( DebugInfo other )
{
if(other == null)
{
return null;
}
int compareBeginLine = this.BeginLineNumber.CompareTo( other.BeginLineNumber );
int beginLineNumber;
int beginColumn;
if(compareBeginLine < 0)
{
beginLineNumber = other.BeginLineNumber;
beginColumn = other.BeginColumn;
}
else
{
beginLineNumber = this.BeginLineNumber;
if(compareBeginLine > 0)
{
beginColumn = this.BeginColumn;
}
else
{
beginColumn = Math.Max( this.BeginColumn, other.BeginColumn );
}
}
//--//
int compareEndLine = this.EndLineNumber.CompareTo( other.EndLineNumber );
int endLineNumber;
int endColumn;
if(compareEndLine > 0)
{
endLineNumber = other.EndLineNumber;
endColumn = other.EndColumn;
}
else
{
endLineNumber = this.EndLineNumber;
if(compareEndLine < 0)
{
endColumn = this.EndColumn;
}
else
{
endColumn = Math.Min( this.EndColumn, other.EndColumn );
}
}
if((beginLineNumber > endLineNumber ) ||
(beginLineNumber == endLineNumber && beginColumn >= endColumn) )
{
return null;
}
return new DebugInfo( null, MethodName, beginLineNumber, beginColumn, endLineNumber, endColumn );
}
public bool IsContainedIn( DebugInfo other )
{
if(this.SrcFileName != other.SrcFileName)
{
return false;
}
int compareBeginLine = this.BeginLineNumber.CompareTo( other.BeginLineNumber );
if(compareBeginLine < 0)
{
return false;
}
if(compareBeginLine == 0 && this.BeginColumn < other.BeginColumn)
{
return false;
}
//--//
int compareEndLine = this.EndLineNumber.CompareTo( other.EndLineNumber );
if(compareEndLine > 0)
{
return false;
}
if(compareEndLine == 0 && this.EndColumn > other.EndColumn)
{
return false;
}
return true;
}
//
// Debug Methods
//
public override String ToString()
{
StringBuilder s = new StringBuilder();
s.AppendFormat( " ; [{0}:{1}-{2}:{3}] {4}", this.BeginLineNumber, this.BeginColumn, this.EndLineNumber, this.EndColumn, this.SrcFileName );
return s.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace HackerRank.Tests
{
[TestFixture]
public class TwoPulsesTester
{
[Test]
public void Sample0()
{
var inputs = new[]
{
"5 6",
"GGGGGG",
"GBBBGB",
"GGGGGG",
"GGBBGB",
"GGGGGG"
};
ConsoleAdapterMocker.InitializeAdapter(false);
ConsoleAdapterMocker.Write(inputs);
TwoPulses.Main(null);
Assert.AreEqual("5", ConsoleAdapter.ReadLine());
}
[Test]
public void Sample1()
{
var inputs = new[]
{
"6 6",
"BGBBGB",
"GGGGGG",
"BGBBGB",
"GGGGGG",
"BGBBGB",
"BGBBGB"
};
ConsoleAdapterMocker.InitializeAdapter(false);
ConsoleAdapterMocker.Write(inputs);
TwoPulses.Main(null);
Assert.AreEqual("25", ConsoleAdapter.ReadLine());
}
[Test]
public void GivenTwoPulseWhoCross_TheTheBiggestIsFound()
{
var inputs = new[]
{
"6 6",
"BBBBGB",
"BBGGGG",
"BBGBGB",
"GGGGGB",
"BBGBBB",
"BBGBBB"
};
ConsoleAdapterMocker.InitializeAdapter(false);
ConsoleAdapterMocker.Write(inputs);
TwoPulses.Main(null);
Assert.AreEqual("45", ConsoleAdapter.ReadLine());
}
[Test]
public void Sample12()
{
var inputs = new[]
{
"12 12",
"GGGGGGGGGGGG",
"GBGGBBBBBBBG",
"GBGGBBBBBBBG",
"GGGGGGGGGGGG",
"GGGGGGGGGGGG",
"GGGGGGGGGGGG",
"GGGGGGGGGGGG",
"GBGGBBBBBBBG",
"GBGGBBBBBBBG",
"GBGGBBBBBBBG",
"GGGGGGGGGGGG",
"GBGGBBBBBBBG"
};
ConsoleAdapterMocker.InitializeAdapter(false);
ConsoleAdapterMocker.Write(inputs);
TwoPulses.Main(null);
Assert.AreEqual("81", ConsoleAdapter.ReadLine());
}
[Test]
public void Sample18()
{
var inputs = new[]
{
"14 13",
"BBGGBGGBBGGGB",
"BBGGBGGBBGGGB",
"BBGGBGGBBGGGB",
"BBGGBGGBBGGGB",
"GGGGGGGGGGGGG",
"BBGGBGGBBGGGB",
"GGGGGGGGGGGGG",
"BBGGBGGBBGGGB",
"BBGGBGGBBGGGB",
"GGGGGGGGGGGGG",
"GGGGGGGGGGGGG",
"GGGGGGGGGGGGG",
"BBGGBGGBBGGGB",
"GGGGGGGGGGGGG"
};
ConsoleAdapterMocker.InitializeAdapter(false);
ConsoleAdapterMocker.Write(inputs);
TwoPulses.Main(null);
Assert.AreEqual("289", ConsoleAdapter.ReadLine());
}
[Test]
public void Sample20()
{
var inputs = new[]
{
"14 15",
"GBBBBBBGGGBGGBB",
"GBBBBBBGGGBGGBB",
"GBBBBBBGGGBGGBB",
"GBBBBBBGGGBGGBB",
"GGGGGGGGGGGGGGG",
"GGGGGGGGGGGGGGG",
"GBBBBBBGGGBGGBB",
"GBBBBBBGGGBGGBB",
"GGGGGGGGGGGGGGG",
"GBBBBBBGGGBGGBB",
"GBBBBBBGGGBGGBB",
"GGGGGGGGGGGGGGG",
"GGGGGGGGGGGGGGG",
"GBBBBBBGGGBGGBB"
};
ConsoleAdapterMocker.InitializeAdapter(false);
ConsoleAdapterMocker.Write(inputs);
TwoPulses.Main(null);
Assert.AreEqual("273", ConsoleAdapter.ReadLine());
}
[TestCase(1, 1)]
[TestCase(3, 5)]
[TestCase(5, 9)]
[TestCase(7, 13)]
[TestCase(42 - 1, 81)]
public void WhenPulseIsInTheMiddle(int size, int expected)
{
var inputs = new List<string>();
inputs.Add($"{size} {size}");
StringBuilder builder = new StringBuilder(size);
var half = size / 2;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (i == half || j == half)
{
builder.Append("G");
}
else
{
builder.Append("B");
}
}
var line = builder.ToString();
Console.WriteLine(line);
inputs.Add(line);
builder.Clear();
}
ConsoleAdapterMocker.InitializeAdapter(false);
ConsoleAdapterMocker.Write(inputs);
TwoPulses.Main(null);
Assert.AreEqual($"{expected}", ConsoleAdapter.ReadLine());
}
[TestCase(1, 1)]
[TestCase(3, 1)]
[TestCase(5, 5)]
[TestCase(7, 9)]
[TestCase(42 - 1, 77)]
public void WhenPulseIsValidButNotInTheMiddle(int size, int expected)
{
var inputs = new List<string>();
inputs.Add($"{size} {size}");
StringBuilder builder = new StringBuilder(size);
var half = size / 2;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (i == half || j == half - 1)
{
builder.Append("G");
}
else
{
builder.Append("B");
}
}
var line = builder.ToString();
Console.WriteLine(line);
inputs.Add(line);
builder.Clear();
}
ConsoleAdapterMocker.InitializeAdapter(false);
ConsoleAdapterMocker.Write(inputs);
TwoPulses.Main(null);
Assert.AreEqual($"{expected}", ConsoleAdapter.ReadLine());
}
}
}
| |
//
// ImageHandler.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// 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;
using System.Collections.Generic;
using Xwt.CairoBackend;
using System.Linq;
namespace Xwt.GtkBackend
{
public class ImageHandler: ImageBackendHandler
{
public override object LoadFromFile (string file)
{
return new GtkImage (new Gdk.Pixbuf (file));
}
public override object LoadFromStream (System.IO.Stream stream)
{
using (Gdk.PixbufLoader loader = new Gdk.PixbufLoader (stream))
return new GtkImage (loader.Pixbuf);
}
public override void SaveToStream (object backend, System.IO.Stream stream, ImageFileType fileType)
{
var pix = (GtkImage)backend;
var buffer = pix.Frames[0].Pixbuf.SaveToBuffer (GetFileType (fileType));
stream.Write (buffer, 0, buffer.Length);
}
public override object CreateCustomDrawn (ImageDrawCallback drawCallback)
{
return new GtkImage (drawCallback);
}
public override object CreateMultiResolutionImage (IEnumerable<object> images)
{
var refImg = (GtkImage) images.First ();
var f = refImg.Frames [0];
var frames = images.Cast<GtkImage> ().Select (img => new GtkImage.ImageFrame (img.Frames[0].Pixbuf, f.Width, f.Height, true));
return new GtkImage (frames);
}
public override object CreateMultiSizeIcon (IEnumerable<object> images)
{
var frames = images.Cast<GtkImage> ().SelectMany (img => img.Frames);
return new GtkImage (frames);
}
string GetFileType (ImageFileType type)
{
switch (type) {
case ImageFileType.Bmp:
return "bmp";
case ImageFileType.Jpeg:
return "jpeg";
case ImageFileType.Png:
return "png";
default:
throw new NotSupportedException ();
}
}
public override Image GetStockIcon (string id)
{
return ApplicationContext.Toolkit.WrapImage (Util.ToGtkStock (id));
}
public override void SetBitmapPixel (object handle, int x, int y, Xwt.Drawing.Color color)
{
var pix = ((GtkImage)handle).Frames[0].Pixbuf;
unsafe {
byte* p = (byte*) pix.Pixels;
p += y * pix.Rowstride + x * pix.NChannels;
p[0] = (byte)(color.Red * 255);
p[1] = (byte)(color.Green * 255);
p[2] = (byte)(color.Blue * 255);
p[3] = (byte)(color.Alpha * 255);
}
}
public override Xwt.Drawing.Color GetBitmapPixel (object handle, int x, int y)
{
var pix = ((GtkImage)handle).Frames[0].Pixbuf;
unsafe {
byte* p = (byte*) pix.Pixels;
p += y * pix.Rowstride + x * pix.NChannels;
return Xwt.Drawing.Color.FromBytes (p[0], p[1], p[2], p[3]);
}
}
public override void Dispose (object backend)
{
((GtkImage)backend).Dispose ();
}
public override bool HasMultipleSizes (object handle)
{
return ((GtkImage)handle).HasMultipleSizes;
}
public override Size GetSize (object handle)
{
var pix = handle as GtkImage;
return pix.DefaultSize;
}
public override object CopyBitmap (object handle)
{
var pix = ((GtkImage)handle).Frames[0].Pixbuf;
return new GtkImage (pix.Copy ());
}
public override void CopyBitmapArea (object srcHandle, int srcX, int srcY, int width, int height, object destHandle, int destX, int destY)
{
var pixSrc = ((GtkImage)srcHandle).Frames[0].Pixbuf;
var pixDst = ((GtkImage)destHandle).Frames[0].Pixbuf;
pixSrc.CopyArea (srcX, srcY, width, height, pixDst, destX, destY);
}
public override object CropBitmap (object handle, int srcX, int srcY, int width, int height)
{
var pix = ((GtkImage)handle).Frames[0].Pixbuf;
Gdk.Pixbuf res = new Gdk.Pixbuf (pix.Colorspace, pix.HasAlpha, pix.BitsPerSample, width, height);
res.Fill (0);
pix.CopyArea (srcX, srcY, width, height, res, 0, 0);
return new GtkImage (res);
}
public override bool IsBitmap (object handle)
{
var img = (GtkImage) handle;
return !img.HasMultipleSizes;
}
public override object ConvertToBitmap (object handle, double width, double height, double scaleFactor, ImageFormat format)
{
var img = (GtkImage) handle;
var f = new GtkImage.ImageFrame (img.GetBestFrame (ApplicationContext, scaleFactor, width, height, true), (int)width, (int)height, true);
return new GtkImage (new GtkImage.ImageFrame [] { f });
}
internal static Gdk.Pixbuf CreateBitmap (string stockId, double width, double height, double scaleFactor)
{
Gdk.Pixbuf result = null;
Gtk.IconSet iconset = Gtk.IconFactory.LookupDefault (stockId);
if (iconset != null) {
// Find the size that better fits the requested size
Gtk.IconSize gsize = Util.GetBestSizeFit (width);
result = iconset.RenderIcon (Gtk.Widget.DefaultStyle, Gtk.TextDirection.Ltr, Gtk.StateType.Normal, gsize, null, null, scaleFactor);
if (result == null || result.Width < width * scaleFactor) {
var gsize2x = Util.GetBestSizeFit (width * scaleFactor, iconset.Sizes);
if (gsize2x != Gtk.IconSize.Invalid && gsize2x != gsize)
// Don't dispose the previous result since the icon is owned by the IconSet
result = iconset.RenderIcon (Gtk.Widget.DefaultStyle, Gtk.TextDirection.Ltr, Gtk.StateType.Normal, gsize2x, null, null);
}
}
if (result == null && Gtk.IconTheme.Default.HasIcon (stockId))
result = Gtk.IconTheme.Default.LoadIcon (stockId, (int)width, (Gtk.IconLookupFlags)0);
if (result == null) {
return CreateBitmap (Gtk.Stock.MissingImage, width, height, scaleFactor);
}
return result;
}
}
public class GtkImage: IDisposable
{
public class ImageFrame {
public Gdk.Pixbuf Pixbuf { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; }
public double Scale { get; set; }
public bool Owned { get; set; }
public ImageFrame (Gdk.Pixbuf pix, bool owned) {
Pixbuf = pix;
Width = pix.Width;
Height = pix.Height;
Scale = 1;
Owned = owned;
}
public ImageFrame (Gdk.Pixbuf pix, int width, int height, bool owned) {
Pixbuf = pix;
Width = width;
Height = height;
Scale = (double)pix.Width / (double) width;
Owned = owned;
}
public void Dispose () {
if (Owned)
Pixbuf.Dispose ();
}
}
ImageFrame[] frames;
ImageDrawCallback drawCallback;
string stockId;
public ImageFrame[] Frames {
get { return frames; }
}
public GtkImage (Gdk.Pixbuf img)
{
this.frames = new ImageFrame [] { new ImageFrame (img, true) };
}
public GtkImage (string stockId)
{
this.stockId = stockId;
}
public GtkImage (IEnumerable<Gdk.Pixbuf> frames)
{
this.frames = frames.Select (p => new ImageFrame (p, true)).ToArray ();
}
public GtkImage (IEnumerable<ImageFrame> frames)
{
this.frames = frames.ToArray ();
}
public GtkImage (ImageDrawCallback drawCallback)
{
this.drawCallback = drawCallback;
}
public void Dispose ()
{
if (frames != null) {
foreach (var f in frames)
f.Dispose ();
}
}
public Size DefaultSize {
get {
if (frames != null)
return new Size (frames[0].Pixbuf.Width, frames[0].Pixbuf.Height);
else
return new Size (16, 16);
}
}
public bool HasMultipleSizes {
get { return frames != null && frames.Length > 1 || drawCallback != null || stockId != null; }
}
Gdk.Pixbuf FindFrame (int width, int height, double scaleFactor)
{
if (frames == null)
return null;
if (frames.Length == 1)
return frames [0].Pixbuf;
Gdk.Pixbuf best = null;
int bestSizeMatch = 0;
double bestResolutionMatch = 0;
foreach (var f in frames) {
int sizeMatch;
if (f.Width == width && f.Height == height) {
if (f.Scale == scaleFactor)
return f.Pixbuf; // Exact match
sizeMatch = 2; // Exact size
}
else if (f.Width >= width && f.Height >= height)
sizeMatch = 1; // Bigger size
else
sizeMatch = 0; // Smaller size
var resolutionMatch = ((double)f.Pixbuf.Width * (double)f.Pixbuf.Height) / ((double)width * (double)height * scaleFactor);
if ( best == null ||
(bestResolutionMatch < 1 && resolutionMatch > bestResolutionMatch) ||
(bestResolutionMatch >= 1 && resolutionMatch >= 1 && resolutionMatch <= bestResolutionMatch && (sizeMatch >= bestSizeMatch)))
{
best = f.Pixbuf;
bestSizeMatch = sizeMatch;
bestResolutionMatch = resolutionMatch;
}
}
return best;
}
public Gdk.Pixbuf ToPixbuf (ApplicationContext actx, double width, double height)
{
return GetBestFrame (actx, 1, width, height, true);
}
public Gdk.Pixbuf ToPixbuf (ApplicationContext actx, Gtk.Widget w)
{
return GetBestFrame (actx, Util.GetScaleFactor (w), DefaultSize.Width, DefaultSize.Height, true);
}
public Gdk.Pixbuf GetBestFrame (ApplicationContext actx, Gtk.Widget w, double width, double height, bool forceExactSize)
{
return GetBestFrame (actx, Util.GetScaleFactor (w), width, height, forceExactSize);
}
public Gdk.Pixbuf GetBestFrame (ApplicationContext actx, double scaleFactor, double width, double height, bool forceExactSize)
{
var f = FindFrame ((int)width, (int)height, scaleFactor);
if (f == null || (forceExactSize && (f.Width != (int)width || f.Height != (int)height)))
return RenderFrame (actx, scaleFactor, width, height);
else
return f;
}
Gdk.Pixbuf RenderFrame (ApplicationContext actx, double scaleFactor, double width, double height)
{
var swidth = Math.Max ((int)(width * scaleFactor), 1);
var sheight = Math.Max ((int)(height * scaleFactor), 1);
using (var sf = new Cairo.ImageSurface (Cairo.Format.ARGB32, swidth, sheight))
using (var ctx = new Cairo.Context (sf)) {
ImageDescription idesc = new ImageDescription () {
Alpha = 1,
Size = new Size (width, height)
};
ctx.Scale (scaleFactor, scaleFactor);
Draw (actx, ctx, scaleFactor, 0, 0, idesc);
var f = new ImageFrame (ImageBuilderBackend.CreatePixbuf (sf), Math.Max((int)width,1), Math.Max((int)height,1), true);
AddFrame (f);
return f.Pixbuf;
}
}
void AddFrame (ImageFrame frame)
{
if (frames == null)
frames = new ImageFrame[] { frame };
else {
Array.Resize (ref frames, frames.Length + 1);
frames [frames.Length - 1] = frame;
}
}
public void Draw (ApplicationContext actx, Cairo.Context ctx, double scaleFactor, double x, double y, ImageDescription idesc)
{
if (stockId != null) {
ImageFrame frame = null;
if (frames != null)
frame = frames.FirstOrDefault (f => f.Width == (int) idesc.Size.Width && f.Height == (int) idesc.Size.Height && f.Scale == scaleFactor);
if (frame == null) {
frame = new ImageFrame (ImageHandler.CreateBitmap (stockId, idesc.Size.Width, idesc.Size.Height, scaleFactor), (int)idesc.Size.Width, (int)idesc.Size.Height, false);
frame.Scale = scaleFactor;
AddFrame (frame);
}
DrawPixbuf (ctx, frame.Pixbuf, x, y, idesc);
}
else if (drawCallback != null) {
CairoContextBackend c = new CairoContextBackend (scaleFactor) {
Context = ctx
};
if (actx != null) {
actx.InvokeUserCode (delegate {
drawCallback (c, new Rectangle (x, y, idesc.Size.Width, idesc.Size.Height));
});
} else
drawCallback (c, new Rectangle (x, y, idesc.Size.Width, idesc.Size.Height));
}
else {
DrawPixbuf (ctx, GetBestFrame (actx, scaleFactor, idesc.Size.Width, idesc.Size.Height, false), x, y, idesc);
}
}
void DrawPixbuf (Cairo.Context ctx, Gdk.Pixbuf img, double x, double y, ImageDescription idesc)
{
ctx.Save ();
ctx.Translate (x, y);
ctx.Scale (idesc.Size.Width / (double)img.Width, idesc.Size.Height / (double)img.Height);
Gdk.CairoHelper.SetSourcePixbuf (ctx, img, 0, 0);
#pragma warning disable 618
using (var pattern = ctx.Source as Cairo.SurfacePattern) {
if (pattern != null) {
if (idesc.Size.Width > img.Width || idesc.Size.Height > img.Height) {
// Fixes blur issue when rendering on an image surface
pattern.Filter = Cairo.Filter.Fast;
} else
pattern.Filter = Cairo.Filter.Good;
}
}
#pragma warning restore 618
if (idesc.Alpha >= 1)
ctx.Paint ();
else
ctx.PaintWithAlpha (idesc.Alpha);
ctx.Restore ();
}
}
public class ImageBox: GtkDrawingArea
{
ImageDescription image;
ApplicationContext actx;
float yalign = 0.5f, xalign = 0.5f;
public ImageBox (ApplicationContext actx, ImageDescription img): this (actx)
{
Image = img;
}
public ImageBox (ApplicationContext actx)
{
this.SetHasWindow (false);
this.SetAppPaintable (true);
this.actx = actx;
}
public ImageDescription Image {
get { return image; }
set {
image = value;
SetSizeRequest ((int)image.Size.Width, (int)image.Size.Height);
QueueResize ();
}
}
public float Yalign {
get { return yalign; }
set { yalign = value; QueueDraw (); }
}
public float Xalign {
get { return xalign; }
set { xalign = value; QueueDraw (); }
}
protected override void OnSizeRequested (ref Gtk.Requisition requisition)
{
base.OnSizeRequested (ref requisition);
if (!image.IsNull) {
requisition.Width = (int) image.Size.Width;
requisition.Height = (int) image.Size.Height;
}
}
protected override bool OnDrawn (Cairo.Context cr)
{
if (image.IsNull)
return true;
int x = (int)(((float)Allocation.Width - (float)image.Size.Width) * xalign);
int y = (int)(((float)Allocation.Height - (float)image.Size.Height) * yalign);
if (x < 0) x = 0;
if (y < 0) y = 0;
((GtkImage)image.Backend).Draw (actx, cr, Util.GetScaleFactor (this), x, y, image);
return base.OnDrawn (cr);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// This RegexWriter class is internal to the Regex package.
// It builds a block of regular expression codes (RegexCode)
// from a RegexTree parse tree.
// Implementation notes:
//
// This step is as simple as walking the tree and emitting
// sequences of codes.
//
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace System.Text.RegularExpressions
{
internal ref struct RegexWriter
{
private const int BeforeChild = 64;
private const int AfterChild = 128;
// Distribution of common patterns indicates an average amount of 56 op codes.
private const int EmittedSize = 56;
private const int IntStackSize = 32;
private ValueListBuilder<int> _emitted;
private ValueListBuilder<int> _intStack;
private readonly Dictionary<string, int> _stringHash;
private readonly List<string> _stringTable;
private Hashtable _caps;
private int _trackCount;
private RegexWriter(Span<int> emittedSpan, Span<int> intStackSpan)
{
_emitted = new ValueListBuilder<int>(emittedSpan);
_intStack = new ValueListBuilder<int>(intStackSpan);
_stringHash = new Dictionary<string, int>();
_stringTable = new List<string>();
_caps = null;
_trackCount = 0;
}
/// <summary>
/// This is the only function that should be called from outside.
/// It takes a RegexTree and creates a corresponding RegexCode.
/// </summary>
internal static RegexCode Write(RegexTree t)
{
Span<int> emittedSpan = stackalloc int[EmittedSize];
Span<int> intStackSpan = stackalloc int[IntStackSize];
var w = new RegexWriter(emittedSpan, intStackSpan);
RegexCode retval = w.RegexCodeFromRegexTree(t);
#if DEBUG
if (t.Debug)
{
t.Dump();
retval.Dump();
}
#endif
return retval;
}
/// <summary>
/// The top level RegexCode generator. It does a depth-first walk
/// through the tree and calls EmitFragment to emits code before
/// and after each child of an interior node, and at each leaf.
/// </summary>
private RegexCode RegexCodeFromRegexTree(RegexTree tree)
{
// construct sparse capnum mapping if some numbers are unused
int capsize;
if (tree._capnumlist == null || tree._captop == tree._capnumlist.Length)
{
capsize = tree._captop;
_caps = null;
}
else
{
capsize = tree._capnumlist.Length;
_caps = tree._caps;
for (int i = 0; i < tree._capnumlist.Length; i++)
_caps[tree._capnumlist[i]] = i;
}
RegexNode curNode = tree._root;
int curChild = 0;
Emit(RegexCode.Lazybranch, 0);
for (; ; )
{
if (curNode._children == null)
{
EmitFragment(curNode._type, curNode, 0);
}
else if (curChild < curNode._children.Count)
{
EmitFragment(curNode._type | BeforeChild, curNode, curChild);
curNode = curNode._children[curChild];
_intStack.Append(curChild);
curChild = 0;
continue;
}
if (_intStack.Length == 0)
break;
curChild = _intStack.Pop();
curNode = curNode._next;
EmitFragment(curNode._type | AfterChild, curNode, curChild);
curChild++;
}
PatchJump(0, _emitted.Length);
Emit(RegexCode.Stop);
RegexPrefix fcPrefix = RegexFCD.FirstChars(tree);
RegexPrefix prefix = RegexFCD.Prefix(tree);
bool rtl = ((tree._options & RegexOptions.RightToLeft) != 0);
CultureInfo culture = (tree._options & RegexOptions.CultureInvariant) != 0 ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture;
RegexBoyerMoore bmPrefix;
if (prefix != null && prefix.Prefix.Length > 0)
bmPrefix = new RegexBoyerMoore(prefix.Prefix, prefix.CaseInsensitive, rtl, culture);
else
bmPrefix = null;
int anchors = RegexFCD.Anchors(tree);
int[] emitted = _emitted.AsSpan().ToArray();
// Cleaning up and returning the borrowed arrays
_emitted.Dispose();
_intStack.Dispose();
return new RegexCode(emitted, _stringTable, _trackCount, _caps, capsize, bmPrefix, fcPrefix, anchors, rtl);
}
/// <summary>
/// Fixes up a jump instruction at the specified offset
/// so that it jumps to the specified jumpDest.
/// </summary>
private void PatchJump(int offset, int jumpDest)
{
_emitted[offset + 1] = jumpDest;
}
/// <summary>
/// Emits a zero-argument operation. Note that the emit
/// functions all run in two modes: they can emit code, or
/// they can just count the size of the code.
/// </summary>
private void Emit(int op)
{
if (RegexCode.OpcodeBacktracks(op))
_trackCount++;
_emitted.Append(op);
}
/// <summary>
/// Emits a one-argument operation.
/// </summary>
private void Emit(int op, int opd1)
{
if (RegexCode.OpcodeBacktracks(op))
_trackCount++;
_emitted.Append(op);
_emitted.Append(opd1);
}
/// <summary>
/// Emits a two-argument operation.
/// </summary>
private void Emit(int op, int opd1, int opd2)
{
if (RegexCode.OpcodeBacktracks(op))
_trackCount++;
_emitted.Append(op);
_emitted.Append(opd1);
_emitted.Append(opd2);
}
/// <summary>
/// Returns an index in the string table for a string;
/// uses a hashtable to eliminate duplicates.
/// </summary>
private int StringCode(string str)
{
if (str == null)
str = string.Empty;
int i;
if (!_stringHash.TryGetValue(str, out i))
{
i = _stringTable.Count;
_stringHash[str] = i;
_stringTable.Add(str);
}
return i;
}
/// <summary>
/// When generating code on a regex that uses a sparse set
/// of capture slots, we hash them to a dense set of indices
/// for an array of capture slots. Instead of doing the hash
/// at match time, it's done at compile time, here.
/// </summary>
private int MapCapnum(int capnum)
{
if (capnum == -1)
return -1;
if (_caps != null)
return (int)_caps[capnum];
else
return capnum;
}
/// <summary>
/// The main RegexCode generator. It does a depth-first walk
/// through the tree and calls EmitFragment to emits code before
/// and after each child of an interior node, and at each leaf.
/// </summary>
private void EmitFragment(int nodetype, RegexNode node, int curIndex)
{
int bits = 0;
if (nodetype <= RegexNode.Ref)
{
if (node.UseOptionR())
bits |= RegexCode.Rtl;
if ((node._options & RegexOptions.IgnoreCase) != 0)
bits |= RegexCode.Ci;
}
switch (nodetype)
{
case RegexNode.Concatenate | BeforeChild:
case RegexNode.Concatenate | AfterChild:
case RegexNode.Empty:
break;
case RegexNode.Alternate | BeforeChild:
if (curIndex < node._children.Count - 1)
{
_intStack.Append(_emitted.Length);
Emit(RegexCode.Lazybranch, 0);
}
break;
case RegexNode.Alternate | AfterChild:
{
if (curIndex < node._children.Count - 1)
{
int LBPos = _intStack.Pop();
_intStack.Append(_emitted.Length);
Emit(RegexCode.Goto, 0);
PatchJump(LBPos, _emitted.Length);
}
else
{
int I;
for (I = 0; I < curIndex; I++)
{
PatchJump(_intStack.Pop(), _emitted.Length);
}
}
break;
}
case RegexNode.Testref | BeforeChild:
switch (curIndex)
{
case 0:
Emit(RegexCode.Setjump);
_intStack.Append(_emitted.Length);
Emit(RegexCode.Lazybranch, 0);
Emit(RegexCode.Testref, MapCapnum(node._m));
Emit(RegexCode.Forejump);
break;
}
break;
case RegexNode.Testref | AfterChild:
switch (curIndex)
{
case 0:
{
int Branchpos = _intStack.Pop();
_intStack.Append(_emitted.Length);
Emit(RegexCode.Goto, 0);
PatchJump(Branchpos, _emitted.Length);
Emit(RegexCode.Forejump);
if (node._children.Count > 1)
break;
// else fallthrough
goto case 1;
}
case 1:
PatchJump(_intStack.Pop(), _emitted.Length);
break;
}
break;
case RegexNode.Testgroup | BeforeChild:
switch (curIndex)
{
case 0:
Emit(RegexCode.Setjump);
Emit(RegexCode.Setmark);
_intStack.Append(_emitted.Length);
Emit(RegexCode.Lazybranch, 0);
break;
}
break;
case RegexNode.Testgroup | AfterChild:
switch (curIndex)
{
case 0:
Emit(RegexCode.Getmark);
Emit(RegexCode.Forejump);
break;
case 1:
int Branchpos = _intStack.Pop();
_intStack.Append(_emitted.Length);
Emit(RegexCode.Goto, 0);
PatchJump(Branchpos, _emitted.Length);
Emit(RegexCode.Getmark);
Emit(RegexCode.Forejump);
if (node._children.Count > 2)
break;
// else fallthrough
goto case 2;
case 2:
PatchJump(_intStack.Pop(), _emitted.Length);
break;
}
break;
case RegexNode.Loop | BeforeChild:
case RegexNode.Lazyloop | BeforeChild:
if (node._n < int.MaxValue || node._m > 1)
Emit(node._m == 0 ? RegexCode.Nullcount : RegexCode.Setcount, node._m == 0 ? 0 : 1 - node._m);
else
Emit(node._m == 0 ? RegexCode.Nullmark : RegexCode.Setmark);
if (node._m == 0)
{
_intStack.Append(_emitted.Length);
Emit(RegexCode.Goto, 0);
}
_intStack.Append(_emitted.Length);
break;
case RegexNode.Loop | AfterChild:
case RegexNode.Lazyloop | AfterChild:
{
int StartJumpPos = _emitted.Length;
int Lazy = (nodetype - (RegexNode.Loop | AfterChild));
if (node._n < int.MaxValue || node._m > 1)
Emit(RegexCode.Branchcount + Lazy, _intStack.Pop(), node._n == int.MaxValue ? int.MaxValue : node._n - node._m);
else
Emit(RegexCode.Branchmark + Lazy, _intStack.Pop());
if (node._m == 0)
PatchJump(_intStack.Pop(), StartJumpPos);
}
break;
case RegexNode.Group | BeforeChild:
case RegexNode.Group | AfterChild:
break;
case RegexNode.Capture | BeforeChild:
Emit(RegexCode.Setmark);
break;
case RegexNode.Capture | AfterChild:
Emit(RegexCode.Capturemark, MapCapnum(node._m), MapCapnum(node._n));
break;
case RegexNode.Require | BeforeChild:
// NOTE: the following line causes lookahead/lookbehind to be
// NON-BACKTRACKING. It can be commented out with (*)
Emit(RegexCode.Setjump);
Emit(RegexCode.Setmark);
break;
case RegexNode.Require | AfterChild:
Emit(RegexCode.Getmark);
// NOTE: the following line causes lookahead/lookbehind to be
// NON-BACKTRACKING. It can be commented out with (*)
Emit(RegexCode.Forejump);
break;
case RegexNode.Prevent | BeforeChild:
Emit(RegexCode.Setjump);
_intStack.Append(_emitted.Length);
Emit(RegexCode.Lazybranch, 0);
break;
case RegexNode.Prevent | AfterChild:
Emit(RegexCode.Backjump);
PatchJump(_intStack.Pop(), _emitted.Length);
Emit(RegexCode.Forejump);
break;
case RegexNode.Greedy | BeforeChild:
Emit(RegexCode.Setjump);
break;
case RegexNode.Greedy | AfterChild:
Emit(RegexCode.Forejump);
break;
case RegexNode.One:
case RegexNode.Notone:
Emit(node._type | bits, node._ch);
break;
case RegexNode.Notoneloop:
case RegexNode.Notonelazy:
case RegexNode.Oneloop:
case RegexNode.Onelazy:
if (node._m > 0)
Emit(((node._type == RegexNode.Oneloop || node._type == RegexNode.Onelazy) ?
RegexCode.Onerep : RegexCode.Notonerep) | bits, node._ch, node._m);
if (node._n > node._m)
Emit(node._type | bits, node._ch, node._n == int.MaxValue ?
int.MaxValue : node._n - node._m);
break;
case RegexNode.Setloop:
case RegexNode.Setlazy:
if (node._m > 0)
Emit(RegexCode.Setrep | bits, StringCode(node._str), node._m);
if (node._n > node._m)
Emit(node._type | bits, StringCode(node._str),
(node._n == int.MaxValue) ? int.MaxValue : node._n - node._m);
break;
case RegexNode.Multi:
Emit(node._type | bits, StringCode(node._str));
break;
case RegexNode.Set:
Emit(node._type | bits, StringCode(node._str));
break;
case RegexNode.Ref:
Emit(node._type | bits, MapCapnum(node._m));
break;
case RegexNode.Nothing:
case RegexNode.Bol:
case RegexNode.Eol:
case RegexNode.Boundary:
case RegexNode.Nonboundary:
case RegexNode.ECMABoundary:
case RegexNode.NonECMABoundary:
case RegexNode.Beginning:
case RegexNode.Start:
case RegexNode.EndZ:
case RegexNode.End:
Emit(node._type);
break;
default:
throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, nodetype.ToString(CultureInfo.CurrentCulture)));
}
}
}
}
| |
// 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.Reflection;
using Internal.Metadata.NativeFormat;
using System.Threading;
using Debug = System.Diagnostics.Debug;
using Internal.TypeSystem;
using Internal.NativeFormat;
namespace Internal.TypeSystem.NativeFormat
{
/// <summary>
/// Override of MetadataType that uses actual NativeFormat335 metadata.
/// </summary>
public sealed partial class NativeFormatType : MetadataType, NativeFormatMetadataUnit.IHandleObject
{
private static readonly LowLevelDictionary<string, TypeFlags> s_primitiveTypes = InitPrimitiveTypesDictionary();
private static LowLevelDictionary<string, TypeFlags> InitPrimitiveTypesDictionary()
{
LowLevelDictionary<string, TypeFlags> result = new LowLevelDictionary<string, TypeFlags>();
result.Add("Void", TypeFlags.Void);
result.Add("Boolean", TypeFlags.Boolean);
result.Add("Char", TypeFlags.Char);
result.Add("SByte", TypeFlags.SByte);
result.Add("Byte", TypeFlags.Byte);
result.Add("Int16", TypeFlags.Int16);
result.Add("UInt16", TypeFlags.UInt16);
result.Add("Int32", TypeFlags.Int32);
result.Add("UInt32", TypeFlags.UInt32);
result.Add("Int64", TypeFlags.Int64);
result.Add("UInt64", TypeFlags.UInt64);
result.Add("IntPtr", TypeFlags.IntPtr);
result.Add("UIntPtr", TypeFlags.UIntPtr);
result.Add("Single", TypeFlags.Single);
result.Add("Double", TypeFlags.Double);
return result;
}
private NativeFormatModule _module;
private NativeFormatMetadataUnit _metadataUnit;
private TypeDefinitionHandle _handle;
private TypeDefinition _typeDefinition;
// Cached values
private string _typeName;
private string _typeNamespace;
private TypeDesc[] _genericParameters;
private MetadataType _baseType;
private int _hashcode;
internal NativeFormatType(NativeFormatMetadataUnit metadataUnit, TypeDefinitionHandle handle)
{
_handle = handle;
_metadataUnit = metadataUnit;
_typeDefinition = metadataUnit.MetadataReader.GetTypeDefinition(handle);
_module = metadataUnit.GetModuleFromNamespaceDefinition(_typeDefinition.NamespaceDefinition);
_baseType = this; // Not yet initialized flag
#if DEBUG
// Initialize name eagerly in debug builds for convenience
this.ToString();
#endif
}
public override int GetHashCode()
{
if (_hashcode != 0)
{
return _hashcode;
}
int nameHash = TypeHashingAlgorithms.ComputeNameHashCode(this.GetFullName());
TypeDesc containingType = ContainingType;
if (containingType == null)
{
_hashcode = nameHash;
}
else
{
_hashcode = TypeHashingAlgorithms.ComputeNestedTypeHashCode(containingType.GetHashCode(), nameHash);
}
return _hashcode;
}
Handle NativeFormatMetadataUnit.IHandleObject.Handle
{
get
{
return _handle;
}
}
NativeFormatType NativeFormatMetadataUnit.IHandleObject.Container
{
get
{
return null;
}
}
// TODO: Use stable hashcode based on the type name?
// public override int GetHashCode()
// {
// }
public override TypeSystemContext Context
{
get
{
return _module.Context;
}
}
private void ComputeGenericParameters()
{
var genericParameterHandles = _typeDefinition.GenericParameters;
int count = genericParameterHandles.Count;
if (count > 0)
{
TypeDesc[] genericParameters = new TypeDesc[count];
int i = 0;
foreach (var genericParameterHandle in genericParameterHandles)
{
genericParameters[i++] = new NativeFormatGenericParameter(_metadataUnit, genericParameterHandle);
}
Interlocked.CompareExchange(ref _genericParameters, genericParameters, null);
}
else
{
_genericParameters = TypeDesc.EmptyTypes;
}
}
public override Instantiation Instantiation
{
get
{
if (_genericParameters == null)
ComputeGenericParameters();
return new Instantiation(_genericParameters);
}
}
public override ModuleDesc Module
{
get
{
return _module;
}
}
public NativeFormatModule NativeFormatModule
{
get
{
return _module;
}
}
public MetadataReader MetadataReader
{
get
{
return _metadataUnit.MetadataReader;
}
}
public NativeFormatMetadataUnit MetadataUnit
{
get
{
return _metadataUnit;
}
}
public TypeDefinitionHandle Handle
{
get
{
return _handle;
}
}
private MetadataType InitializeBaseType()
{
var baseTypeHandle = _typeDefinition.BaseType;
if (baseTypeHandle.IsNull(MetadataReader))
{
_baseType = null;
return null;
}
var type = _metadataUnit.GetType(baseTypeHandle) as MetadataType;
if (type == null)
{
throw new BadImageFormatException();
}
_baseType = type;
return type;
}
public override DefType BaseType
{
get
{
if (_baseType == this)
return InitializeBaseType();
return _baseType;
}
}
public override MetadataType MetadataBaseType
{
get
{
if (_baseType == this)
return InitializeBaseType();
return _baseType;
}
}
protected override TypeFlags ComputeTypeFlags(TypeFlags mask)
{
TypeFlags flags = 0;
if ((mask & TypeFlags.CategoryMask) != 0 && (flags & TypeFlags.CategoryMask) == 0)
{
TypeDesc baseType = this.BaseType;
if (baseType != null && baseType.IsWellKnownType(WellKnownType.ValueType) &&
!this.IsWellKnownType(WellKnownType.Enum))
{
TypeFlags categoryFlags;
if (!TryGetCategoryFlagsForPrimitiveType(out categoryFlags))
{
categoryFlags = TypeFlags.ValueType;
}
flags |= categoryFlags;
}
else
if (baseType != null && baseType.IsWellKnownType(WellKnownType.Enum))
{
flags |= TypeFlags.Enum;
}
else
{
if ((_typeDefinition.Flags & TypeAttributes.Interface) != 0)
flags |= TypeFlags.Interface;
else
flags |= TypeFlags.Class;
}
// All other cases are handled during TypeSystemContext intitialization
}
if ((mask & TypeFlags.HasGenericVarianceComputed) != 0 &&
(flags & TypeFlags.HasGenericVarianceComputed) == 0)
{
flags |= TypeFlags.HasGenericVarianceComputed;
foreach (GenericParameterDesc genericParam in Instantiation)
{
if (genericParam.Variance != GenericVariance.None)
{
flags |= TypeFlags.HasGenericVariance;
break;
}
}
}
return flags;
}
private bool TryGetCategoryFlagsForPrimitiveType(out TypeFlags categoryFlags)
{
categoryFlags = 0;
if (_module != _metadataUnit.Context.SystemModule)
{
// Primitive types reside in the system module
return false;
}
NamespaceDefinition namespaceDef = MetadataReader.GetNamespaceDefinition(_typeDefinition.NamespaceDefinition);
if (namespaceDef.ParentScopeOrNamespace.HandleType != HandleType.NamespaceDefinition)
{
// Primitive types are in the System namespace the parent of which is the root namespace
return false;
}
if (!namespaceDef.Name.StringEquals("System", MetadataReader))
{
// Namespace name must be 'System'
return false;
}
NamespaceDefinitionHandle parentNamespaceDefHandle =
namespaceDef.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(MetadataReader);
NamespaceDefinition parentDef = MetadataReader.GetNamespaceDefinition(parentNamespaceDefHandle);
if (parentDef.ParentScopeOrNamespace.HandleType != HandleType.ScopeDefinition)
{
// The root parent namespace should have scope (assembly) handle as its parent
return false;
}
return s_primitiveTypes.TryGetValue(Name, out categoryFlags);
}
private string InitializeName()
{
var metadataReader = this.MetadataReader;
_typeName = metadataReader.GetString(_typeDefinition.Name);
return _typeName;
}
public override string Name
{
get
{
if (_typeName == null)
return InitializeName();
return _typeName;
}
}
private string InitializeNamespace()
{
if (ContainingType == null)
{
var metadataReader = this.MetadataReader;
_typeNamespace = metadataReader.GetNamespaceName(_typeDefinition.NamespaceDefinition);
return _typeNamespace;
}
else
{
_typeNamespace = "";
return _typeNamespace;
}
}
public override string Namespace
{
get
{
if (_typeNamespace == null)
return InitializeNamespace();
return _typeNamespace;
}
}
public override IEnumerable<MethodDesc> GetMethods()
{
foreach (var handle in _typeDefinition.Methods)
{
yield return (MethodDesc)_metadataUnit.GetMethod(handle, this);
}
}
public override MethodDesc GetMethod(string name, MethodSignature signature)
{
var metadataReader = this.MetadataReader;
foreach (var handle in _typeDefinition.Methods)
{
if (metadataReader.GetMethod(handle).Name.StringEquals(name, metadataReader))
{
MethodDesc method = (MethodDesc)_metadataUnit.GetMethod(handle, this);
if (signature == null || signature.Equals(method.Signature))
return method;
}
}
return null;
}
public override MethodDesc GetStaticConstructor()
{
var metadataReader = this.MetadataReader;
foreach (var handle in _typeDefinition.Methods)
{
var methodDefinition = metadataReader.GetMethod(handle);
if (methodDefinition.Flags.IsRuntimeSpecialName() &&
methodDefinition.Name.StringEquals(".cctor", metadataReader))
{
MethodDesc method = (MethodDesc)_metadataUnit.GetMethod(handle, this);
return method;
}
}
return null;
}
public override MethodDesc GetDefaultConstructor()
{
if (IsAbstract)
return null;
MetadataReader metadataReader = this.MetadataReader;
foreach (var handle in _typeDefinition.Methods)
{
var methodDefinition = metadataReader.GetMethod(handle);
MethodAttributes attributes = methodDefinition.Flags;
if (attributes.IsRuntimeSpecialName() && attributes.IsPublic() &&
methodDefinition.Name.StringEquals(".ctor", metadataReader))
{
MethodDesc method = (MethodDesc)_metadataUnit.GetMethod(handle, this);
if (method.Signature.Length != 0)
continue;
return method;
}
}
return null;
}
public override MethodDesc GetFinalizer()
{
// System.Object defines Finalize but doesn't use it, so we can determine that a type has a Finalizer
// by checking for a virtual method override that lands anywhere other than Object in the inheritance
// chain.
if (!HasBaseType)
return null;
TypeDesc objectType = Context.GetWellKnownType(WellKnownType.Object);
MethodDesc decl = objectType.GetMethod("Finalize", null);
if (decl != null)
{
MethodDesc impl = this.FindVirtualFunctionTargetMethodOnObjectType(decl);
if (impl == null)
{
// TODO: invalid input: the type doesn't derive from our System.Object
throw new TypeLoadException(this.GetFullName());
}
if (impl.OwningType != objectType)
{
return impl;
}
return null;
}
// TODO: Better exception type. Should be: "CoreLib doesn't have a required thing in it".
throw new NotImplementedException();
}
public override IEnumerable<FieldDesc> GetFields()
{
foreach (var handle in _typeDefinition.Fields)
{
yield return _metadataUnit.GetField(handle, this);
}
}
public override FieldDesc GetField(string name)
{
var metadataReader = this.MetadataReader;
foreach (var handle in _typeDefinition.Fields)
{
if (metadataReader.GetField(handle).Name.StringEquals(name, metadataReader))
{
return _metadataUnit.GetField(handle, this);
}
}
return null;
}
public override IEnumerable<MetadataType> GetNestedTypes()
{
foreach (var handle in _typeDefinition.NestedTypes)
{
yield return (MetadataType)_metadataUnit.GetType(handle);
}
}
public override MetadataType GetNestedType(string name)
{
var metadataReader = this.MetadataReader;
foreach (var handle in _typeDefinition.NestedTypes)
{
if (metadataReader.GetTypeDefinition(handle).Name.StringEquals(name, metadataReader))
return (MetadataType)_metadataUnit.GetType(handle);
}
return null;
}
public TypeAttributes Attributes
{
get
{
return _typeDefinition.Flags;
}
}
//
// ContainingType of nested type
//
public override DefType ContainingType
{
get
{
var handle = _typeDefinition.EnclosingType;
if (handle.IsNull(MetadataReader))
return null;
return (DefType)_metadataUnit.GetType(handle);
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return MetadataReader.HasCustomAttribute(_typeDefinition.CustomAttributes,
attributeNamespace, attributeName);
}
public override string ToString()
{
return "[" + NativeFormatModule.GetName().Name + "]" + this.GetFullName();
}
public override ClassLayoutMetadata GetClassLayout()
{
ClassLayoutMetadata result;
result.PackingSize = checked((int)_typeDefinition.PackingSize);
result.Size = checked((int)_typeDefinition.Size);
// Skip reading field offsets if this is not explicit layout
if (IsExplicitLayout)
{
var fieldDefinitionHandles = _typeDefinition.Fields;
var numInstanceFields = 0;
foreach (var handle in fieldDefinitionHandles)
{
var fieldDefinition = MetadataReader.GetField(handle);
if ((fieldDefinition.Flags & FieldAttributes.Static) != 0)
continue;
numInstanceFields++;
}
result.Offsets = new FieldAndOffset[numInstanceFields];
int index = 0;
foreach (var handle in fieldDefinitionHandles)
{
var fieldDefinition = MetadataReader.GetField(handle);
if ((fieldDefinition.Flags & FieldAttributes.Static) != 0)
continue;
// Note: GetOffset() returns -1 when offset was not set in the metadata
int fieldOffsetInMetadata = (int)fieldDefinition.Offset;
LayoutInt fieldOffset = fieldOffsetInMetadata == -1 ? FieldAndOffset.InvalidOffset : new LayoutInt(fieldOffsetInMetadata);
result.Offsets[index] =
new FieldAndOffset(_metadataUnit.GetField(handle, this), fieldOffset);
index++;
}
}
else
result.Offsets = null;
return result;
}
public override bool IsExplicitLayout
{
get
{
return (_typeDefinition.Flags & TypeAttributes.ExplicitLayout) != 0;
}
}
public override bool IsSequentialLayout
{
get
{
return (_typeDefinition.Flags & TypeAttributes.SequentialLayout) != 0;
}
}
public override bool IsBeforeFieldInit
{
get
{
return (_typeDefinition.Flags & TypeAttributes.BeforeFieldInit) != 0;
}
}
public override bool IsSealed
{
get
{
return (_typeDefinition.Flags & TypeAttributes.Sealed) != 0;
}
}
public override bool IsAbstract
{
get
{
return (_typeDefinition.Flags & TypeAttributes.Abstract) != 0;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Hosting
{
/// <summary>
/// AtomicComposition provides lightweight atomicCompositional semantics to enable temporary
/// state to be managed for a series of nested atomicCompositions. Each atomicComposition maintains
/// queryable state along with a sequence of actions necessary to complete the state when
/// the atomicComposition is no longer in danger of being rolled back. State is completed or
/// rolled back when the atomicComposition is disposed, depending on the state of the
/// CompleteOnDipose property which defaults to false. The using(...) pattern in C# is a
/// convenient mechanism for defining atomicComposition scopes.
///
/// The least obvious aspects of AtomicComposition deal with nesting.
///
/// Firstly, no complete actions are actually performed until the outermost atomicComposition is
/// completed. Completeting or rolling back nested atomicCompositions serves only to change which
/// actions would be completed the outer atomicComposition.
///
/// Secondly, state is added in the form of queries associated with an object key. The
/// key represents a unique object the state is being held on behalf of. The quieries are
/// accessed throught the Query methods which provide automatic chaining to execute queries
/// across the target atomicComposition and its inner atomicComposition as appropriate.
///
/// Lastly, when a nested atomicComposition is created for a given outer the outer atomicComposition is locked.
/// It remains locked until the inner atomicComposition is disposed or completeed preventing the addition of
/// state, actions or other inner atomicCompositions.
/// </summary>
public class AtomicComposition : IDisposable
{
private readonly AtomicComposition _outerAtomicComposition;
private KeyValuePair<object, object>[] _values;
private int _valueCount = 0;
private List<Action> _completeActionList;
private List<Action> _revertActionList;
private bool _isDisposed = false;
private bool _isCompleted = false;
private bool _containsInnerAtomicComposition = false;
public AtomicComposition()
: this(null)
{
}
public AtomicComposition(AtomicComposition outerAtomicComposition)
{
// Lock the inner atomicComposition so that we can assume nothing changes except on
// the innermost scope, and thereby optimize the query path
if (outerAtomicComposition != null)
{
_outerAtomicComposition = outerAtomicComposition;
_outerAtomicComposition.ContainsInnerAtomicComposition = true;
}
}
public void SetValue(object key, object value)
{
ThrowIfDisposed();
ThrowIfCompleted();
ThrowIfContainsInnerAtomicComposition();
Requires.NotNull(key, nameof(key));
SetValueInternal(key, value);
}
public bool TryGetValue<T>(object key, out T value)
{
return TryGetValue(key, false, out value);
}
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters")]
public bool TryGetValue<T>(object key, bool localAtomicCompositionOnly, out T value)
{
ThrowIfDisposed();
ThrowIfCompleted();
Requires.NotNull(key, nameof(key));
return TryGetValueInternal(key, localAtomicCompositionOnly, out value);
}
public void AddCompleteAction(Action completeAction)
{
ThrowIfDisposed();
ThrowIfCompleted();
ThrowIfContainsInnerAtomicComposition();
Requires.NotNull(completeAction, nameof(completeAction));
if (_completeActionList == null)
{
_completeActionList = new List<Action>();
}
_completeActionList.Add(completeAction);
}
public void AddRevertAction(Action revertAction)
{
ThrowIfDisposed();
ThrowIfCompleted();
ThrowIfContainsInnerAtomicComposition();
Requires.NotNull(revertAction, nameof(revertAction));
if (_revertActionList == null)
{
_revertActionList = new List<Action>();
}
_revertActionList.Add(revertAction);
}
public void Complete()
{
ThrowIfDisposed();
ThrowIfCompleted();
if (_outerAtomicComposition == null)
{ // Execute all the complete actions
FinalComplete();
}
else
{ // Copy the actions and state to the outer atomicComposition
CopyComplete();
}
_isCompleted = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
ThrowIfDisposed();
_isDisposed = true;
if (_outerAtomicComposition != null)
{
_outerAtomicComposition.ContainsInnerAtomicComposition = false;
}
// Revert is always immediate and involves forgetting information and
// exceuting any appropriate revert actions
if (!_isCompleted)
{
if (_revertActionList != null)
{
List<Exception> exceptions = null;
// Execute the revert actions in reverse order to ensure
// everything incrementally rollsback its state.
for (int i = _revertActionList.Count - 1; i >= 0; i--)
{
Action action = _revertActionList[i];
try
{
action();
}
catch(CompositionException)
{
// This can only happen after preview is completed, so ... abandon remainder of events is correct
throw;
}
catch(Exception e)
{
if (exceptions == null)
{
//If any exceptions leak through the actions we will swallow them for now
// complete processing the list
// and we will throw InvalidOperationException with an AggregateException as it's innerException
exceptions = new List<Exception>();
}
exceptions.Add(e);
}
}
_revertActionList = null;
if(exceptions != null)
{
throw new InvalidOperationException(SR.InvalidOperation_RevertAndCompleteActionsMustNotThrow, new AggregateException(exceptions));
}
}
}
}
private void FinalComplete()
{
// Completeting the outer most scope is easy, just execute all the actions
if (_completeActionList != null)
{
List<Exception> exceptions = null;
foreach (Action action in _completeActionList)
{
try
{
action();
}
catch(CompositionException)
{
// This can only happen after preview is completed, so ... abandon remainder of events is correct
throw;
}
catch(Exception e)
{
if (exceptions == null)
{
//If any exceptions leak through the actions we will swallow them for now complete processing the list
// and we will throw InvalidOperationException with an AggregateException as it's innerException
exceptions = new List<Exception>();
}
exceptions.Add(e);
}
}
_completeActionList = null;
if(exceptions != null)
{
throw new InvalidOperationException(SR.InvalidOperation_RevertAndCompleteActionsMustNotThrow, new AggregateException(exceptions));
}
}
}
private void CopyComplete()
{
if (_outerAtomicComposition == null)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
_outerAtomicComposition.ContainsInnerAtomicComposition = false;
// Inner scopes are much odder, because completeting them means coalescing them into the
// outer scope - the complete or revert actions are deferred until the outermost scope completes
// or any intermediate rolls back
if (_completeActionList != null)
{
foreach (Action action in _completeActionList)
{
_outerAtomicComposition.AddCompleteAction(action);
}
}
if (_revertActionList != null)
{
foreach (Action action in _revertActionList)
{
_outerAtomicComposition.AddRevertAction(action);
}
}
// We can copy over existing atomicComposition entries because they're either already chained or
// overwrite by design and can now be completed or rolled back together
for (var index = 0; index < _valueCount; index++)
{
_outerAtomicComposition.SetValueInternal(
_values[index].Key, _values[index].Value);
}
}
private bool ContainsInnerAtomicComposition
{
set
{
if (value == true && _containsInnerAtomicComposition == true)
{
throw new InvalidOperationException(SR.AtomicComposition_AlreadyNested);
}
_containsInnerAtomicComposition = value;
}
}
private bool TryGetValueInternal<T>(object key, bool localAtomicCompositionOnly, out T value)
{
for (var index = 0; index < _valueCount; index++)
{
if (_values[index].Key == key)
{
value = (T)_values[index].Value;
return true;
}
}
// If there's no atomicComposition available then recurse until we hit the outermost
// scope, where upon we go ahead and return null
if (!localAtomicCompositionOnly && _outerAtomicComposition != null)
{
return _outerAtomicComposition.TryGetValueInternal<T>(key, localAtomicCompositionOnly, out value);
}
value = default(T);
return false;
}
private void SetValueInternal(object key, object value)
{
// Handle overwrites quickly
for (var index = 0; index < _valueCount; index++)
{
if (_values[index].Key == key)
{
_values[index] = new KeyValuePair<object,object>(key, value);
return;
}
}
// Expand storage when needed
if (_values == null || _valueCount == _values.Length)
{
var newQueries = new KeyValuePair<object, object>[_valueCount == 0 ? 5 : _valueCount * 2];
if (_values != null)
{
Array.Copy(_values, 0, newQueries, 0, _valueCount);
}
_values = newQueries;
}
// Store a new entry
_values[_valueCount] = new KeyValuePair<object, object>(key, value);
_valueCount++;
return;
}
[DebuggerStepThrough]
private void ThrowIfContainsInnerAtomicComposition()
{
if (_containsInnerAtomicComposition)
{
throw new InvalidOperationException(SR.AtomicComposition_PartOfAnotherAtomicComposition);
}
}
[DebuggerStepThrough]
private void ThrowIfCompleted()
{
if (_isCompleted)
{
throw new InvalidOperationException(SR.AtomicComposition_AlreadyCompleted);
}
}
[DebuggerStepThrough]
private void ThrowIfDisposed()
{
if (_isDisposed)
{
throw ExceptionBuilder.CreateObjectDisposed(this);
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
namespace o2dtk
{
namespace Utility
{
public class GUI
{
// Ends the last horizontal and begins a new one
public static void BreakHorizontal()
{
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
}
// Puts a label on a horizontal line
public static void Label(string label)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label);
GUILayout.EndHorizontal();
}
// Puts a two-valued label on a horizontal line
public static void Label(string label, string value)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label);
GUILayout.FlexibleSpace();
GUILayout.Label(value);
GUILayout.EndHorizontal();
}
// Puts a button on a horizontal line
public static bool Button(string label)
{
GUILayout.BeginHorizontal();
bool value = GUILayout.Button(label);
GUILayout.EndHorizontal();
return value;
}
// Puts a toggle on a horizontal line
public static bool LabeledToggle(string label, bool value)
{
GUILayout.BeginHorizontal();
value = GUILayout.Toggle(value, label);
GUILayout.EndHorizontal();
return value;
}
// Puts a toggle on a horizontal line
public static bool BeginToggleGroup(string label, bool value)
{
return EditorGUILayout.BeginToggleGroup(label, value);
}
// Puts a toggle on a horizontal line
public static void EndToggleGroup()
{
EditorGUILayout.EndToggleGroup();
}
// Draws a labeled integer field on a single horizontal line
public static int LabeledIntField(string label, int value)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label);
GUILayout.FlexibleSpace();
value = EditorGUILayout.IntField(value);
GUILayout.EndHorizontal();
return value;
}
// Draws a labeled floating point number field on single horizontal line
public static float LabeledFloatField(string label, float value)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label);
GUILayout.FlexibleSpace();
value = EditorGUILayout.FloatField(value);
GUILayout.EndHorizontal();
return value;
}
// Draws an enum selection field on a single horizontal line
public static System.Enum LabeledEnumField(string label, System.Enum value)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label);
GUILayout.FlexibleSpace();
value = EditorGUILayout.EnumPopup(value);
GUILayout.EndHorizontal();
return value;
}
// Draws a labeled text field on a single horizontal line
public static string LabeledTextField(string label, string value)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label);
GUILayout.FlexibleSpace();
value = EditorGUILayout.TextField(value);
GUILayout.EndHorizontal();
return value;
}
// Draws a labeled object field on a single horizontal line
public static Object LabeledObjectField(string label, Object obj, System.Type type = null, bool allow_game_objects = false)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label);
GUILayout.FlexibleSpace();
obj = EditorGUILayout.ObjectField(obj, typeof(Object), allow_game_objects);
GUILayout.EndHorizontal();
return obj;
}
// Draws an object field in the GUI and returns a valid directory object
// If an invalid object is given, an error is displayed
public static Object FileField(Object file)
{
Object obj = EditorGUILayout.ObjectField(file, typeof(Object), false);
if (obj != file)
{
string path = AssetDatabase.GetAssetPath(obj);
FileAttributes attr = File.GetAttributes(path);
if ((attr & FileAttributes.Directory) != FileAttributes.Directory)
return obj;
else
EditorUtility.DisplayDialog("Invalid input", "The given object is not a file", "OK");
}
return file;
}
// Draws a labeled object field and returns a valid directory object
public static Object LabeledFileField(string label, Object file)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label);
GUILayout.FlexibleSpace();
file = FileField(file);
GUILayout.EndHorizontal();
return file;
}
// Draws an object field in the GUI and returns a valid directory object
// If an invalid object is given, an error is displayed
public static MonoScript MonoScriptField(MonoScript file)
{
MonoScript obj = EditorGUILayout.ObjectField(file, typeof(MonoScript), false) as MonoScript;
if (obj != file)
{
string path = AssetDatabase.GetAssetPath(obj);
FileAttributes attr = File.GetAttributes(path);
if ((attr & FileAttributes.Directory) != FileAttributes.Directory)
return obj;
else
EditorUtility.DisplayDialog("Invalid input", "The given object is not a mono script", "OK");
}
return file;
}
// Draws a labeled object field and returns a valid directory object
public static MonoScript LabeledMonoScriptField(string label, MonoScript file)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label);
GUILayout.FlexibleSpace();
file = MonoScriptField(file);
GUILayout.EndHorizontal();
return file;
}
// Draws an object field in the GUI and returns a valid directory object
// If an invalid object is given, an error is displayed
public static Object DirectoryField(Object dir)
{
Object obj = EditorGUILayout.ObjectField(dir, typeof(Object), false);
if (obj != dir)
{
string path = AssetDatabase.GetAssetPath(obj);
FileAttributes attr = File.GetAttributes(path);
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
return obj;
else
EditorUtility.DisplayDialog("Invalid input", "The given object is not a directory", "OK");
}
return dir;
}
// Draws a labeled object field and returns a valid directory object
public static Object LabeledDirectoryField(string label, Object dir)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label);
GUILayout.FlexibleSpace();
dir = DirectoryField(dir);
GUILayout.EndHorizontal();
return dir;
}
// Displays a notification on the currently-focused window
public static void Notify(string text)
{
EditorWindow.focusedWindow.ShowNotification(new GUIContent(text));
}
}
}
}
| |
//
// Copyright (c) 2003-2006 Jaroslaw Kowalski <[email protected]>
// Copyright (c) 2006-2014 Piotr Fusik <[email protected]>
//
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using Sooda.Schema;
using System;
using System.Data;
using System.Data.SqlClient;
namespace Sooda.Sql
{
public class SqlServerBuilder : SqlBuilderNamedArg
{
public SqlServerBuilder() { }
public override string StringConcatenationOperator
{
get { return "+"; }
}
public override string GetDDLCommandTerminator()
{
return Environment.NewLine + "GO" + Environment.NewLine + Environment.NewLine;
}
public override string GetSQLDataType(Sooda.Schema.FieldInfo fi)
{
switch (fi.DataType)
{
case FieldDataType.Integer:
return "int";
case FieldDataType.AnsiString:
if (fi.Size > 4000)
return "text";
else
return "varchar(" + fi.Size + ")";
case FieldDataType.String:
if (fi.Size > 4000)
return "ntext";
else
return "nvarchar(" + fi.Size + ")";
case FieldDataType.Decimal:
if (fi.Size < 0)
return "decimal";
else if (fi.Precision < 0)
return "decimal(" + fi.Size + ")";
else
return "decimal(" + fi.Size + "," + fi.Precision + ")";
case FieldDataType.Guid:
return "uniqueidentifier";
case FieldDataType.Double:
if (fi.Size < 0)
return "float";
else if (fi.Precision < 0)
return "float(" + fi.Size + ")";
else
return "float(" + fi.Size + "," + fi.Precision + ")";
case FieldDataType.Float:
if (fi.Size < 0)
return "float";
else if (fi.Precision < 0)
return "float(" + fi.Size + ")";
else
return "float(" + fi.Size + "," + fi.Precision + ")";
case FieldDataType.DateTime:
return "datetime";
case FieldDataType.Image:
return "image";
case FieldDataType.Long:
return "bigint";
case FieldDataType.BooleanAsInteger:
return "int";
case FieldDataType.TimeSpan:
return "int";
case FieldDataType.Boolean:
return "bit";
case FieldDataType.Blob:
return "varbinary(max)";
default:
throw new NotImplementedException(String.Format("Datatype {0} not supported for this database", fi.DataType.ToString()));
}
}
protected override string GetNameForParameter(int pos)
{
return "@p" + pos.ToString();
}
public override string QuoteIdentifier(string s)
{
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (!(c >= 'A' && c <= 'Z')
&& !(c >= 'a' && c <= 'z')
&& !(c >= '0' && c <= '9')
&& c != '_')
return "[" + s + "]";
}
return s;
}
public override SqlTopSupportMode TopSupport
{
get
{
return SqlTopSupportMode.MSSQLRowNum;
// return SqlTopSupportMode.MSSQL2012;
}
}
public override int MaxIdentifierLength
{
get
{
return 128;
}
}
public override string EndInsert(string tableName)
{
return "set identity_insert " + tableName + " off ";
}
public override string BeginInsert(string tableName)
{
return "set identity_insert " + tableName + " on ";
}
public override string GetSQLOrderBy(Sooda.Schema.FieldInfo fi, bool start)
{
switch (fi.DataType)
{
case FieldDataType.AnsiString:
if (fi.Size > 4000)
return start ? "convert(varchar(3999), " : ")";
else
return "";
case FieldDataType.String:
if (fi.Size > 4000)
return start ? "convert(nvarchar(3999), " : ")";
else
return "";
default:
return "";
}
}
public override string GetAlterTableStatement(Sooda.Schema.TableInfo tableInfo)
{
string ident = GetTruncatedIdentifier(String.Format("PK_{0}", tableInfo.DBTableName));
return String.Format("alter table {0} add constraint {1} primary key", tableInfo.DBTableName, ident);
}
public override bool HandleFatalException(IDbConnection connection, Exception e)
{
SqlConnection.ClearAllPools();
return false;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D03_Continent_Child (editable child object).<br/>
/// This is a generated base class of <see cref="D03_Continent_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="D02_Continent"/> collection.
/// </remarks>
[Serializable]
public partial class D03_Continent_Child : BusinessBase<D03_Continent_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "SubContinents Child Name");
/// <summary>
/// Gets or sets the SubContinents Child Name.
/// </summary>
/// <value>The SubContinents Child Name.</value>
public string Continent_Child_Name
{
get { return GetProperty(Continent_Child_NameProperty); }
set { SetProperty(Continent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D03_Continent_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D03_Continent_Child"/> object.</returns>
internal static D03_Continent_Child NewD03_Continent_Child()
{
return DataPortal.CreateChild<D03_Continent_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="D03_Continent_Child"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID1">The Continent_ID1 parameter of the D03_Continent_Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="D03_Continent_Child"/> object.</returns>
internal static D03_Continent_Child GetD03_Continent_Child(int continent_ID1)
{
return DataPortal.FetchChild<D03_Continent_Child>(continent_ID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D03_Continent_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public D03_Continent_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D03_Continent_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D03_Continent_Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="continent_ID1">The Continent ID1.</param>
protected void Child_Fetch(int continent_ID1)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetD03_Continent_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID1", continent_ID1).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, continent_ID1);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="D03_Continent_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Continent_Child_NameProperty, dr.GetString("Continent_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="D03_Continent_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D02_Continent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddD03_Continent_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID1", parent.Continent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Continent_Child_Name", ReadProperty(Continent_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D03_Continent_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(D02_Continent parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateD03_Continent_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID1", parent.Continent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Continent_Child_Name", ReadProperty(Continent_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="D03_Continent_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(D02_Continent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteD03_Continent_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID1", parent.Continent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
using SFML.Window;
namespace SFML
{
namespace Graphics
{
////////////////////////////////////////////////////////////
/// <summary>
/// Define a 3x3 transform matrix
/// </summary>
////////////////////////////////////////////////////////////
[StructLayout(LayoutKind.Sequential)]
public struct Transform
{
////////////////////////////////////////////////////////////
/// <summary>
/// Construct a transform from a 3x3 matrix
/// </summary>
/// <param name="a00">Element (0, 0) of the matrix</param>
/// <param name="a01">Element (0, 1) of the matrix</param>
/// <param name="a02">Element (0, 2) of the matrix</param>
/// <param name="a10">Element (1, 0) of the matrix</param>
/// <param name="a11">Element (1, 1) of the matrix</param>
/// <param name="a12">Element (1, 2) of the matrix</param>
/// <param name="a20">Element (2, 0) of the matrix</param>
/// <param name="a21">Element (2, 1) of the matrix</param>
/// <param name="a22">Element (2, 2) of the matrix</param>
////////////////////////////////////////////////////////////
public Transform(float a00, float a01, float a02,
float a10, float a11, float a12,
float a20, float a21, float a22)
{
m00 = a00; m01 = a01; m02 = a02;
m10 = a10; m11 = a11; m12 = a12;
m20 = a20; m21 = a21; m22 = a22;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Return the inverse of the transform.
///
/// If the inverse cannot be computed, an identity transform
/// is returned.
/// </summary>
/// <returns>A new transform which is the inverse of self</returns>
////////////////////////////////////////////////////////////
public Transform GetInverse()
{
return sfTransform_getInverse(ref this);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Transform a 2D point.
/// </summary>
/// <param name="x">X coordinate of the point to transform</param>
/// <param name="y">Y coordinate of the point to transform</param>
/// <returns>Transformed point</returns>
////////////////////////////////////////////////////////////
public Vector2f TransformPoint(float x, float y)
{
return TransformPoint(new Vector2f(x, y));
}
////////////////////////////////////////////////////////////
/// <summary>
/// Transform a 2D point.
/// </summary>
/// <param name="point">Point to transform</param>
/// <returns>Transformed point</returns>
////////////////////////////////////////////////////////////
public Vector2f TransformPoint(Vector2f point)
{
return sfTransform_transformPoint(ref this, point);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Transform a rectangle.
///
/// Since SFML doesn't provide support for oriented rectangles,
/// the result of this function is always an axis-aligned
/// rectangle. Which means that if the transform contains a
/// rotation, the bounding rectangle of the transformed rectangle
/// is returned.
/// </summary>
/// <param name="rectangle">Rectangle to transform</param>
/// <returns>Transformed rectangle</returns>
////////////////////////////////////////////////////////////
public FloatRect TransformRect(FloatRect rectangle)
{
return sfTransform_transformRect(ref this, rectangle);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Combine the current transform with another one.
///
/// The result is a transform that is equivalent to applying
/// this followed by transform. Mathematically, it is
/// equivalent to a matrix multiplication.
/// </summary>
/// <param name="transform">Transform to combine to this transform</param>
////////////////////////////////////////////////////////////
public void Combine(Transform transform)
{
sfTransform_combine(ref this, ref transform);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Combine the current transform with a translation.
/// </summary>
/// <param name="x">Offset to apply on X axis</param>
/// <param name="y">Offset to apply on Y axis</param>
////////////////////////////////////////////////////////////
public void Translate(float x, float y)
{
sfTransform_translate(ref this, x, y);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Combine the current transform with a translation.
/// </summary>
/// <param name="offset">Translation offset to apply</param>
////////////////////////////////////////////////////////////
public void Translate(Vector2f offset)
{
Translate(offset.X, offset.Y);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Combine the current transform with a rotation.
/// </summary>
/// <param name="angle">Rotation angle, in degrees</param>
////////////////////////////////////////////////////////////
public void Rotate(float angle)
{
sfTransform_rotate(ref this, angle);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Combine the current transform with a rotation.
///
/// The center of rotation is provided for convenience as a second
/// argument, so that you can build rotations around arbitrary points
/// more easily (and efficiently) than the usual
/// Translate(-center); Rotate(angle); Translate(center).
/// </summary>
/// <param name="angle">Rotation angle, in degrees</param>
/// <param name="centerX">X coordinate of the center of rotation</param>
/// <param name="centerY">Y coordinate of the center of rotation</param>
////////////////////////////////////////////////////////////
public void Rotate(float angle, float centerX, float centerY)
{
sfTransform_rotateWithCenter(ref this, angle, centerX, centerY);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Combine the current transform with a rotation.
///
/// The center of rotation is provided for convenience as a second
/// argument, so that you can build rotations around arbitrary points
/// more easily (and efficiently) than the usual
/// Translate(-center); Rotate(angle); Translate(center).
/// </summary>
/// <param name="angle">Rotation angle, in degrees</param>
/// <param name="center">Center of rotation</param>
////////////////////////////////////////////////////////////
public void Rotate(float angle, Vector2f center)
{
Rotate(angle, center.X, center.Y);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Combine the current transform with a scaling.
/// </summary>
/// <param name="scaleX">Scaling factor on the X axis</param>
/// <param name="scaleY">Scaling factor on the Y axis</param>
////////////////////////////////////////////////////////////
public void Scale(float scaleX, float scaleY)
{
sfTransform_scale(ref this, scaleX, scaleY);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Combine the current transform with a scaling.
///
/// The center of scaling is provided for convenience as a second
/// argument, so that you can build scaling around arbitrary points
/// more easily (and efficiently) than the usual
/// Translate(-center); Scale(factors); Translate(center).
/// </summary>
/// <param name="scaleX">Scaling factor on X axis</param>
/// <param name="scaleY">Scaling factor on Y axis</param>
/// <param name="centerX">X coordinate of the center of scaling</param>
/// <param name="centerY">Y coordinate of the center of scaling</param>
////////////////////////////////////////////////////////////
public void Scale(float scaleX, float scaleY, float centerX, float centerY)
{
sfTransform_scaleWithCenter(ref this, scaleX, scaleY, centerX, centerY);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Combine the current transform with a scaling.
/// </summary>
/// <param name="factors">Scaling factors</param>
////////////////////////////////////////////////////////////
public void Scale(Vector2f factors)
{
Scale(factors.X, factors.Y);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Combine the current transform with a scaling.
///
/// The center of scaling is provided for convenience as a second
/// argument, so that you can build scaling around arbitrary points
/// more easily (and efficiently) than the usual
/// Translate(-center); Scale(factors); Translate(center).
/// </summary>
/// <param name="factors">Scaling factors</param>
/// <param name="center">Center of scaling</param>
////////////////////////////////////////////////////////////
public void Scale(Vector2f factors, Vector2f center)
{
Scale(factors.X, factors.Y, center.X, center.Y);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Overload of binary operator * to combine two transforms.
/// This call is equivalent to calling new Transform(left).Combine(right).
/// </summary>
/// <param name="left">Left operand (the first transform)</param>
/// <param name="right">Right operand (the second transform)</param>
/// <returns>New combined transform</returns>
////////////////////////////////////////////////////////////
public static Transform operator *(Transform left, Transform right)
{
left.Combine(right);
return left;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Overload of binary operator * to transform a point.
/// This call is equivalent to calling left.TransformPoint(right).
/// </summary>
/// <param name="left">Left operand (the transform)</param>
/// <param name="right">Right operand (the point to transform)</param>
/// <returns>New transformed point</returns>
////////////////////////////////////////////////////////////
public static Vector2f operator *(Transform left, Vector2f right)
{
return left.TransformPoint(right);
}
////////////////////////////////////////////////////////////
/// <summary>The identity transform (does nothing)</summary>
////////////////////////////////////////////////////////////
public static Transform Identity
{
get
{
return new Transform(1, 0, 0,
0, 1, 0,
0, 0, 1);
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Provide a string describing the object
/// </summary>
/// <returns>String description of the object</returns>
////////////////////////////////////////////////////////////
public override string ToString()
{
return "[Transform]" +
" Matrix(" +
m00 + ", " + m01 + ", " + m02 +
m10 + ", " + m11 + ", " + m12 +
m20 + ", " + m21 + ", " + m22 +
")";
}
float m00, m01, m02;
float m10, m11, m12;
float m20, m21, m22;
#region Imports
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern Transform sfTransform_getInverse(ref Transform transform);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern Vector2f sfTransform_transformPoint(ref Transform transform, Vector2f point);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern FloatRect sfTransform_transformRect(ref Transform transform, FloatRect rectangle);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfTransform_combine(ref Transform transform, ref Transform other);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfTransform_translate(ref Transform transform, float x, float y);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfTransform_rotate(ref Transform transform, float angle);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfTransform_rotateWithCenter(ref Transform transform, float angle, float centerX, float centerY);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfTransform_scale(ref Transform transform, float scaleX, float scaleY);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfTransform_scaleWithCenter(ref Transform transform, float scaleX, float scaleY, float centerX, float centerY);
#endregion
}
}
}
| |
/*
* 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.Drawing;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.LegacyMap
{
public enum DrawRoutine
{
Rectangle,
Polygon,
Ellipse
}
public struct face
{
public Point[] pts;
}
public struct DrawStruct
{
public DrawRoutine dr;
public Rectangle rect;
public SolidBrush brush;
public face[] trns;
}
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapImageModule")]
public class MapImageModule : IMapImageGenerator, INonSharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
private IConfigSource m_config;
private IMapTileTerrainRenderer terrainRenderer;
private bool m_Enabled = false;
#region IMapImageGenerator Members
public Bitmap CreateMapTile()
{
bool drawPrimVolume = true;
bool textureTerrain = false;
bool generateMaptiles = true;
Bitmap mapbmp;
string[] configSections = new string[] { "Map", "Startup" };
drawPrimVolume
= Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, drawPrimVolume);
textureTerrain
= Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, textureTerrain);
generateMaptiles
= Util.GetConfigVarFromSections<bool>(m_config, "GenerateMaptiles", configSections, generateMaptiles);
if (generateMaptiles)
{
if (textureTerrain)
{
terrainRenderer = new TexturedMapTileRenderer();
}
else
{
terrainRenderer = new ShadedMapTileRenderer();
}
terrainRenderer.Initialise(m_scene, m_config);
mapbmp = new Bitmap((int)Constants.RegionSize, (int)Constants.RegionSize, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
//long t = System.Environment.TickCount;
//for (int i = 0; i < 10; ++i) {
terrainRenderer.TerrainToBitmap(mapbmp);
//}
//t = System.Environment.TickCount - t;
//m_log.InfoFormat("[MAPTILE] generation of 10 maptiles needed {0} ms", t);
if (drawPrimVolume)
{
DrawObjectVolume(m_scene, mapbmp);
}
}
else
{
mapbmp = FetchTexture(m_scene.RegionInfo.RegionSettings.TerrainImageID);
}
return mapbmp;
}
public byte[] WriteJpeg2000Image()
{
try
{
using (Bitmap mapbmp = CreateMapTile())
return OpenJPEG.EncodeFromImage(mapbmp, true);
}
catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke
{
m_log.Error("Failed generating terrain map: " + e);
}
return null;
}
#endregion
#region Region Module interface
public void Initialise(IConfigSource source)
{
m_config = source;
if (Util.GetConfigVarFromSections<string>(
m_config, "MapImageModule", new string[] { "Startup", "Map" }, "MapImageModule") != "MapImageModule")
return;
m_Enabled = true;
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_scene = scene;
m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
public string Name
{
get { return "MapImageModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
// TODO: unused:
// private void ShadeBuildings(Bitmap map)
// {
// lock (map)
// {
// lock (m_scene.Entities)
// {
// foreach (EntityBase entity in m_scene.Entities.Values)
// {
// if (entity is SceneObjectGroup)
// {
// SceneObjectGroup sog = (SceneObjectGroup) entity;
//
// foreach (SceneObjectPart primitive in sog.Children.Values)
// {
// int x = (int) (primitive.AbsolutePosition.X - (primitive.Scale.X / 2));
// int y = (int) (primitive.AbsolutePosition.Y - (primitive.Scale.Y / 2));
// int w = (int) primitive.Scale.X;
// int h = (int) primitive.Scale.Y;
//
// int dx;
// for (dx = x; dx < x + w; dx++)
// {
// int dy;
// for (dy = y; dy < y + h; dy++)
// {
// if (x < 0 || y < 0)
// continue;
// if (x >= map.Width || y >= map.Height)
// continue;
//
// map.SetPixel(dx, dy, Color.DarkGray);
// }
// }
// }
// }
// }
// }
// }
// }
private Bitmap FetchTexture(UUID id)
{
AssetBase asset = m_scene.AssetService.Get(id.ToString());
if (asset != null)
{
m_log.DebugFormat("[MAPTILE]: Static map image texture {0} found for {1}", id, m_scene.Name);
}
else
{
m_log.WarnFormat("[MAPTILE]: Static map image texture {0} not found for {1}", id, m_scene.Name);
return null;
}
ManagedImage managedImage;
Image image;
try
{
if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
return new Bitmap(image);
else
return null;
}
catch (DllNotFoundException)
{
m_log.ErrorFormat("[MAPTILE]: OpenJpeg is not installed correctly on this system. Asset Data is empty for {0}", id);
}
catch (IndexOutOfRangeException)
{
m_log.ErrorFormat("[MAPTILE]: OpenJpeg was unable to decode this. Asset Data is empty for {0}", id);
}
catch (Exception)
{
m_log.ErrorFormat("[MAPTILE]: OpenJpeg was unable to decode this. Asset Data is empty for {0}", id);
}
return null;
}
private Bitmap DrawObjectVolume(Scene whichScene, Bitmap mapbmp)
{
int tc = 0;
double[,] hm = whichScene.Heightmap.GetDoubles();
tc = Environment.TickCount;
m_log.Debug("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile");
EntityBase[] objs = whichScene.GetEntities();
Dictionary<uint, DrawStruct> z_sort = new Dictionary<uint, DrawStruct>();
//SortedList<float, RectangleDrawStruct> z_sort = new SortedList<float, RectangleDrawStruct>();
List<float> z_sortheights = new List<float>();
List<uint> z_localIDs = new List<uint>();
lock (objs)
{
foreach (EntityBase obj in objs)
{
// Only draw the contents of SceneObjectGroup
if (obj is SceneObjectGroup)
{
SceneObjectGroup mapdot = (SceneObjectGroup)obj;
Color mapdotspot = Color.Gray; // Default color when prim color is white
// Loop over prim in group
foreach (SceneObjectPart part in mapdot.Parts)
{
if (part == null)
continue;
// Draw if the object is at least 1 meter wide in any direction
if (part.Scale.X > 1f || part.Scale.Y > 1f || part.Scale.Z > 1f)
{
// Try to get the RGBA of the default texture entry..
//
try
{
// get the null checks out of the way
// skip the ones that break
if (part == null)
continue;
if (part.Shape == null)
continue;
if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree || part.Shape.PCode == (byte)PCode.Grass)
continue; // eliminates trees from this since we don't really have a good tree representation
// if you want tree blocks on the map comment the above line and uncomment the below line
//mapdotspot = Color.PaleGreen;
Primitive.TextureEntry textureEntry = part.Shape.Textures;
if (textureEntry == null || textureEntry.DefaultTexture == null)
continue;
Color4 texcolor = textureEntry.DefaultTexture.RGBA;
// Not sure why some of these are null, oh well.
int colorr = 255 - (int)(texcolor.R * 255f);
int colorg = 255 - (int)(texcolor.G * 255f);
int colorb = 255 - (int)(texcolor.B * 255f);
if (!(colorr == 255 && colorg == 255 && colorb == 255))
{
//Try to set the map spot color
try
{
// If the color gets goofy somehow, skip it *shakes fist at Color4
mapdotspot = Color.FromArgb(colorr, colorg, colorb);
}
catch (ArgumentException)
{
}
}
}
catch (IndexOutOfRangeException)
{
// Windows Array
}
catch (ArgumentOutOfRangeException)
{
// Mono Array
}
Vector3 pos = part.GetWorldPosition();
// skip prim outside of retion
if (pos.X < 0f || pos.X > 256f || pos.Y < 0f || pos.Y > 256f)
continue;
// skip prim in non-finite position
if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) ||
Single.IsInfinity(pos.X) || Single.IsInfinity(pos.Y))
continue;
// Figure out if object is under 256m above the height of the terrain
bool isBelow256AboveTerrain = false;
try
{
isBelow256AboveTerrain = (pos.Z < ((float)hm[(int)pos.X, (int)pos.Y] + 256f));
}
catch (Exception)
{
}
if (isBelow256AboveTerrain)
{
// Translate scale by rotation so scale is represented properly when object is rotated
Vector3 lscale = new Vector3(part.Shape.Scale.X, part.Shape.Scale.Y, part.Shape.Scale.Z);
Vector3 scale = new Vector3();
Vector3 tScale = new Vector3();
Vector3 axPos = new Vector3(pos.X,pos.Y,pos.Z);
Quaternion llrot = part.GetWorldRotation();
Quaternion rot = new Quaternion(llrot.W, llrot.X, llrot.Y, llrot.Z);
scale = lscale * rot;
// negative scales don't work in this situation
scale.X = Math.Abs(scale.X);
scale.Y = Math.Abs(scale.Y);
scale.Z = Math.Abs(scale.Z);
// This scaling isn't very accurate and doesn't take into account the face rotation :P
int mapdrawstartX = (int)(pos.X - scale.X);
int mapdrawstartY = (int)(pos.Y - scale.Y);
int mapdrawendX = (int)(pos.X + scale.X);
int mapdrawendY = (int)(pos.Y + scale.Y);
// If object is beyond the edge of the map, don't draw it to avoid errors
if (mapdrawstartX < 0 || mapdrawstartX > ((int)Constants.RegionSize - 1) || mapdrawendX < 0 || mapdrawendX > ((int)Constants.RegionSize - 1)
|| mapdrawstartY < 0 || mapdrawstartY > ((int)Constants.RegionSize - 1) || mapdrawendY < 0
|| mapdrawendY > ((int)Constants.RegionSize - 1))
continue;
#region obb face reconstruction part duex
Vector3[] vertexes = new Vector3[8];
// float[] distance = new float[6];
Vector3[] FaceA = new Vector3[6]; // vertex A for Facei
Vector3[] FaceB = new Vector3[6]; // vertex B for Facei
Vector3[] FaceC = new Vector3[6]; // vertex C for Facei
Vector3[] FaceD = new Vector3[6]; // vertex D for Facei
tScale = new Vector3(lscale.X, -lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[0] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[0].x = pos.X + vertexes[0].x;
//vertexes[0].y = pos.Y + vertexes[0].y;
//vertexes[0].z = pos.Z + vertexes[0].z;
FaceA[0] = vertexes[0];
FaceB[3] = vertexes[0];
FaceA[4] = vertexes[0];
tScale = lscale;
scale = ((tScale * rot));
vertexes[1] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[1].x = pos.X + vertexes[1].x;
// vertexes[1].y = pos.Y + vertexes[1].y;
//vertexes[1].z = pos.Z + vertexes[1].z;
FaceB[0] = vertexes[1];
FaceA[1] = vertexes[1];
FaceC[4] = vertexes[1];
tScale = new Vector3(lscale.X, -lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[2] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
//vertexes[2].x = pos.X + vertexes[2].x;
//vertexes[2].y = pos.Y + vertexes[2].y;
//vertexes[2].z = pos.Z + vertexes[2].z;
FaceC[0] = vertexes[2];
FaceD[3] = vertexes[2];
FaceC[5] = vertexes[2];
tScale = new Vector3(lscale.X, lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[3] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
//vertexes[3].x = pos.X + vertexes[3].x;
// vertexes[3].y = pos.Y + vertexes[3].y;
// vertexes[3].z = pos.Z + vertexes[3].z;
FaceD[0] = vertexes[3];
FaceC[1] = vertexes[3];
FaceA[5] = vertexes[3];
tScale = new Vector3(-lscale.X, lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[4] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[4].x = pos.X + vertexes[4].x;
// vertexes[4].y = pos.Y + vertexes[4].y;
// vertexes[4].z = pos.Z + vertexes[4].z;
FaceB[1] = vertexes[4];
FaceA[2] = vertexes[4];
FaceD[4] = vertexes[4];
tScale = new Vector3(-lscale.X, lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[5] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[5].x = pos.X + vertexes[5].x;
// vertexes[5].y = pos.Y + vertexes[5].y;
// vertexes[5].z = pos.Z + vertexes[5].z;
FaceD[1] = vertexes[5];
FaceC[2] = vertexes[5];
FaceB[5] = vertexes[5];
tScale = new Vector3(-lscale.X, -lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[6] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[6].x = pos.X + vertexes[6].x;
// vertexes[6].y = pos.Y + vertexes[6].y;
// vertexes[6].z = pos.Z + vertexes[6].z;
FaceB[2] = vertexes[6];
FaceA[3] = vertexes[6];
FaceB[4] = vertexes[6];
tScale = new Vector3(-lscale.X, -lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[7] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[7].x = pos.X + vertexes[7].x;
// vertexes[7].y = pos.Y + vertexes[7].y;
// vertexes[7].z = pos.Z + vertexes[7].z;
FaceD[2] = vertexes[7];
FaceC[3] = vertexes[7];
FaceD[5] = vertexes[7];
#endregion
//int wy = 0;
//bool breakYN = false; // If we run into an error drawing, break out of the
// loop so we don't lag to death on error handling
DrawStruct ds = new DrawStruct();
ds.brush = new SolidBrush(mapdotspot);
//ds.rect = new Rectangle(mapdrawstartX, (255 - mapdrawstartY), mapdrawendX - mapdrawstartX, mapdrawendY - mapdrawstartY);
ds.trns = new face[FaceA.Length];
for (int i = 0; i < FaceA.Length; i++)
{
Point[] working = new Point[5];
working[0] = project(FaceA[i], axPos);
working[1] = project(FaceB[i], axPos);
working[2] = project(FaceD[i], axPos);
working[3] = project(FaceC[i], axPos);
working[4] = project(FaceA[i], axPos);
face workingface = new face();
workingface.pts = working;
ds.trns[i] = workingface;
}
z_sort.Add(part.LocalId, ds);
z_localIDs.Add(part.LocalId);
z_sortheights.Add(pos.Z);
//for (int wx = mapdrawstartX; wx < mapdrawendX; wx++)
//{
//for (wy = mapdrawstartY; wy < mapdrawendY; wy++)
//{
//m_log.InfoFormat("[MAPDEBUG]: {0},{1}({2})", wx, (255 - wy),wy);
//try
//{
// Remember, flip the y!
// mapbmp.SetPixel(wx, (255 - wy), mapdotspot);
//}
//catch (ArgumentException)
//{
// breakYN = true;
//}
//if (breakYN)
// break;
//}
//if (breakYN)
// break;
//}
} // Object is within 256m Z of terrain
} // object is at least a meter wide
} // loop over group children
} // entitybase is sceneobject group
} // foreach loop over entities
float[] sortedZHeights = z_sortheights.ToArray();
uint[] sortedlocalIds = z_localIDs.ToArray();
// Sort prim by Z position
Array.Sort(sortedZHeights, sortedlocalIds);
Graphics g = Graphics.FromImage(mapbmp);
for (int s = 0; s < sortedZHeights.Length; s++)
{
if (z_sort.ContainsKey(sortedlocalIds[s]))
{
DrawStruct rectDrawStruct = z_sort[sortedlocalIds[s]];
for (int r = 0; r < rectDrawStruct.trns.Length; r++)
{
g.FillPolygon(rectDrawStruct.brush,rectDrawStruct.trns[r].pts);
}
//g.FillRectangle(rectDrawStruct.brush , rectDrawStruct.rect);
}
}
g.Dispose();
} // lock entities objs
m_log.Debug("[MAPTILE]: Generating Maptile Step 2: Done in " + (Environment.TickCount - tc) + " ms");
return mapbmp;
}
private Point project(Vector3 point3d, Vector3 originpos)
{
Point returnpt = new Point();
//originpos = point3d;
//int d = (int)(256f / 1.5f);
//Vector3 topos = new Vector3(0, 0, 0);
// float z = -point3d.z - topos.z;
returnpt.X = (int)point3d.X;//(int)((topos.x - point3d.x) / z * d);
returnpt.Y = (int)(((int)Constants.RegionSize - 1) - point3d.Y);//(int)(255 - (((topos.y - point3d.y) / z * d)));
return returnpt;
}
public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
{
return null;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public static partial class DatabaseRecommendedActionOperationsExtensions
{
/// <summary>
/// Returns details of a recommended action.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseRecommendedActionOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL server.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL database.
/// </param>
/// <param name='advisorName'>
/// Required. The name of the Azure SQL database advisor.
/// </param>
/// <param name='recommendedActionName'>
/// Required. The name of the Azure SQL database recommended action.
/// </param>
/// <returns>
/// Represents the response to a get recommended action request.
/// </returns>
public static RecommendedActionGetResponse Get(this IDatabaseRecommendedActionOperations operations, string resourceGroupName, string serverName, string databaseName, string advisorName, string recommendedActionName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseRecommendedActionOperations)s).GetAsync(resourceGroupName, serverName, databaseName, advisorName, recommendedActionName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns details of a recommended action.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseRecommendedActionOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL server.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL database.
/// </param>
/// <param name='advisorName'>
/// Required. The name of the Azure SQL database advisor.
/// </param>
/// <param name='recommendedActionName'>
/// Required. The name of the Azure SQL database recommended action.
/// </param>
/// <returns>
/// Represents the response to a get recommended action request.
/// </returns>
public static Task<RecommendedActionGetResponse> GetAsync(this IDatabaseRecommendedActionOperations operations, string resourceGroupName, string serverName, string databaseName, string advisorName, string recommendedActionName)
{
return operations.GetAsync(resourceGroupName, serverName, databaseName, advisorName, recommendedActionName, CancellationToken.None);
}
/// <summary>
/// Returns list of recommended actions for this advisor.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseRecommendedActionOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL server.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL database.
/// </param>
/// <param name='advisorName'>
/// Required. The name of the Azure SQL database advisor.
/// </param>
/// <returns>
/// Represents the response to a list recommended actions request.
/// </returns>
public static RecommendedActionListResponse List(this IDatabaseRecommendedActionOperations operations, string resourceGroupName, string serverName, string databaseName, string advisorName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseRecommendedActionOperations)s).ListAsync(resourceGroupName, serverName, databaseName, advisorName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns list of recommended actions for this advisor.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseRecommendedActionOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL server.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL database.
/// </param>
/// <param name='advisorName'>
/// Required. The name of the Azure SQL database advisor.
/// </param>
/// <returns>
/// Represents the response to a list recommended actions request.
/// </returns>
public static Task<RecommendedActionListResponse> ListAsync(this IDatabaseRecommendedActionOperations operations, string resourceGroupName, string serverName, string databaseName, string advisorName)
{
return operations.ListAsync(resourceGroupName, serverName, databaseName, advisorName, CancellationToken.None);
}
/// <summary>
/// Updates recommended action state.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseRecommendedActionOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL server.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL database.
/// </param>
/// <param name='advisorName'>
/// Required. The name of the Azure SQL database advisor.
/// </param>
/// <param name='recommendedActionName'>
/// Required. The name of the Azure SQL database recommended action.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for updating recommended action
/// state.
/// </param>
/// <returns>
/// Represents the response to an update recommended action request.
/// </returns>
public static RecommendedActionUpdateResponse Update(this IDatabaseRecommendedActionOperations operations, string resourceGroupName, string serverName, string databaseName, string advisorName, string recommendedActionName, RecommendedActionUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDatabaseRecommendedActionOperations)s).UpdateAsync(resourceGroupName, serverName, databaseName, advisorName, recommendedActionName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates recommended action state.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IDatabaseRecommendedActionOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL server.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL database.
/// </param>
/// <param name='advisorName'>
/// Required. The name of the Azure SQL database advisor.
/// </param>
/// <param name='recommendedActionName'>
/// Required. The name of the Azure SQL database recommended action.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for updating recommended action
/// state.
/// </param>
/// <returns>
/// Represents the response to an update recommended action request.
/// </returns>
public static Task<RecommendedActionUpdateResponse> UpdateAsync(this IDatabaseRecommendedActionOperations operations, string resourceGroupName, string serverName, string databaseName, string advisorName, string recommendedActionName, RecommendedActionUpdateParameters parameters)
{
return operations.UpdateAsync(resourceGroupName, serverName, databaseName, advisorName, recommendedActionName, parameters, CancellationToken.None);
}
}
}
| |
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Framework.Input.Bindings
{
/// <summary>
/// A collection of keys, mouse and other controllers' buttons.
/// </summary>
public enum InputKey
{
/// <summary>
/// No key pressed.
/// </summary>
None = 0,
/// <summary>
/// The shift key.
/// </summary>
Shift = 1,
/// <summary>
/// The control key.
/// </summary>
Control = 3,
/// <summary>
/// The alt key.
/// </summary>
Alt = 5,
/// <summary>
/// The win key.
/// </summary>
Super = 7,
/// <summary>
/// The menu key.
/// </summary>
Menu = 9,
/// <summary>
/// The F1 key.
/// </summary>
F1 = 10,
/// <summary>
/// The F2 key.
/// </summary>
F2 = 11,
/// <summary>
/// The F3 key.
/// </summary>
F3 = 12,
/// <summary>
/// The F4 key.
/// </summary>
F4 = 13,
/// <summary>
/// The F5 key.
/// </summary>
F5 = 14,
/// <summary>
/// The F6 key.
/// </summary>
F6 = 15,
/// <summary>
/// The F7 key.
/// </summary>
F7 = 16,
/// <summary>
/// The F8 key.
/// </summary>
F8 = 17,
/// <summary>
/// The F9 key.
/// </summary>
F9 = 18,
/// <summary>
/// The F10 key.
/// </summary>
F10 = 19,
/// <summary>
/// The F11 key.
/// </summary>
F11 = 20,
/// <summary>
/// The F12 key.
/// </summary>
F12 = 21,
/// <summary>
/// The F13 key.
/// </summary>
F13 = 22,
/// <summary>
/// The F14 key.
/// </summary>
F14 = 23,
/// <summary>
/// The F15 key.
/// </summary>
F15 = 24,
/// <summary>
/// The F16 key.
/// </summary>
F16 = 25,
/// <summary>
/// The F17 key.
/// </summary>
F17 = 26,
/// <summary>
/// The F18 key.
/// </summary>
F18 = 27,
/// <summary>
/// The F19 key.
/// </summary>
F19 = 28,
/// <summary>
/// The F20 key.
/// </summary>
F20 = 29,
/// <summary>
/// The F21 key.
/// </summary>
F21 = 30,
/// <summary>
/// The F22 key.
/// </summary>
F22 = 31,
/// <summary>
/// The F23 key.
/// </summary>
F23 = 32,
/// <summary>
/// The F24 key.
/// </summary>
F24 = 33,
/// <summary>
/// The F25 key.
/// </summary>
F25 = 34,
/// <summary>
/// The F26 key.
/// </summary>
F26 = 35,
/// <summary>
/// The F27 key.
/// </summary>
F27 = 36,
/// <summary>
/// The F28 key.
/// </summary>
F28 = 37,
/// <summary>
/// The F29 key.
/// </summary>
F29 = 38,
/// <summary>
/// The F30 key.
/// </summary>
F30 = 39,
/// <summary>
/// The F31 key.
/// </summary>
F31 = 40,
/// <summary>
/// The F32 key.
/// </summary>
F32 = 41,
/// <summary>
/// The F33 key.
/// </summary>
F33 = 42,
/// <summary>
/// The F34 key.
/// </summary>
F34 = 43,
/// <summary>
/// The F35 key.
/// </summary>
F35 = 44,
/// <summary>
/// The up arrow key.
/// </summary>
Up = 45,
/// <summary>
/// The down arrow key.
/// </summary>
Down = 46,
/// <summary>
/// The left arrow key.
/// </summary>
Left = 47,
/// <summary>
/// The right arrow key.
/// </summary>
Right = 48,
/// <summary>
/// The enter key.
/// </summary>
Enter = 49,
/// <summary>
/// The escape key.
/// </summary>
Escape = 50,
/// <summary>
/// The space key.
/// </summary>
Space = 51,
/// <summary>
/// The tab key.
/// </summary>
Tab = 52,
/// <summary>
/// The backspace key.
/// </summary>
BackSpace = 53,
/// <summary>
/// The backspace key (equivalent to BackSpace).
/// </summary>
Back = 53,
/// <summary>
/// The insert key.
/// </summary>
Insert = 54,
/// <summary>
/// The delete key.
/// </summary>
Delete = 55,
/// <summary>
/// The page up key.
/// </summary>
PageUp = 56,
/// <summary>
/// The page down key.
/// </summary>
PageDown = 57,
/// <summary>
/// The home key.
/// </summary>
Home = 58,
/// <summary>
/// The end key.
/// </summary>
End = 59,
/// <summary>
/// The caps lock key.
/// </summary>
CapsLock = 60,
/// <summary>
/// The scroll lock key.
/// </summary>
ScrollLock = 61,
/// <summary>
/// The print screen key.
/// </summary>
PrintScreen = 62,
/// <summary>
/// The pause key.
/// </summary>
Pause = 63,
/// <summary>
/// The num lock key.
/// </summary>
NumLock = 64,
/// <summary>
/// The clear key (Keypad5 with NumLock disabled, on typical keyboards).
/// </summary>
Clear = 65,
/// <summary>
/// The sleep key.
/// </summary>
Sleep = 66,
/// <summary>
/// The keypad 0 key.
/// </summary>
Keypad0 = 67,
/// <summary>
/// The keypad 1 key.
/// </summary>
Keypad1 = 68,
/// <summary>
/// The keypad 2 key.
/// </summary>
Keypad2 = 69,
/// <summary>
/// The keypad 3 key.
/// </summary>
Keypad3 = 70,
/// <summary>
/// The keypad 4 key.
/// </summary>
Keypad4 = 71,
/// <summary>
/// The keypad 5 key.
/// </summary>
Keypad5 = 72,
/// <summary>
/// The keypad 6 key.
/// </summary>
Keypad6 = 73,
/// <summary>
/// The keypad 7 key.
/// </summary>
Keypad7 = 74,
/// <summary>
/// The keypad 8 key.
/// </summary>
Keypad8 = 75,
/// <summary>
/// The keypad 9 key.
/// </summary>
Keypad9 = 76,
/// <summary>
/// The keypad divide key.
/// </summary>
KeypadDivide = 77,
/// <summary>
/// The keypad multiply key.
/// </summary>
KeypadMultiply = 78,
/// <summary>
/// The keypad subtract key.
/// </summary>
KeypadSubtract = 79,
/// <summary>
/// The keypad minus key (equivalent to KeypadSubtract).
/// </summary>
KeypadMinus = 79,
/// <summary>
/// The keypad add key.
/// </summary>
KeypadAdd = 80,
/// <summary>
/// The keypad plus key (equivalent to KeypadAdd).
/// </summary>
KeypadPlus = 80,
/// <summary>
/// The keypad decimal key.
/// </summary>
KeypadDecimal = 81,
/// <summary>
/// The keypad period key (equivalent to KeypadDecimal).
/// </summary>
KeypadPeriod = 81,
/// <summary>
/// The keypad enter key.
/// </summary>
KeypadEnter = 82,
/// <summary>
/// The A key.
/// </summary>
A = 83,
/// <summary>
/// The B key.
/// </summary>
B = 84,
/// <summary>
/// The C key.
/// </summary>
C = 85,
/// <summary>
/// The D key.
/// </summary>
D = 86,
/// <summary>
/// The E key.
/// </summary>
E = 87,
/// <summary>
/// The F key.
/// </summary>
F = 88,
/// <summary>
/// The G key.
/// </summary>
G = 89,
/// <summary>
/// The H key.
/// </summary>
H = 90,
/// <summary>
/// The I key.
/// </summary>
I = 91,
/// <summary>
/// The J key.
/// </summary>
J = 92,
/// <summary>
/// The K key.
/// </summary>
K = 93,
/// <summary>
/// The L key.
/// </summary>
L = 94,
/// <summary>
/// The M key.
/// </summary>
M = 95,
/// <summary>
/// The N key.
/// </summary>
N = 96,
/// <summary>
/// The O key.
/// </summary>
O = 97,
/// <summary>
/// The P key.
/// </summary>
P = 98,
/// <summary>
/// The Q key.
/// </summary>
Q = 99,
/// <summary>
/// The R key.
/// </summary>
R = 100,
/// <summary>
/// The S key.
/// </summary>
S = 101,
/// <summary>
/// The T key.
/// </summary>
T = 102,
/// <summary>
/// The U key.
/// </summary>
U = 103,
/// <summary>
/// The V key.
/// </summary>
V = 104,
/// <summary>
/// The W key.
/// </summary>
W = 105,
/// <summary>
/// The X key.
/// </summary>
X = 106,
/// <summary>
/// The Y key.
/// </summary>
Y = 107,
/// <summary>
/// The Z key.
/// </summary>
Z = 108,
/// <summary>
/// The number 0 key.
/// </summary>
Number0 = 109,
/// <summary>
/// The number 1 key.
/// </summary>
Number1 = 110,
/// <summary>
/// The number 2 key.
/// </summary>
Number2 = 111,
/// <summary>
/// The number 3 key.
/// </summary>
Number3 = 112,
/// <summary>
/// The number 4 key.
/// </summary>
Number4 = 113,
/// <summary>
/// The number 5 key.
/// </summary>
Number5 = 114,
/// <summary>
/// The number 6 key.
/// </summary>
Number6 = 115,
/// <summary>
/// The number 7 key.
/// </summary>
Number7 = 116,
/// <summary>
/// The number 8 key.
/// </summary>
Number8 = 117,
/// <summary>
/// The number 9 key.
/// </summary>
Number9 = 118,
/// <summary>
/// The tilde key.
/// </summary>
Tilde = 119,
/// <summary>
/// The grave key (equivaent to Tilde).
/// </summary>
Grave = 119,
/// <summary>
/// The minus key.
/// </summary>
Minus = 120,
/// <summary>
/// The plus key.
/// </summary>
Plus = 121,
/// <summary>
/// The left bracket key.
/// </summary>
BracketLeft = 122,
/// <summary>
/// The left bracket key (equivalent to BracketLeft).
/// </summary>
LBracket = 122,
/// <summary>
/// The right bracket key.
/// </summary>
BracketRight = 123,
/// <summary>
/// The right bracket key (equivalent to BracketRight).
/// </summary>
RBracket = 123,
/// <summary>
/// The semicolon key.
/// </summary>
Semicolon = 124,
/// <summary>
/// The quote key.
/// </summary>
Quote = 125,
/// <summary>
/// The comma key.
/// </summary>
Comma = 126,
/// <summary>
/// The period key.
/// </summary>
Period = 127,
/// <summary>
/// The slash key.
/// </summary>
Slash = 128,
/// <summary>
/// The backslash key.
/// </summary>
BackSlash = 129,
/// <summary>
/// The secondary backslash key.
/// </summary>
NonUSBackSlash = 130,
/// <summary>
/// Indicates the last available keyboard key.
/// </summary>
LastKey = 131,
FirstMouseButton = 132,
/// <summary>
/// The left mouse button.
/// </summary>
MouseLeft = 132,
/// <summary>
/// The middle mouse button.
/// </summary>
MouseMiddle = 133,
/// <summary>
/// The right mouse button.
/// </summary>
MouseRight = 134,
/// <summary>
/// The first extra mouse button.
/// </summary>
MouseButton1 = 135,
/// <summary>
/// The second extra mouse button.
/// </summary>
MouseButton2 = 136,
/// <summary>
/// The third extra mouse button.
/// </summary>
MouseButton3 = 137,
/// <summary>
/// The fourth extra mouse button.
/// </summary>
MouseButton4 = 138,
/// <summary>
/// The fifth extra mouse button.
/// </summary>
MouseButton5 = 139,
/// <summary>
/// The sixth extra mouse button.
/// </summary>
MouseButton6 = 140,
/// <summary>
/// The seventh extra mouse button.
/// </summary>
MouseButton7 = 141,
/// <summary>
/// The eigth extra mouse button.
/// </summary>
MouseButton8 = 142,
/// <summary>
/// The ninth extra mouse button.
/// </summary>
MouseButton9 = 143,
/// <summary>
/// Indicates the last available mouse button.
/// </summary>
MouseLastButton = 144,
/// <summary>
/// Mouse wheel rolled up.
/// </summary>
MouseWheelUp = 145,
/// <summary>
/// Mouse wheel rolled down.
/// </summary>
MouseWheelDown = 146,
/// <summary>
/// Indicates the first available joystick button.
/// </summary>
FirstJoystickButton = 1024,
/// <summary>
/// Joystick button 1.
/// </summary>
Joystick1,
/// <summary>
/// Joystick button 2.
/// </summary>
Joystick2,
/// <summary>
/// Joystick button 3.
/// </summary>
Joystick3,
/// <summary>
/// Joystick button 4.
/// </summary>
Joystick4,
/// <summary>
/// Joystick button 5.
/// </summary>
Joystick5,
/// <summary>
/// Joystick button 6.
/// </summary>
Joystick6,
/// <summary>
/// Joystick button 7.
/// </summary>
Joystick7,
/// <summary>
/// Joystick button 8.
/// </summary>
Joystick8,
/// <summary>
/// Joystick button 9.
/// </summary>
Joystick9,
/// <summary>
/// Joystick button 10.
/// </summary>
Joystick10,
/// <summary>
/// Joystick button 11.
/// </summary>
Joystick11,
/// <summary>
/// Joystick button 12.
/// </summary>
Joystick12,
/// <summary>
/// Joystick button 13.
/// </summary>
Joystick13,
/// <summary>
/// Joystick button 14.
/// </summary>
Joystick14,
/// <summary>
/// Joystick button 15.
/// </summary>
Joystick15,
/// <summary>
/// Joystick button 16.
/// </summary>
Joystick16,
/// <summary>
/// Joystick button 17.
/// </summary>
Joystick17,
/// <summary>
/// Joystick button 18.
/// </summary>
Joystick18,
/// <summary>
/// Joystick button 19.
/// </summary>
Joystick19,
/// <summary>
/// Joystick button 20.
/// </summary>
Joystick20,
/// <summary>
/// Joystick button 21.
/// </summary>
Joystick21,
/// <summary>
/// Joystick button 22.
/// </summary>
Joystick22,
/// <summary>
/// Joystick button 23.
/// </summary>
Joystick23,
/// <summary>
/// Joystick button 24.
/// </summary>
Joystick24,
/// <summary>
/// Joystick button 25.
/// </summary>
Joystick25,
/// <summary>
/// Joystick button 26.
/// </summary>
Joystick26,
/// <summary>
/// Joystick button 27.
/// </summary>
Joystick27,
/// <summary>
/// Joystick button 28.
/// </summary>
Joystick28,
/// <summary>
/// Joystick button 29.
/// </summary>
Joystick29,
/// <summary>
/// Joystick button 30.
/// </summary>
Joystick30,
/// <summary>
/// Joystick button 31.
/// </summary>
Joystick31,
/// <summary>
/// Joystick button 32.
/// </summary>
Joystick32,
/// <summary>
/// Joystick button 33.
/// </summary>
Joystick33,
/// <summary>
/// Joystick button 34.
/// </summary>
Joystick34,
/// <summary>
/// Joystick button 35.
/// </summary>
Joystick35,
/// <summary>
/// Joystick button 36.
/// </summary>
Joystick36,
/// <summary>
/// Joystick button 37.
/// </summary>
Joystick37,
/// <summary>
/// Joystick button 38.
/// </summary>
Joystick38,
/// <summary>
/// Joystick button 39.
/// </summary>
Joystick39,
/// <summary>
/// Joystick button 40.
/// </summary>
Joystick40,
/// <summary>
/// Joystick button 41.
/// </summary>
Joystick41,
/// <summary>
/// Joystick button 42.
/// </summary>
Joystick42,
/// <summary>
/// Joystick button 43.
/// </summary>
Joystick43,
/// <summary>
/// Joystick button 44.
/// </summary>
Joystick44,
/// <summary>
/// Joystick button 45.
/// </summary>
Joystick45,
/// <summary>
/// Joystick button 46.
/// </summary>
Joystick46,
/// <summary>
/// Joystick button 47.
/// </summary>
Joystick47,
/// <summary>
/// Joystick button 48.
/// </summary>
Joystick48,
/// <summary>
/// Joystick button 49.
/// </summary>
Joystick49,
/// <summary>
/// Joystick button 50.
/// </summary>
Joystick50,
/// <summary>
/// Joystick button 51.
/// </summary>
Joystick51,
/// <summary>
/// Joystick button 52.
/// </summary>
Joystick52,
/// <summary>
/// Joystick button 53.
/// </summary>
Joystick53,
/// <summary>
/// Joystick button 54.
/// </summary>
Joystick54,
/// <summary>
/// Joystick button 55.
/// </summary>
Joystick55,
/// <summary>
/// Joystick button 56.
/// </summary>
Joystick56,
/// <summary>
/// Joystick button 57.
/// </summary>
Joystick57,
/// <summary>
/// Joystick button 58.
/// </summary>
Joystick58,
/// <summary>
/// Joystick button 59.
/// </summary>
Joystick59,
/// <summary>
/// Joystick button 60.
/// </summary>
Joystick60,
/// <summary>
/// Joystick button 61.
/// </summary>
Joystick61,
/// <summary>
/// Joystick button 62.
/// </summary>
Joystick62,
/// <summary>
/// Joystick button 63.
/// </summary>
Joystick63,
/// <summary>
/// Joystick button 64.
/// </summary>
Joystick64,
/// <summary>
/// Indicates the first available negative-axis joystick button.
/// </summary>
FirstJoystickAxisNegativeButton = 2048,
/// <summary>
/// Joystick axis 1 negative button.
/// </summary>
JoystickAxis1Negative,
/// <summary>
/// Joystick axis 2 negative button.
/// </summary>
JoystickAxis2Negative,
/// <summary>
/// Joystick axis 3 negative button.
/// </summary>
JoystickAxis3Negative,
/// <summary>
/// Joystick axis 4 negative button.
/// </summary>
JoystickAxis4Negative,
/// <summary>
/// Joystick axis 5 negative button.
/// </summary>
JoystickAxis5Negative,
/// <summary>
/// Joystick axis 6 negative button.
/// </summary>
JoystickAxis6Negative,
/// <summary>
/// Joystick axis 7 negative button.
/// </summary>
JoystickAxis7Negative,
/// <summary>
/// Joystick axis 8 negative button.
/// </summary>
JoystickAxis8Negative,
/// <summary>
/// Joystick axis 9 negative button.
/// </summary>
JoystickAxis9Negative,
/// <summary>
/// Joystick axis 10 negative button.
/// </summary>
JoystickAxis10Negative,
/// <summary>
/// Joystick axis 11 negative button.
/// </summary>
JoystickAxis11Negative,
/// <summary>
/// Joystick axis 12 negative button.
/// </summary>
JoystickAxis12Negative,
/// <summary>
/// Joystick axis 13 negative button.
/// </summary>
JoystickAxis13Negative,
/// <summary>
/// Joystick axis 14 negative button.
/// </summary>
JoystickAxis14Negative,
/// <summary>
/// Joystick axis 15 negative button.
/// </summary>
JoystickAxis15Negative,
/// <summary>
/// Joystick axis 16 negative button.
/// </summary>
JoystickAxis16Negative,
/// <summary>
/// Joystick axis 17 negative button.
/// </summary>
JoystickAxis17Negative,
/// <summary>
/// Joystick axis 18 negative button.
/// </summary>
JoystickAxis18Negative,
/// <summary>
/// Joystick axis 19 negative button.
/// </summary>
JoystickAxis19Negative,
/// <summary>
/// Joystick axis 20 negative button.
/// </summary>
JoystickAxis20Negative,
/// <summary>
/// Joystick axis 21 negative button.
/// </summary>
JoystickAxis21Negative,
/// <summary>
/// Joystick axis 22 negative button.
/// </summary>
JoystickAxis22Negative,
/// <summary>
/// Joystick axis 23 negative button.
/// </summary>
JoystickAxis23Negative,
/// <summary>
/// Joystick axis 24 negative button.
/// </summary>
JoystickAxis24Negative,
/// <summary>
/// Joystick axis 25 negative button.
/// </summary>
JoystickAxis25Negative,
/// <summary>
/// Joystick axis 26 negative button.
/// </summary>
JoystickAxis26Negative,
/// <summary>
/// Joystick axis 27 negative button.
/// </summary>
JoystickAxis27Negative,
/// <summary>
/// Joystick axis 28 negative button.
/// </summary>
JoystickAxis28Negative,
/// <summary>
/// Joystick axis 29 negative button.
/// </summary>
JoystickAxis29Negative,
/// <summary>
/// Joystick axis 30 negative button.
/// </summary>
JoystickAxis30Negative,
/// <summary>
/// Joystick axis 31 negative button.
/// </summary>
JoystickAxis31Negative,
/// <summary>
/// Joystick axis 32 negative button.
/// </summary>
JoystickAxis32Negative,
/// <summary>
/// Joystick axis 33 negative button.
/// </summary>
JoystickAxis33Negative,
/// <summary>
/// Joystick axis 34 negative button.
/// </summary>
JoystickAxis34Negative,
/// <summary>
/// Joystick axis 35 negative button.
/// </summary>
JoystickAxis35Negative,
/// <summary>
/// Joystick axis 36 negative button.
/// </summary>
JoystickAxis36Negative,
/// <summary>
/// Joystick axis 37 negative button.
/// </summary>
JoystickAxis37Negative,
/// <summary>
/// Joystick axis 38 negative button.
/// </summary>
JoystickAxis38Negative,
/// <summary>
/// Joystick axis 39 negative button.
/// </summary>
JoystickAxis39Negative,
/// <summary>
/// Joystick axis 40 negative button.
/// </summary>
JoystickAxis40Negative,
/// <summary>
/// Joystick axis 41 negative button.
/// </summary>
JoystickAxis41Negative,
/// <summary>
/// Joystick axis 42 negative button.
/// </summary>
JoystickAxis42Negative,
/// <summary>
/// Joystick axis 43 negative button.
/// </summary>
JoystickAxis43Negative,
/// <summary>
/// Joystick axis 44 negative button.
/// </summary>
JoystickAxis44Negative,
/// <summary>
/// Joystick axis 45 negative button.
/// </summary>
JoystickAxis45Negative,
/// <summary>
/// Joystick axis 46 negative button.
/// </summary>
JoystickAxis46Negative,
/// <summary>
/// Joystick axis 47 negative button.
/// </summary>
JoystickAxis47Negative,
/// <summary>
/// Joystick axis 48 negative button.
/// </summary>
JoystickAxis48Negative,
/// <summary>
/// Joystick axis 49 negative button.
/// </summary>
JoystickAxis49Negative,
/// <summary>
/// Joystick axis 50 negative button.
/// </summary>
JoystickAxis50Negative,
/// <summary>
/// Joystick axis 51 negative button.
/// </summary>
JoystickAxis51Negative,
/// <summary>
/// Joystick axis 52 negative button.
/// </summary>
JoystickAxis52Negative,
/// <summary>
/// Joystick axis 53 negative button.
/// </summary>
JoystickAxis53Negative,
/// <summary>
/// Joystick axis 54 negative button.
/// </summary>
JoystickAxis54Negative,
/// <summary>
/// Joystick axis 55 negative button.
/// </summary>
JoystickAxis55Negative,
/// <summary>
/// Joystick axis 56 negative button.
/// </summary>
JoystickAxis56Negative,
/// <summary>
/// Joystick axis 57 negative button.
/// </summary>
JoystickAxis57Negative,
/// <summary>
/// Joystick axis 58 negative button.
/// </summary>
JoystickAxis58Negative,
/// <summary>
/// Joystick axis 59 negative button.
/// </summary>
JoystickAxis59Negative,
/// <summary>
/// Joystick axis 60 negative button.
/// </summary>
JoystickAxis60Negative,
/// <summary>
/// Joystick axis 61 negative button.
/// </summary>
JoystickAxis61Negative,
/// <summary>
/// Joystick axis 62 negative button.
/// </summary>
JoystickAxis62Negative,
/// <summary>
/// Joystick axis 63 negative button.
/// </summary>
JoystickAxis63Negative,
/// <summary>
/// Joystick axis 64 negative button.
/// </summary>
JoystickAxis64Negative,
/// <summary>
/// Indicates the first available positive-axis joystick button.
/// </summary>
FirstJoystickAxisPositiveButton = 3072,
/// <summary>
/// Joystick axis 1 positive button.
/// </summary>
JoystickAxis1Positive,
/// <summary>
/// Joystick axis 2 positive button.
/// </summary>
JoystickAxis2Positive,
/// <summary>
/// Joystick axis 3 positive button.
/// </summary>
JoystickAxis3Positive,
/// <summary>
/// Joystick axis 4 positive button.
/// </summary>
JoystickAxis4Positive,
/// <summary>
/// Joystick axis 5 positive button.
/// </summary>
JoystickAxis5Positive,
/// <summary>
/// Joystick axis 6 positive button.
/// </summary>
JoystickAxis6Positive,
/// <summary>
/// Joystick axis 7 positive button.
/// </summary>
JoystickAxis7Positive,
/// <summary>
/// Joystick axis 8 positive button.
/// </summary>
JoystickAxis8Positive,
/// <summary>
/// Joystick axis 9 positive button.
/// </summary>
JoystickAxis9Positive,
/// <summary>
/// Joystick axis 10 positive button.
/// </summary>
JoystickAxis10Positive,
/// <summary>
/// Joystick axis 11 positive button.
/// </summary>
JoystickAxis11Positive,
/// <summary>
/// Joystick axis 12 positive button.
/// </summary>
JoystickAxis12Positive,
/// <summary>
/// Joystick axis 13 positive button.
/// </summary>
JoystickAxis13Positive,
/// <summary>
/// Joystick axis 14 positive button.
/// </summary>
JoystickAxis14Positive,
/// <summary>
/// Joystick axis 15 positive button.
/// </summary>
JoystickAxis15Positive,
/// <summary>
/// Joystick axis 16 positive button.
/// </summary>
JoystickAxis16Positive,
/// <summary>
/// Joystick axis 17 positive button.
/// </summary>
JoystickAxis17Positive,
/// <summary>
/// Joystick axis 18 positive button.
/// </summary>
JoystickAxis18Positive,
/// <summary>
/// Joystick axis 19 positive button.
/// </summary>
JoystickAxis19Positive,
/// <summary>
/// Joystick axis 20 positive button.
/// </summary>
JoystickAxis20Positive,
/// <summary>
/// Joystick axis 21 positive button.
/// </summary>
JoystickAxis21Positive,
/// <summary>
/// Joystick axis 22 positive button.
/// </summary>
JoystickAxis22Positive,
/// <summary>
/// Joystick axis 23 positive button.
/// </summary>
JoystickAxis23Positive,
/// <summary>
/// Joystick axis 24 positive button.
/// </summary>
JoystickAxis24Positive,
/// <summary>
/// Joystick axis 25 positive button.
/// </summary>
JoystickAxis25Positive,
/// <summary>
/// Joystick axis 26 positive button.
/// </summary>
JoystickAxis26Positive,
/// <summary>
/// Joystick axis 27 positive button.
/// </summary>
JoystickAxis27Positive,
/// <summary>
/// Joystick axis 28 positive button.
/// </summary>
JoystickAxis28Positive,
/// <summary>
/// Joystick axis 29 positive button.
/// </summary>
JoystickAxis29Positive,
/// <summary>
/// Joystick axis 30 positive button.
/// </summary>
JoystickAxis30Positive,
/// <summary>
/// Joystick axis 31 positive button.
/// </summary>
JoystickAxis31Positive,
/// <summary>
/// Joystick axis 32 positive button.
/// </summary>
JoystickAxis32Positive,
/// <summary>
/// Joystick axis 33 positive button.
/// </summary>
JoystickAxis33Positive,
/// <summary>
/// Joystick axis 34 positive button.
/// </summary>
JoystickAxis34Positive,
/// <summary>
/// Joystick axis 35 positive button.
/// </summary>
JoystickAxis35Positive,
/// <summary>
/// Joystick axis 36 positive button.
/// </summary>
JoystickAxis36Positive,
/// <summary>
/// Joystick axis 37 positive button.
/// </summary>
JoystickAxis37Positive,
/// <summary>
/// Joystick axis 38 positive button.
/// </summary>
JoystickAxis38Positive,
/// <summary>
/// Joystick axis 39 positive button.
/// </summary>
JoystickAxis39Positive,
/// <summary>
/// Joystick axis 40 positive button.
/// </summary>
JoystickAxis40Positive,
/// <summary>
/// Joystick axis 41 positive button.
/// </summary>
JoystickAxis41Positive,
/// <summary>
/// Joystick axis 42 positive button.
/// </summary>
JoystickAxis42Positive,
/// <summary>
/// Joystick axis 43 positive button.
/// </summary>
JoystickAxis43Positive,
/// <summary>
/// Joystick axis 44 positive button.
/// </summary>
JoystickAxis44Positive,
/// <summary>
/// Joystick axis 45 positive button.
/// </summary>
JoystickAxis45Positive,
/// <summary>
/// Joystick axis 46 positive button.
/// </summary>
JoystickAxis46Positive,
/// <summary>
/// Joystick axis 47 positive button.
/// </summary>
JoystickAxis47Positive,
/// <summary>
/// Joystick axis 48 positive button.
/// </summary>
JoystickAxis48Positive,
/// <summary>
/// Joystick axis 49 positive button.
/// </summary>
JoystickAxis49Positive,
/// <summary>
/// Joystick axis 50 positive button.
/// </summary>
JoystickAxis50Positive,
/// <summary>
/// Joystick axis 51 positive button.
/// </summary>
JoystickAxis51Positive,
/// <summary>
/// Joystick axis 52 positive button.
/// </summary>
JoystickAxis52Positive,
/// <summary>
/// Joystick axis 53 positive button.
/// </summary>
JoystickAxis53Positive,
/// <summary>
/// Joystick axis 54 positive button.
/// </summary>
JoystickAxis54Positive,
/// <summary>
/// Joystick axis 55 positive button.
/// </summary>
JoystickAxis55Positive,
/// <summary>
/// Joystick axis 56 positive button.
/// </summary>
JoystickAxis56Positive,
/// <summary>
/// Joystick axis 57 positive button.
/// </summary>
JoystickAxis57Positive,
/// <summary>
/// Joystick axis 58 positive button.
/// </summary>
JoystickAxis58Positive,
/// <summary>
/// Joystick axis 59 positive button.
/// </summary>
JoystickAxis59Positive,
/// <summary>
/// Joystick axis 60 positive button.
/// </summary>
JoystickAxis60Positive,
/// <summary>
/// Joystick axis 61 positive button.
/// </summary>
JoystickAxis61Positive,
/// <summary>
/// Joystick axis 62 positive button.
/// </summary>
JoystickAxis62Positive,
/// <summary>
/// Joystick axis 63 positive button.
/// </summary>
JoystickAxis63Positive,
/// <summary>
/// Joystick axis 64 positive button.
/// </summary>
JoystickAxis64Positive,
/// <summary>
/// Indicates the first available joystick hat up button.
/// </summary>
FirstJoystickHatUpButton = 4096,
/// <summary>
/// Joystick hat 1 up button.
/// </summary>
JoystickHat1Up,
/// <summary>
/// Joystick hat 2 up button.
/// </summary>
JoystickHat2Up,
/// <summary>
/// Joystick hat 3 up button.
/// </summary>
JoystickHat3Up,
/// <summary>
/// Joystick hat 4 up button.
/// </summary>
JoystickHat4Up,
/// <summary>
/// Indicates the first available joystick hat down button.
/// </summary>
FirstJoystickHatDownButton = 5120,
/// <summary>
/// Joystick hat 1 down button.
/// </summary>
JoystickHat1Down,
/// <summary>
/// Joystick hat 2 down button.
/// </summary>
JoystickHat2Down,
/// <summary>
/// Joystick hat 3 down button.
/// </summary>
JoystickHat3Down,
/// <summary>
/// Joystick hat 4 down button.
/// </summary>
JoystickHat4Down,
/// <summary>
/// Indicates the first available joystick hat left button.
/// </summary>
FirstJoystickHatLeftButton = 6144,
/// <summary>
/// Joystick hat 1 left button.
/// </summary>
JoystickHat1Left,
/// <summary>
/// Joystick hat 2 left button.
/// </summary>
JoystickHat2Left,
/// <summary>
/// Joystick hat 3 left button.
/// </summary>
JoystickHat3Left,
/// <summary>
/// Joystick hat 4 left button.
/// </summary>
JoystickHat4Left,
/// <summary>
/// Indicates the first available joystick hat right button.
/// </summary>
FirstJoystickHatRightButton = 7168,
/// <summary>
/// Joystick hat 1 right button.
/// </summary>
JoystickHat1Right,
/// <summary>
/// Joystick hat 2 right button.
/// </summary>
JoystickHat2Right,
/// <summary>
/// Joystick hat 3 right button.
/// </summary>
JoystickHat3Right,
/// <summary>
/// Joystick hat 4 right button.
/// </summary>
JoystickHat4Right,
}
}
| |
using System;
using System.IO;
using Xunit;
using PwSafe = Medo.Security.Cryptography.PasswordSafe;
namespace PasswordSafe.Test {
public class EntryTests {
[Fact(DisplayName = "PasswordSafe: Entry: New")]
public void Entry_New() {
var entry = new PwSafe.Entry();
Assert.Equal(3, entry.Records.Count);
Assert.True(entry.Records.Contains(PwSafe.RecordType.Uuid));
Assert.True(entry.Records.Contains(PwSafe.RecordType.Title));
Assert.True(entry.Records.Contains(PwSafe.RecordType.Password));
Assert.True(entry.Uuid != Guid.Empty);
Assert.Equal("", entry.Title);
Assert.Equal("", entry.Password);
}
[Fact(DisplayName = "PasswordSafe: Entry: New with Title")]
public void Entry_New_WithTitle() {
var entry = new PwSafe.Entry("Test");
Assert.Equal(3, entry.Records.Count);
Assert.True(entry.Records.Contains(PwSafe.RecordType.Uuid));
Assert.True(entry.Records.Contains(PwSafe.RecordType.Title));
Assert.True(entry.Records.Contains(PwSafe.RecordType.Password));
Assert.True(entry.Uuid != Guid.Empty);
Assert.Equal("Test", entry.Title);
Assert.Equal("", entry.Password);
}
[Fact(DisplayName = "PasswordSafe: Entry: Clone")]
public void Entry_Clone() {
var entry = new PwSafe.Entry("Test");
Assert.Equal(3, entry.Records.Count);
Assert.True(entry.Records.Contains(PwSafe.RecordType.Uuid));
Assert.True(entry.Records.Contains(PwSafe.RecordType.Title));
Assert.True(entry.Records.Contains(PwSafe.RecordType.Password));
Assert.True(entry.Uuid != Guid.Empty);
Assert.Equal("Test", entry.Title);
Assert.Equal("", entry.Password);
var clone = entry.Clone();
Assert.Equal(3, clone.Records.Count);
Assert.True(clone.Records.Contains(PwSafe.RecordType.Uuid));
Assert.True(clone.Records.Contains(PwSafe.RecordType.Title));
Assert.True(clone.Records.Contains(PwSafe.RecordType.Password));
Assert.True(clone.Uuid != Guid.Empty);
Assert.Equal("Test", clone.Title);
Assert.Equal("", clone.Password);
}
[Fact(DisplayName = "PasswordSafe: Entry: Clone (in document)")]
public void Entry_Clone_Document() {
var doc = new PwSafe.Document("Password");
doc.Entries.Add(new PwSafe.Entry("Test"));
doc.Save(new MemoryStream());
doc.Entries[0].Clone();
Assert.Equal(false, doc.HasChanged);
}
[Fact(DisplayName = "PasswordSafe: Entry: Change (read-only)")]
public void Entry_ReadOnly() {
Assert.Throws<NotSupportedException>(() => {
var doc = new PwSafe.Document("Password");
doc.Entries["Test"].Password = "Old";
doc.IsReadOnly = true;
doc.Entries["Test"].Password = "New";
});
}
[Fact(DisplayName = "PasswordSafe: Entry: Indexer Get via Type")]
public void Entry_AccessByRecordType() {
var doc = new PwSafe.Document("Password");
doc.Entries["Test"].Password = "Old";
Assert.True(doc.Entries["Test"][PwSafe.RecordType.Uuid].Uuid != Guid.Empty);
Assert.Equal("Old", doc.Entries["Test"][PwSafe.RecordType.Password].Text);
doc.Entries["Test"][PwSafe.RecordType.Password].Text = "New";
Assert.Equal("New", doc.Entries["Test"][PwSafe.RecordType.Password].Text);
}
[Fact(DisplayName = "PasswordSafe: Entry: Add")]
public void Entry_TestNamed() {
var guid = Guid.NewGuid();
var doc = new PwSafe.Document("Password") { TrackAccess = false, TrackModify = false };
var entry = new PwSafe.Entry();
doc.Entries.Add(entry);
entry.Uuid = guid;
entry.Group = "Group";
entry.Title = "Title";
entry.UserName = "UserName";
entry.Notes = "Notes";
entry.Password = "Password";
entry.CreationTime = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc);
entry.PasswordModificationTime = new DateTime(2002, 1, 1, 0, 0, 0, DateTimeKind.Utc);
entry.LastAccessTime = new DateTime(2003, 1, 1, 0, 0, 0, DateTimeKind.Utc);
entry.PasswordExpiryTime = new DateTime(2004, 1, 1, 0, 0, 0, DateTimeKind.Utc);
entry.LastModificationTime = new DateTime(2005, 1, 1, 0, 0, 0, DateTimeKind.Utc);
entry.Url = "http://example.com";
entry.Email = "[email protected]";
entry.TwoFactorKey = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
entry.CreditCardNumber = "1234 5678 9012 3456";
entry.CreditCardExpiration = "Title";
entry.CreditCardVerificationValue = "0987";
entry.CreditCardPin = "6543";
entry.QRCode = "https://medo64.com/";
Assert.Equal(guid, entry.Uuid);
Assert.Equal("Group", (string)entry.Group);
Assert.Equal("Title", entry.Title);
Assert.Equal("UserName", entry.UserName);
Assert.Equal("Notes", entry.Notes);
Assert.Equal("Password", entry.Password);
Assert.Equal(new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc), entry.CreationTime);
Assert.Equal(new DateTime(2002, 1, 1, 0, 0, 0, DateTimeKind.Utc), entry.PasswordModificationTime);
Assert.Equal(new DateTime(2003, 1, 1, 0, 0, 0, DateTimeKind.Utc), entry.LastAccessTime);
Assert.Equal(new DateTime(2004, 1, 1, 0, 0, 0, DateTimeKind.Utc), entry.PasswordExpiryTime);
Assert.Equal(new DateTime(2005, 1, 1, 0, 0, 0, DateTimeKind.Utc), entry.LastModificationTime);
Assert.Equal("http://example.com", entry.Url);
Assert.Equal("[email protected]", entry.Email);
Assert.Equal("00-01-02-03-04-05-06-07-08-09", BitConverter.ToString(entry.TwoFactorKey));
Assert.Equal("1234 5678 9012 3456", entry.CreditCardNumber);
Assert.Equal("Title", entry.CreditCardExpiration);
Assert.Equal("0987", entry.CreditCardVerificationValue);
Assert.Equal("6543", entry.CreditCardPin);
Assert.Equal("https://medo64.com/", entry.QRCode);
Assert.Equal(guid, entry[PwSafe.RecordType.Uuid].Uuid);
Assert.Equal("Group", entry[PwSafe.RecordType.Group].Text);
Assert.Equal("Title", entry[PwSafe.RecordType.Title].Text);
Assert.Equal("UserName", entry[PwSafe.RecordType.UserName].Text);
Assert.Equal("Notes", entry[PwSafe.RecordType.Notes].Text);
Assert.Equal("Password", entry[PwSafe.RecordType.Password].Text);
Assert.Equal(new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc), entry[PwSafe.RecordType.CreationTime].Time);
Assert.Equal(new DateTime(2002, 1, 1, 0, 0, 0, DateTimeKind.Utc), entry[PwSafe.RecordType.PasswordModificationTime].Time);
Assert.Equal(new DateTime(2003, 1, 1, 0, 0, 0, DateTimeKind.Utc), entry[PwSafe.RecordType.LastAccessTime].Time);
Assert.Equal(new DateTime(2004, 1, 1, 0, 0, 0, DateTimeKind.Utc), entry[PwSafe.RecordType.PasswordExpiryTime].Time);
Assert.Equal(new DateTime(2005, 1, 1, 0, 0, 0, DateTimeKind.Utc), entry[PwSafe.RecordType.LastModificationTime].Time);
Assert.Equal("http://example.com", entry[PwSafe.RecordType.Url].Text);
Assert.Equal("[email protected]", entry[PwSafe.RecordType.EmailAddress].Text);
Assert.Equal("00-01-02-03-04-05-06-07-08-09", BitConverter.ToString(entry[PwSafe.RecordType.TwoFactorKey].GetBytes()));
Assert.Equal("1234 5678 9012 3456", entry[PwSafe.RecordType.CreditCardNumber].Text);
Assert.Equal("Title", entry[PwSafe.RecordType.CreditCardExpiration].Text);
Assert.Equal("0987", entry[PwSafe.RecordType.CreditCardVerificationValue].Text);
Assert.Equal("6543", entry[PwSafe.RecordType.CreditCardPin].Text);
Assert.Equal("https://medo64.com/", entry[PwSafe.RecordType.QRCode].Text);
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (default tokens)")]
public void Entry_Autotype_Tokens_Default() {
Assert.Equal("UserName {Tab} Password {Enter}", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(null)));
Assert.Equal("D e f a u l t {Tab} P a s s w 0 r d {Enter}", string.Join(" ", GetExampleEntry(null).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (two-factor)")]
public void Entry_Autotype_Tokens_TwoFactor() {
var autoTypeText = @"\u\t\p\t\2\t\n";
Assert.Equal("UserName {Tab} Password {Tab} TwoFactorCode {Tab} {Enter}", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("D e f a u l t {Tab} P a s s w 0 r d {Tab} TwoFactorCode {Tab} {Enter}", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (some text)")]
public void Entry_Autotype_Tokens_SomeText1() {
var autoTypeText = @"admin\n\p\n";
Assert.Equal("a d m i n {Enter} Password {Enter}", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("a d m i n {Enter} P a s s w 0 r d {Enter}", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (some text 2)")]
public void Entry_Autotype_Tokens_SomeText2() {
var autoTypeText = @"\badmin\n\p\n";
Assert.Equal("{Backspace} a d m i n {Enter} Password {Enter}", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("{Backspace} a d m i n {Enter} P a s s w 0 r d {Enter}", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (some text 3)")]
public void Entry_Autotype_Tokens_SomeText3() {
var autoTypeText = @"admin\n\p\nXXX";
Assert.Equal("a d m i n {Enter} Password {Enter} X X X", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("a d m i n {Enter} P a s s w 0 r d {Enter} X X X", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (credit card)")]
public void Entry_Autotype_Tokens_CreditCard() {
var autoTypeText = @"\cn\t\ce\t\cv\t\cp";
Assert.Equal("CreditCardNumber {Tab} CreditCardExpiration {Tab} CreditCardVerificationValue {Tab} CreditCardPin", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 {Tab} 0 1 / 7 9 {Tab} 1 2 3 {Tab} 1 2 3 4", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (credit card, tabbed)")]
public void Entry_Autotype_Tokens_CreditCardTabbed() {
var autoTypeText = @"\ct\t\ce\t\cv\t\cp";
Assert.Equal("CreditCardNumberTabbed {Tab} CreditCardExpiration {Tab} CreditCardVerificationValue {Tab} CreditCardPin", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("1 2 3 4 {Tab} 5 6 7 8 {Tab} 9 0 1 2 {Tab} 3 4 5 6 {Tab} 0 1 / 7 9 {Tab} 1 2 3 {Tab} 1 2 3 4", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (credit card, tabbed Amex)")]
public void Entry_Autotype_Tokens_CreditCardTabbedAmex() {
var autoTypeText = @"\ct\t\ce\t\cv\t\cp";
Assert.Equal("CreditCardNumberTabbed {Tab} CreditCardExpiration {Tab} CreditCardVerificationValue {Tab} CreditCardPin", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("1 2 3 {Tab} 4 5 6 7 {Tab} 8 9 0 1 {Tab} 2 3 4 5 {Tab} 0 1 / 7 9 {Tab} 1 2 3 {Tab} 1 2 3 4", string.Join(" ", GetExampleEntry(autoTypeText, amexCard: true).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (optional number, not used)")]
public void Entry_Autotype_Tokens_OptionalNumberNotUsed() {
var autoTypeText = @"\oTest";
Assert.Equal("Notes T e s t", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("1 {Enter} 2 {Enter} 3 {Enter} {^} {Enter} T e s t", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (optional number, line 1)")]
public void Entry_Autotype_Tokens_OptionalNumber_Line1() {
var autoTypeText = @"\o1Test";
Assert.Equal("Notes:1 T e s t", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("1 T e s t", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (optional number, line 2)")]
public void Entry_Autotype_Tokens_OptionalNumber_Line2() {
var autoTypeText = @"\o2Test";
Assert.Equal("Notes:2 T e s t", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("2 T e s t", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (optional number, line 3)")]
public void Entry_Autotype_Tokens_OptionalNumber_Line3() {
var autoTypeText = @"\o3Test";
Assert.Equal("Notes:3 T e s t", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("3 T e s t", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (optional number, line 4)")]
public void Entry_Autotype_Tokens_OptionalNumber_Line4() {
var autoTypeText = @"\o4Test";
Assert.Equal("Notes:4 T e s t", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("{^} T e s t", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (optional number, line 5)")]
public void Entry_Autotype_Tokens_OptionalNumber_Line5() {
var autoTypeText = @"\o5Test";
Assert.Equal("Notes:5 T e s t", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("T e s t", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (optional number, single digit)")]
public void Entry_Autotype_Tokens_OptionalNumberOneDigit() {
var autoTypeText = @"\o9Test";
Assert.Equal("Notes:9 T e s t", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("T e s t", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (optional number, two digit)")]
public void Entry_Autotype_Tokens_OptionalNumberTwoDigits() {
var autoTypeText = @"\o98Test";
Assert.Equal("Notes:98 T e s t", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("T e s t", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (optional number, three digits)")]
public void Entry_Autotype_Tokens_OptionalNumberThreeDigits() {
var autoTypeText = @"\o987Test";
Assert.Equal("Notes:987 T e s t", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("T e s t", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (optional number, no suffix)")]
public void Entry_Autotype_Tokens_OptionalNumberNoSuffix() {
var autoTypeText = @"\o12";
Assert.Equal("Notes:12", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (mandatory number, single digit)")]
public void Entry_Autotype_Tokens_MandatoryNumberOneDigit() {
var autoTypeText = @"\W1Test";
Assert.Equal("Wait:1000 T e s t", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("Wait:1000 T e s t", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (mandatory number, two digits)")]
public void Entry_Autotype_Tokens_MandatoryNumberTwoDigit() {
var autoTypeText = @"\w12Test";
Assert.Equal("Wait:12 T e s t", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("Wait:12 T e s t", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (mandatory number, three digits)")]
public void Entry_Autotype_Tokens_MandatoryNumberThreeDigit() {
var autoTypeText = @"\d123Test";
Assert.Equal("Delay:123 T e s t", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("Delay:123 T e s t", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (mandatory number, no suffix)")]
public void Entry_Autotype_Tokens_MandatoryNumberNoSuffix() {
var autoTypeText = @"\d12";
Assert.Equal("Delay:12", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("Delay:12", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (example 1)")]
public void Entry_Autotype_Tokens_Example1() {
var autoTypeText = @"\z\u\t\p\n";
Assert.Equal("Legacy UserName {Tab} Password {Enter}", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("Legacy D e f a u l t {Tab} P a s s w 0 r d {Enter}", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype (example 2)")]
public void Entry_Autotype_Tokens_Example2() {
var autoTypeText = @"\i\g\l\m";
Assert.Equal("Title Group Url Email", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("E x a m p l e E x a m p l e s m e d o 6 4 . c o m t e s t @ e x a m p l e . c o m", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
#region Typos
[Fact(DisplayName = "PasswordSafe: Entry: Autotype typo (no escape)")]
public void Entry_Autotype_Tokens_TypoNoEscape() {
var autoTypeText = @"\x";
Assert.Equal("x", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("x", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype typo (no escape, two char)")]
public void Entry_Autotype_Tokens_TypoNoEscapeDouble() {
var autoTypeText = @"\cx\p";
Assert.Equal("c x Password", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal("c x P a s s w 0 r d", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype typo (no escape, hanging escape)")]
public void Entry_Autotype_Tokens_HangingEscape() {
var autoTypeText = @"admin\";
Assert.Equal(@"a d m i n \", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal(@"a d m i n \", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype typo (optional number, too long)")]
public void Entry_Autotype_Tokens_OptionalNumberTooLong() {
var autoTypeText = @"\o1234";
Assert.Equal(@"Notes:123 4", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal(@"4", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype typo (mandatory number, too long)")]
public void Entry_Autotype_Tokens_MandatoryNumberTooLong() {
var autoTypeText = @"\w1234";
Assert.Equal(@"Wait:123 4", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal(@"Wait:123 4", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype typo (mandatory number, invalid number)")]
public void Entry_Autotype_Tokens_MandatoryNumberNotPresent() {
var autoTypeText = @"\dX";
Assert.Equal(@"d X", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal(@"d X", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
[Fact(DisplayName = "PasswordSafe: Entry: Autotype typo (mandatory number, no number)")]
public void Entry_Autotype_Tokens_MandatoryIncompleteCommand() {
var autoTypeText = @"\W";
Assert.Equal(@"W", string.Join(" ", PwSafe.AutotypeToken.GetUnexpandedAutotypeTokens(autoTypeText)));
Assert.Equal(@"W", string.Join(" ", GetExampleEntry(autoTypeText).AutotypeTokens));
}
private static PwSafe.Entry GetExampleEntry(string autotypeText, bool amexCard = false) {
var entry = new PwSafe.Entry() {
Title = "Example",
Group = "Examples",
UserName = "Default",
Password = "Passw0rd",
CreditCardNumber = amexCard ? "123 4567 8901 2345" : "1234 5678 9012 3456",
CreditCardExpiration = "01/79",
CreditCardVerificationValue = "123",
CreditCardPin = "1234",
TwoFactorKey = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
Email = "[email protected]",
Url = "medo64.com",
Notes = "1\r\n2\n3\r^\n",
};
if (autotypeText != null) { entry.Autotype = autotypeText; }
return entry;
}
#endregion
}
}
| |
//==============================================================================
// TorqueLab ->
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
$BasicClouds::Default_["texture0"] = "art/gfx/skies/clouds/cloud1.png";
$BasicClouds::Default_["texture1"] = "art/gfx/skies/clouds/cloud2.png";
$BasicClouds::Default_["texture2"] = "art/gfx/skies/clouds/cloud3.png";
//==============================================================================
// Prepare the default config array for the Scene Editor Plugin
//SEP_AmbientManager.buildBasicCloudsParams();
function SEP_AmbientManager::buildBasicCloudsParams( %this ) {
%arCfg = Lab.createBaseParamsArray("SEP_BasicClouds",SEP_BasicClouds_StockParam);
%arCfg.updateFunc = "SEP_AmbientManager.updateBasicCloudsParam";
%arCfg.useNewSystem = true;
//%arCfg.arrayOnly = true;
//%arCfg.group[%gid++] = "Cloud Layer #1" TAB "Stack StackA";
%arCfg.setVal("layerEnabled[0]", "" TAB "Enabled" TAB "Checkbox" TAB "" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texture[0]", "" TAB "Texture" TAB "FileSelect" TAB "callback>>SEP_AmbientManager.getBasicCloudTexture(0);" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texScale[0]", "" TAB "Layer scale" TAB "SliderEdit" TAB "range>>0 5" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texDirection[0]", "" TAB "Layer direction" TAB "TextEdit" TAB "" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texSpeed[0]", "" TAB "Layer speed" TAB "SliderEdit" TAB "range>>0 5" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texOffset[0]", "" TAB "Layer offset" TAB "TextEdit" TAB "" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("height[0]", "" TAB "Layer heigth0" TAB "SliderEdit" TAB "range>>0 10;;tickAt 1" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
//%arCfg.group[%gid++] = "Cloud Layer #2" TAB "Stack StackA";
%arCfg.setVal("layerEnabled[1]", "" TAB "Enabled" TAB "Checkbox" TAB "" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texture[1]", "" TAB "Texture" TAB "FileSelect" TAB "callback>>SEP_AmbientManager.getBasicCloudTexture(1);" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texScale[1]", "" TAB "Layer scale" TAB "SliderEdit" TAB "range>>0 5" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texDirection[1]", "" TAB "Layer direction" TAB "TextEdit" TAB "" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texSpeed[1]", "" TAB "Layer speed" TAB "SliderEdit" TAB "range>>0 5" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texOffset[1]", "" TAB "Layer offset" TAB "TextEdit" TAB "" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("height[1]", "" TAB "Layer heigth1" TAB "SliderEdit" TAB "range>>0 10;;tickAt 1" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
//%arCfg.group[%gid++] = "Cloud Layer #3" TAB "Stack StackA";
%arCfg.setVal("layerEnabled[2]", "" TAB "Enabled" TAB "Checkbox" TAB "" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texture[2]", "" TAB "Texture" TAB "FileSelect" TAB "callback>>SEP_AmbientManager.getBasicCloudTexture(2);" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texScale[2]", "" TAB "Layer scale" TAB "SliderEdit" TAB "range>>0 5" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texDirection[2]", "" TAB "Layer direction" TAB "TextEdit" TAB "" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texSpeed[2]", "" TAB "Layer speed" TAB "SliderEdit" TAB "range>>0 5" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("texOffset[2]", "" TAB "Layer offset" TAB "TextEdit" TAB "" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
%arCfg.setVal("height[2]", "" TAB "Layer heigth2" TAB "SliderEdit" TAB "range>>0 10;;tickAt 1" TAB "SEP_AmbientManager.selectedBasicClouds" TAB %gid);
//buildParamsArray(%arCfg,false);
%this.BasicCloudsParamArray = %arCfg;
}
//------------------------------------------------------------------------------
//==============================================================================
function SEP_AmbientManager::updateBasicCloudsParam(%this,%field,%value,%ctrl,%arg1,%arg2,%arg3) {
logd("SEP_AmbientManager::updateBasicCloudsParam(%this,%field,%value,%ctrl,%arg1,%arg2,%arg3)",%this,%field,%value,%ctrl,%arg1,%arg2,%arg3);
%fieldData = strreplace(%field,"["," ");
%fieldData = strreplace(%fieldData,"]","");
%this.updateBasicCloudField(getWord(%fieldData,0),%value, getWord(%fieldData,1));
}
//------------------------------------------------------------------------------
//==============================================================================
// Sync the current profile values into the params objects
function SEP_AmbientManager::getBasicCloudTexture( %this,%layer ) {
/*if(Canvas.isCursorOn())
{
devLog("Cursor is on");
Canvas.cursorOff();
// TLabGameGui.noCursor = 0;
}*/
%this.currentBasicClouds = %layer;
%currentFile = $GLab_SelectedObject.bitmap;
//Canvas.cursorOff();
getLoadFilename("*.*|*.*", "SEP_AmbientManager.setBasicCloudTexture", %currentFile);
}
//------------------------------------------------------------------------------
//==============================================================================
// Sync the current profile values into the params objects
function SEP_AmbientManager::setBasicCloudTexture( %this,%file ) {
%filename = makeRelativePath( %file, getMainDotCsDir() );
%layer = %this.currentBasicClouds;
%this.updateBasicCloudField("texture",%filename,%layer);
%textEdit = SEP_BasicClouds_StockParam.findObjectByInternalName("texture["@%layer@"]",true);
%textEdit.setText(%filename);
}
//------------------------------------------------------------------------------
//==============================================================================
// Sync the current profile values into the params objects
function SEP_AmbientManager::updateBasicCloudField( %this,%field, %value,%layerId ) {
devLog("SEP_AmbientManager::updateBasicCloudField( %this,%field, %value,%layerId )",%this,%field, %value,%layerId );
//SEP_AmbientManager.buildBasicCloudsParams();
%obj = %this.selectedBasicClouds;
if (!isObject(%obj)) {
warnLog("Can't update ground cover value because none is selected. Tried wth:",%obj);
return;
}
LabObj.set(%obj,%field,%value,%layerId);
//eval("%obj."@%checkField@" = %value;");
//%obj.setFieldValue(%field,%value,%layerId);
EWorldEditor.isDirty = true;
%this.setBasicCloudsDirty();
//BasicCloudsInspector.refresh();
//BasicCloudsInspector.apply();
syncParamArray(SEP_AmbientManager.BasicCloudsParamArray);
}
//------------------------------------------------------------------------------
//==============================================================================
// Prepare the default config array for the Scene Editor PluginSEP_AmbientManager.initBasicCloudsData
function SEP_AmbientManager::initBasicCloudsData( %this ) {
%basicCloudsList = Lab.getMissionObjectClassList("BasicClouds");
%first = getWord(%basicCloudsList,0);
if (isObject(%first))
%selected = %first.getId();
%currentId = "-1";
if (isObject(%this.selectedBasicClouds))
%currentId = %this.selectedBasicClouds.getId();
SEP_BasicCloudsMenu.clear();
SEP_BasicCloudsMenu.add("None",0);
foreach$(%layer in %basicCloudsList) {
%added = true;
SEP_BasicCloudsMenu.add(%layer.getName(),%layer.getId());
if (%currentId $= %layer.getId())
%selected = %layer.getId();
}
if (%selected $= "")
%selected = 0;
SEP_BasicCloudsMenu.setSelected(%selected);
}
//------------------------------------------------------------------------------
//==============================================================================
function SEP_AmbientManager::selectBasicClouds(%this,%obj) {
logd("SEP_AmbientManager::selectBasicClouds(%this,%obj)",%this,%obj);
if (isObject(%obj)) {
%name = %obj.getName();
%id = %obj;
%inspectThis = %obj;
Lab.inspect(%inspectThis);
}
SEP_AmbientManager.selectedBasicClouds = %id;
%this.selectedBasicCloudsName = %name;
%this.setBasicCloudsDirty();
//BasicCloudsInspector.inspect( %inspectThis);
syncParamArray(SEP_AmbientManager.BasicCloudsParamArray,true);
}
//------------------------------------------------------------------------------
//==============================================================================
function SEP_AmbientManager::saveBasicCloudsObject(%this) {
devLog("SEP_AmbientManager::saveBasicCloudsObject(%this)",%this);
%obj = %this.selectedBasicClouds;
if (!isObject(%obj)) {
warnLog("Can't save BasicClouds because none is selected. Tried wth:",%obj);
return;
}
LabObj.save(%obj);
%this.setCloudLayerDirty(false);
return;
if (SEP_AmbientManager.missionIsDirty) {
SEP_AmbientManager_PM.setDirty(MissionGroup);
SEP_AmbientManager_PM.saveDirtyObject(MissionGroup);
SEP_AmbientManager.missionIsDirty = false;
%this.setBasicCloudsDirty(false);
return;
}
if (!SEP_AmbientManager_PM.isDirty(%obj)) {
warnLog("Object is not dirty, nothing to save");
return;
}
SEP_AmbientManager_PM.setDirty(%obj);
SEP_AmbientManager_PM.saveDirtyObject(%obj);
%this.setBasicCloudsDirty(false);
}
//------------------------------------------------------------------------------
//==============================================================================
function SEP_AmbientManager::setBasicCloudsDirty(%this) {
logd("SEP_AmbientManager::setBasicCloudsDirty(%this)",%this);
%obj = %this.selectedBasicClouds;
%isDirty = LabObj.isDirty(%obj);
%this.isDirty = %isDirty;
SEP_BasicCloudsSaveButton.active = %isDirty;
}
//------------------------------------------------------------------------------
//==============================================================================
function SEP_AmbientManager::deleteBasicClouds(%this) {
delObj(%this.selectedBasicClouds);
//%this.selectBasicClouds();
SEP_AmbientManager.initBasicCloudsData();
}
//------------------------------------------------------------------------------
//==============================================================================
function SEP_AmbientManager::createBasicClouds(%this) {
logd("SEP_AmbientManager::createBasicClouds(%this)",%this);
%obj = %this.selectedBasicClouds;
%name = getUniqueName("envBasicClouds");
%obj = new BasicClouds(%name) {
layerEnabled[0] = "1";
layerEnabled[1] = "1";
layerEnabled[2] = "1";
texture[0] = $BasicClouds::Default_["texture0"];
texture[1] = $BasicClouds::Default_["texture1"];
texture[2] = $BasicClouds::Default_["texture2"];
texScale[0] = "1";
texScale[1] = "0.857143";
texScale[2] = "1";
texDirection[0] = "1 0";
texDirection[1] = "1 0";
texDirection[2] = "1 0";
texSpeed[0] = "0.001";
texSpeed[1] = "0.450549";
texSpeed[2] = "0.002";
texOffset[0] = "0.5 0.5";
texOffset[1] = "0.2 0.2";
texOffset[2] = "0.2 0.2";
height[0] = "8";
height[1] = "5";
height[2] = "3";
byGroup = "0";
};
%group = Scene.getActiveSimGroup();
%group.add(%obj);
%obj.setFileName(MissionGroup.getFileName());
SEP_BasicCloudsMenu.add(%obj.getName(),%obj.getId());
SEP_BasicCloudsMenu.setSelected(%obj.getId());
SEP_AmbientManager.missionIsDirty = true;
}
//------------------------------------------------------------------------------
//==============================================================================
function SEP_BasicCloudsMenu::onSelect(%this,%id,%text) {
SEP_AmbientManager.selectBasicClouds(%text);
}
//------------------------------------------------------------------------------
//==============================================================================
function SEP_BasicClouds::toggleInspectorMode(%this) {
logd("SEP_BasicClouds::toggleInspectorMode(%this)",%this);
SEP_BasicClouds.inspectorMode = !SEP_BasicClouds.inspectorMode;
if (SEP_BasicClouds.inspectorMode) {
SEP_BasicCloudsInspectButton.text = "Custom mode";
SEP_BasicClouds_Custom.visible = 0;
SEP_BasicClouds_Inspector.visible = 1;
} else {
SEP_BasicCloudsInspectButton.text = "Inspector mode";
SEP_BasicClouds_Inspector.visible = 0;
SEP_BasicClouds_Custom.visible = 1;
}
}
//------------------------------------------------------------------------------
//==============================================================================
/*
layerEnabled
texture
texScale
texDirection
texSpeed
texOffset
height
*/
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGAssetBroker")]
public class HGAssetBroker : ISharedRegionModule, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private IImprovedAssetCache m_Cache = null;
private IAssetService m_GridService;
private IAssetService m_HGService;
private Scene m_aScene;
private string m_LocalAssetServiceURI;
private bool m_Enabled = false;
private AssetPermissions m_AssetPerms;
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "HGAssetBroker"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("AssetServices", "");
if (name == Name)
{
IConfig assetConfig = source.Configs["AssetService"];
if (assetConfig == null)
{
m_log.Error("[HG ASSET CONNECTOR]: AssetService missing from OpenSim.ini");
return;
}
string localDll = assetConfig.GetString("LocalGridAssetService",
String.Empty);
string HGDll = assetConfig.GetString("HypergridAssetService",
String.Empty);
if (localDll == String.Empty)
{
m_log.Error("[HG ASSET CONNECTOR]: No LocalGridAssetService named in section AssetService");
return;
}
if (HGDll == String.Empty)
{
m_log.Error("[HG ASSET CONNECTOR]: No HypergridAssetService named in section AssetService");
return;
}
Object[] args = new Object[] { source };
m_GridService =
ServerUtils.LoadPlugin<IAssetService>(localDll,
args);
m_HGService =
ServerUtils.LoadPlugin<IAssetService>(HGDll,
args);
if (m_GridService == null)
{
m_log.Error("[HG ASSET CONNECTOR]: Can't load local asset service");
return;
}
if (m_HGService == null)
{
m_log.Error("[HG ASSET CONNECTOR]: Can't load hypergrid asset service");
return;
}
m_LocalAssetServiceURI = assetConfig.GetString("AssetServerURI", string.Empty);
if (m_LocalAssetServiceURI == string.Empty)
{
IConfig netConfig = source.Configs["Network"];
m_LocalAssetServiceURI = netConfig.GetString("asset_server_url", string.Empty);
}
if (m_LocalAssetServiceURI != string.Empty)
m_LocalAssetServiceURI = m_LocalAssetServiceURI.Trim('/');
IConfig hgConfig = source.Configs["HGAssetService"];
m_AssetPerms = new AssetPermissions(hgConfig); // it's ok if arg is null
m_Enabled = true;
m_log.Info("[HG ASSET CONNECTOR]: HG asset broker enabled");
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_aScene = scene;
m_aScene.RegisterModuleInterface<IAssetService>(this);
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
if (m_Cache == null)
{
m_Cache = scene.RequestModuleInterface<IImprovedAssetCache>();
if (!(m_Cache is ISharedRegionModule))
m_Cache = null;
}
m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled hypergrid asset broker for region {0}", scene.RegionInfo.RegionName);
if (m_Cache != null)
{
m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled asset caching for region {0}", scene.RegionInfo.RegionName);
}
}
private bool IsHG(string id)
{
Uri assetUri;
if (Uri.TryCreate(id, UriKind.Absolute, out assetUri) &&
assetUri.Scheme == Uri.UriSchemeHttp)
return true;
return false;
}
public AssetBase Get(string id)
{
//m_log.DebugFormat("[HG ASSET CONNECTOR]: Get {0}", id);
AssetBase asset = null;
if (m_Cache != null)
{
asset = m_Cache.Get(id);
if (asset != null)
return asset;
}
if (IsHG(id))
{
asset = m_HGService.Get(id);
if (asset != null)
{
// Now store it locally, if allowed
if (m_AssetPerms.AllowedImport(asset.Type))
m_GridService.Store(asset);
else
return null;
}
}
else
asset = m_GridService.Get(id);
if (m_Cache != null)
m_Cache.Cache(asset);
return asset;
}
public AssetBase GetCached(string id)
{
if (m_Cache != null)
return m_Cache.Get(id);
return null;
}
public AssetMetadata GetMetadata(string id)
{
AssetBase asset = null;
if (m_Cache != null)
{
if (m_Cache != null)
m_Cache.Get(id);
if (asset != null)
return asset.Metadata;
}
AssetMetadata metadata;
if (IsHG(id))
metadata = m_HGService.GetMetadata(id);
else
metadata = m_GridService.GetMetadata(id);
return metadata;
}
public byte[] GetData(string id)
{
AssetBase asset = null;
if (m_Cache != null)
{
if (m_Cache != null)
m_Cache.Get(id);
if (asset != null)
return asset.Data;
}
if (IsHG(id))
return m_HGService.GetData(id);
else
return m_GridService.GetData(id);
}
public bool Get(string id, Object sender, AssetRetrieved handler)
{
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset != null)
{
Util.FireAndForget(delegate { handler(id, sender, asset); });
return true;
}
if (IsHG(id))
{
return m_HGService.Get(id, sender, delegate (string assetID, Object s, AssetBase a)
{
if (m_Cache != null)
m_Cache.Cache(a);
handler(assetID, s, a);
});
}
else
{
return m_GridService.Get(id, sender, delegate (string assetID, Object s, AssetBase a)
{
if (m_Cache != null)
m_Cache.Cache(a);
handler(assetID, s, a);
});
}
}
public string Store(AssetBase asset)
{
bool isHG = IsHG(asset.ID);
if ((m_Cache != null) && !isHG)
// Don't store it in the cache if the asset is to
// be sent to the other grid, because this is already
// a copy of the local asset.
m_Cache.Cache(asset);
if (asset.Temporary || asset.Local)
{
if (m_Cache != null)
m_Cache.Cache(asset);
return asset.ID;
}
string id = string.Empty;
if (IsHG(asset.ID))
{
if (m_AssetPerms.AllowedExport(asset.Type))
id = m_HGService.Store(asset);
else
return String.Empty;
}
else
id = m_GridService.Store(asset);
if (id != String.Empty)
{
// Placing this here, so that this work with old asset servers that don't send any reply back
// SynchronousRestObjectRequester returns somethins that is not an empty string
if (id != null)
asset.ID = id;
if (m_Cache != null)
m_Cache.Cache(asset);
}
return id;
}
public bool UpdateContent(string id, byte[] data)
{
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset != null)
{
asset.Data = data;
m_Cache.Cache(asset);
}
if (IsHG(id))
return m_HGService.UpdateContent(id, data);
else
return m_GridService.UpdateContent(id, data);
}
public bool Delete(string id)
{
if (m_Cache != null)
m_Cache.Expire(id);
bool result = false;
if (IsHG(id))
result = m_HGService.Delete(id);
else
result = m_GridService.Delete(id);
if (result && m_Cache != null)
m_Cache.Expire(id);
return result;
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="DoubleCollection.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Windows.Media.Converters;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media
{
/// <summary>
/// A collection of doubles.
/// </summary>
[TypeConverter(typeof(DoubleCollectionConverter))]
[ValueSerializer(typeof(DoubleCollectionValueSerializer))] // Used by MarkupWriter
public sealed partial class DoubleCollection : Freezable, IFormattable, IList, IList<double>
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new DoubleCollection Clone()
{
return (DoubleCollection)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new DoubleCollection CloneCurrentValue()
{
return (DoubleCollection)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region IList<T>
/// <summary>
/// Adds "value" to the list
/// </summary>
public void Add(double value)
{
AddHelper(value);
}
/// <summary>
/// Removes all elements from the list
/// </summary>
public void Clear()
{
WritePreamble();
_collection.Clear();
++_version;
WritePostscript();
}
/// <summary>
/// Determines if the list contains "value"
/// </summary>
public bool Contains(double value)
{
ReadPreamble();
return _collection.Contains(value);
}
/// <summary>
/// Returns the index of "value" in the list
/// </summary>
public int IndexOf(double value)
{
ReadPreamble();
return _collection.IndexOf(value);
}
/// <summary>
/// Inserts "value" into the list at the specified position
/// </summary>
public void Insert(int index, double value)
{
WritePreamble();
_collection.Insert(index, value);
++_version;
WritePostscript();
}
/// <summary>
/// Removes "value" from the list
/// </summary>
public bool Remove(double value)
{
WritePreamble();
int index = IndexOf(value);
if (index >= 0)
{
// we already have index from IndexOf so instead of using Remove,
// which will search the collection a second time, we'll use RemoveAt
_collection.RemoveAt(index);
++_version;
WritePostscript();
return true;
}
// Collection_Remove returns true, calls WritePostscript,
// increments version, and does UpdateResource if it succeeds
return false;
}
/// <summary>
/// Removes the element at the specified index
/// </summary>
public void RemoveAt(int index)
{
RemoveAtWithoutFiringPublicEvents(index);
// RemoveAtWithoutFiringPublicEvents incremented the version
WritePostscript();
}
/// <summary>
/// Removes the element at the specified index without firing
/// the public Changed event.
/// The caller - typically a public method - is responsible for calling
/// WritePostscript if appropriate.
/// </summary>
internal void RemoveAtWithoutFiringPublicEvents(int index)
{
WritePreamble();
_collection.RemoveAt(index);
++_version;
// No WritePostScript to avoid firing the Changed event.
}
/// <summary>
/// Indexer for the collection
/// </summary>
public double this[int index]
{
get
{
ReadPreamble();
return _collection[index];
}
set
{
WritePreamble();
_collection[ index ] = value;
++_version;
WritePostscript();
}
}
#endregion
#region ICollection<T>
/// <summary>
/// The number of elements contained in the collection.
/// </summary>
public int Count
{
get
{
ReadPreamble();
return _collection.Count;
}
}
/// <summary>
/// Copies the elements of the collection into "array" starting at "index"
/// </summary>
public void CopyTo(double[] array, int index)
{
ReadPreamble();
if (array == null)
{
throw new ArgumentNullException("array");
}
// This will not throw in the case that we are copying
// from an empty collection. This is consistent with the
// BCL Collection implementations. (Windows 1587365)
if (index < 0 || (index + _collection.Count) > array.Length)
{
throw new ArgumentOutOfRangeException("index");
}
_collection.CopyTo(array, index);
}
bool ICollection<double>.IsReadOnly
{
get
{
ReadPreamble();
return IsFrozen;
}
}
#endregion
#region IEnumerable<T>
/// <summary>
/// Returns an enumerator for the collection
/// </summary>
public Enumerator GetEnumerator()
{
ReadPreamble();
return new Enumerator(this);
}
IEnumerator<double> IEnumerable<double>.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region IList
bool IList.IsReadOnly
{
get
{
return ((ICollection<double>)this).IsReadOnly;
}
}
bool IList.IsFixedSize
{
get
{
ReadPreamble();
return IsFrozen;
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
// Forwards to typed implementation
this[index] = Cast(value);
}
}
int IList.Add(object value)
{
// Forward to typed helper
return AddHelper(Cast(value));
}
bool IList.Contains(object value)
{
if (value is double)
{
return Contains((double)value);
}
return false;
}
int IList.IndexOf(object value)
{
if (value is double)
{
return IndexOf((double)value);
}
return -1;
}
void IList.Insert(int index, object value)
{
// Forward to IList<T> Insert
Insert(index, Cast(value));
}
void IList.Remove(object value)
{
if (value is double)
{
Remove((double)value);
}
}
#endregion
#region ICollection
void ICollection.CopyTo(Array array, int index)
{
ReadPreamble();
if (array == null)
{
throw new ArgumentNullException("array");
}
// This will not throw in the case that we are copying
// from an empty collection. This is consistent with the
// BCL Collection implementations. (Windows 1587365)
if (index < 0 || (index + _collection.Count) > array.Length)
{
throw new ArgumentOutOfRangeException("index");
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Get(SRID.Collection_BadRank));
}
// Elsewhere in the collection we throw an AE when the type is
// bad so we do it here as well to be consistent
try
{
int count = _collection.Count;
for (int i = 0; i < count; i++)
{
array.SetValue(_collection[i], index + i);
}
}
catch (InvalidCastException e)
{
throw new ArgumentException(SR.Get(SRID.Collection_BadDestArray, this.GetType().Name), e);
}
}
bool ICollection.IsSynchronized
{
get
{
ReadPreamble();
return IsFrozen || Dispatcher != null;
}
}
object ICollection.SyncRoot
{
get
{
ReadPreamble();
return this;
}
}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Internal Helpers
/// <summary>
/// A frozen empty DoubleCollection.
/// </summary>
internal static DoubleCollection Empty
{
get
{
if (s_empty == null)
{
DoubleCollection collection = new DoubleCollection();
collection.Freeze();
s_empty = collection;
}
return s_empty;
}
}
/// <summary>
/// Helper to return read only access.
/// </summary>
internal double Internal_GetItem(int i)
{
return _collection[i];
}
#endregion
#region Private Helpers
private double Cast(object value)
{
if( value == null )
{
throw new System.ArgumentNullException("value");
}
if (!(value is double))
{
throw new System.ArgumentException(SR.Get(SRID.Collection_BadType, this.GetType().Name, value.GetType().Name, "double"));
}
return (double) value;
}
// IList.Add returns int and IList<T>.Add does not. This
// is called by both Adds and IList<T>'s just ignores the
// integer
private int AddHelper(double value)
{
int index = AddWithoutFiringPublicEvents(value);
// AddAtWithoutFiringPublicEvents incremented the version
WritePostscript();
return index;
}
internal int AddWithoutFiringPublicEvents(double value)
{
int index = -1;
WritePreamble();
index = _collection.Add(value);
++_version;
// No WritePostScript to avoid firing the Changed event.
return index;
}
#endregion Private Helpers
private static DoubleCollection s_empty;
#region Public Properties
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new DoubleCollection();
}
/// <summary>
/// Implementation of Freezable.CloneCore()
/// </summary>
protected override void CloneCore(Freezable source)
{
DoubleCollection sourceDoubleCollection = (DoubleCollection) source;
base.CloneCore(source);
int count = sourceDoubleCollection._collection.Count;
_collection = new FrugalStructList<double>(count);
for (int i = 0; i < count; i++)
{
_collection.Add(sourceDoubleCollection._collection[i]);
}
}
/// <summary>
/// Implementation of Freezable.CloneCurrentValueCore()
/// </summary>
protected override void CloneCurrentValueCore(Freezable source)
{
DoubleCollection sourceDoubleCollection = (DoubleCollection) source;
base.CloneCurrentValueCore(source);
int count = sourceDoubleCollection._collection.Count;
_collection = new FrugalStructList<double>(count);
for (int i = 0; i < count; i++)
{
_collection.Add(sourceDoubleCollection._collection[i]);
}
}
/// <summary>
/// Implementation of Freezable.GetAsFrozenCore()
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
DoubleCollection sourceDoubleCollection = (DoubleCollection) source;
base.GetAsFrozenCore(source);
int count = sourceDoubleCollection._collection.Count;
_collection = new FrugalStructList<double>(count);
for (int i = 0; i < count; i++)
{
_collection.Add(sourceDoubleCollection._collection[i]);
}
}
/// <summary>
/// Implementation of Freezable.GetCurrentValueAsFrozenCore()
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
DoubleCollection sourceDoubleCollection = (DoubleCollection) source;
base.GetCurrentValueAsFrozenCore(source);
int count = sourceDoubleCollection._collection.Count;
_collection = new FrugalStructList<double>(count);
for (int i = 0; i < count; i++)
{
_collection.Add(sourceDoubleCollection._collection[i]);
}
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// Creates a string representation of this object based on the current culture.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
public override string ToString()
{
ReadPreamble();
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, null /* format provider */);
}
/// <summary>
/// Creates a string representation of this object based on the IFormatProvider
/// passed in. If the provider is null, the CurrentCulture is used.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
public string ToString(IFormatProvider provider)
{
ReadPreamble();
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, provider);
}
/// <summary>
/// Creates a string representation of this object based on the format string
/// and IFormatProvider passed in.
/// If the provider is null, the CurrentCulture is used.
/// See the documentation for IFormattable for more information.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
string IFormattable.ToString(string format, IFormatProvider provider)
{
ReadPreamble();
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(format, provider);
}
/// <summary>
/// Creates a string representation of this object based on the format string
/// and IFormatProvider passed in.
/// If the provider is null, the CurrentCulture is used.
/// See the documentation for IFormattable for more information.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
internal string ConvertToString(string format, IFormatProvider provider)
{
if (_collection.Count == 0)
{
return String.Empty;
}
StringBuilder str = new StringBuilder();
// Consider using this separator
// Helper to get the numeric list separator for a given culture.
// char separator = MS.Internal.TokenizerHelper.GetNumericListSeparator(provider);
for (int i=0; i<_collection.Count; i++)
{
str.AppendFormat(
provider,
"{0:" + format + "}",
_collection[i]);
if (i != _collection.Count-1)
{
str.Append(" ");
}
}
return str.ToString();
}
/// <summary>
/// Parse - returns an instance converted from the provided string
/// using the current culture
/// <param name="source"> string with DoubleCollection data </param>
/// </summary>
public static DoubleCollection Parse(string source)
{
IFormatProvider formatProvider = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;
TokenizerHelper th = new TokenizerHelper(source, formatProvider);
DoubleCollection resource = new DoubleCollection();
double value;
while (th.NextToken())
{
value = Convert.ToDouble(th.GetCurrentToken(), formatProvider);
resource.Add(value);
}
return resource;
}
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal FrugalStructList<double> _collection;
internal uint _version = 0;
#endregion Internal Fields
#region Enumerator
/// <summary>
/// Enumerates the items in a doubleCollection
/// </summary>
public struct Enumerator : IEnumerator, IEnumerator<double>
{
#region Constructor
internal Enumerator(DoubleCollection list)
{
Debug.Assert(list != null, "list may not be null.");
_list = list;
_version = list._version;
_index = -1;
_current = default(double);
}
#endregion
#region Methods
void IDisposable.Dispose()
{
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element,
/// false if the enumerator has passed the end of the collection.
/// </returns>
public bool MoveNext()
{
_list.ReadPreamble();
if (_version == _list._version)
{
if (_index > -2 && _index < _list._collection.Count - 1)
{
_current = _list._collection[++_index];
return true;
}
else
{
_index = -2; // -2 indicates "past the end"
return false;
}
}
else
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged));
}
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the
/// first element in the collection.
/// </summary>
public void Reset()
{
_list.ReadPreamble();
if (_version == _list._version)
{
_index = -1;
}
else
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged));
}
}
#endregion
#region Properties
object IEnumerator.Current
{
get
{
return this.Current;
}
}
/// <summary>
/// Current element
///
/// The behavior of IEnumerable<T>.Current is undefined
/// before the first MoveNext and after we have walked
/// off the end of the list. However, the IEnumerable.Current
/// contract requires that we throw exceptions
/// </summary>
public double Current
{
get
{
if (_index > -1)
{
return _current;
}
else if (_index == -1)
{
throw new InvalidOperationException(SR.Get(SRID.Enumerator_NotStarted));
}
else
{
Debug.Assert(_index == -2, "expected -2, got " + _index + "\n");
throw new InvalidOperationException(SR.Get(SRID.Enumerator_ReachedEnd));
}
}
}
#endregion
#region Data
private double _current;
private DoubleCollection _list;
private uint _version;
private int _index;
#endregion
}
#endregion
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
/// <summary>
/// Initializes a new instance that is empty.
/// </summary>
public DoubleCollection()
{
_collection = new FrugalStructList<double>();
}
/// <summary>
/// Initializes a new instance that is empty and has the specified initial capacity.
/// </summary>
/// <param name="capacity"> int - The number of elements that the new list is initially capable of storing. </param>
public DoubleCollection(int capacity)
{
_collection = new FrugalStructList<double>(capacity);
}
/// <summary>
/// Creates a DoubleCollection with all of the same elements as collection
/// </summary>
public DoubleCollection(IEnumerable<double> collection)
{
// The WritePreamble and WritePostscript aren't technically necessary
// in the constructor as of 1/20/05 but they are put here in case
// their behavior changes at a later date
WritePreamble();
if (collection != null)
{
ICollection<double> icollectionOfT = collection as ICollection<double>;
if (icollectionOfT != null)
{
_collection = new FrugalStructList<double>(icollectionOfT);
}
else
{
ICollection icollection = collection as ICollection;
if (icollection != null) // an IC but not and IC<T>
{
_collection = new FrugalStructList<double>(icollection);
}
else // not a IC or IC<T> so fall back to the slower Add
{
_collection = new FrugalStructList<double>();
foreach (double item in collection)
{
_collection.Add(item);
}
}
}
WritePostscript();
}
else
{
throw new ArgumentNullException("collection");
}
}
#endregion Constructors
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Windows.Forms;
namespace Ripper
{
using System.ComponentModel;
using System.Timers;
partial class Login
{
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region 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()
{
ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Login));
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.GuestLogin = new System.Windows.Forms.CheckBox();
this.ForumList = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.ForumUrl = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.LanuageSelector = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.LoginButton = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.PasswordField = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.UserNameField = new System.Windows.Forms.TextBox();
this.timer1 = new System.Timers.Timer();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
this.SuspendLayout();
// groupBox1
this.groupBox1.Controls.Add(this.GuestLogin);
this.groupBox1.Controls.Add(this.ForumList);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.label6);
this.groupBox1.Controls.Add(this.ForumUrl);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.LanuageSelector);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.LoginButton);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.PasswordField);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.UserNameField);
this.groupBox1.Location = new System.Drawing.Point(8, 16);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(376, 304);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Provide Login Credentials for the Forums";
this.groupBox1.UseCompatibleTextRendering = true;
// GuestLogin
this.GuestLogin.AutoSize = true;
this.GuestLogin.Location = new System.Drawing.Point(102, 78);
this.GuestLogin.Name = "GuestLogin";
this.GuestLogin.Size = new System.Drawing.Size(92, 17);
this.GuestLogin.TabIndex = 17;
this.GuestLogin.Text = "Guest Access";
this.GuestLogin.UseVisualStyleBackColor = true;
this.GuestLogin.CheckedChanged += new System.EventHandler(this.GuestLogin_CheckedChanged);
// ForumList
this.ForumList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.ForumList.IntegralHeight = false;
this.ForumList.ItemHeight = 13;
this.ForumList.Items.AddRange(
new object[]
{
"<Select a Forum>", "ViperGirls Forums", "Sexy and Funny Forums", "Scanlover Forums",
"Big Naturals Only", "The phun.org forum", "<Other - Enter URL bellow>"
});
this.ForumList.Location = new System.Drawing.Point(102, 109);
this.ForumList.Name = "ForumList";
this.ForumList.Size = new System.Drawing.Size(246, 21);
this.ForumList.TabIndex = 2;
this.ForumList.SelectedIndexChanged += new System.EventHandler(this.ForumSelectedIndexChanged);
// label4
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(6, 143);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(64, 13);
this.label4.TabIndex = 16;
this.label4.Text = "Forum URL:";
// label6
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(6, 112);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(72, 13);
this.label6.TabIndex = 15;
this.label6.Text = "Select Forum:";
// ForumUrl
this.ForumUrl.Location = new System.Drawing.Point(102, 144);
this.ForumUrl.Name = "ForumUrl";
this.ForumUrl.Size = new System.Drawing.Size(246, 20);
this.ForumUrl.TabIndex = 3;
// label5
this.label5.Location = new System.Drawing.Point(114, 273);
this.label5.MaximumSize = new System.Drawing.Size(0, 13);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(120, 13);
this.label5.TabIndex = 13;
this.label5.Text = "label5";
this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.label5.UseCompatibleTextRendering = true;
// LanuageSelector
this.LanuageSelector.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.LanuageSelector.Items.AddRange(new object[] { "German", "French", "English" });
this.LanuageSelector.Location = new System.Drawing.Point(240, 270);
this.LanuageSelector.MaximumSize = new System.Drawing.Size(121, 0);
this.LanuageSelector.Name = "LanuageSelector";
this.LanuageSelector.Size = new System.Drawing.Size(121, 21);
this.LanuageSelector.TabIndex = 6;
this.LanuageSelector.SelectedIndexChanged += new System.EventHandler(this.LanuageSelectorIndexChanged);
// label3
this.label3.Font = new System.Drawing.Font(
"Verdana",
9.75F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte)(0)));
this.label3.ForeColor = System.Drawing.Color.Red;
this.label3.Location = new System.Drawing.Point(9, 213);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(339, 24);
this.label3.TabIndex = 5;
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
// LoginButton
this.LoginButton.Font = new System.Drawing.Font(
"Microsoft Sans Serif",
8.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((byte)(0)));
this.LoginButton.Image = ((System.Drawing.Image)(resources.GetObject("LoginButton.Image")));
this.LoginButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.LoginButton.Location = new System.Drawing.Point(102, 170);
this.LoginButton.Name = "LoginButton";
this.LoginButton.Size = new System.Drawing.Size(246, 40);
this.LoginButton.TabIndex = 5;
this.LoginButton.Text = "Login";
this.LoginButton.UseCompatibleTextRendering = true;
this.LoginButton.Click += new System.EventHandler(this.LoginBtnClick);
// label2
this.label2.Location = new System.Drawing.Point(6, 54);
this.label2.MaximumSize = new System.Drawing.Size(87, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(87, 16);
this.label2.TabIndex = 3;
this.label2.Text = "Password :";
this.label2.UseCompatibleTextRendering = true;
// PasswordField
this.PasswordField.Location = new System.Drawing.Point(102, 51);
this.PasswordField.MaximumSize = new System.Drawing.Size(246, 20);
this.PasswordField.Name = "PasswordField";
this.PasswordField.PasswordChar = '*';
this.PasswordField.Size = new System.Drawing.Size(246, 20);
this.PasswordField.TabIndex = 1;
// label1
this.label1.Location = new System.Drawing.Point(6, 22);
this.label1.MaximumSize = new System.Drawing.Size(87, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(87, 16);
this.label1.TabIndex = 1;
this.label1.Text = "User Name :";
this.label1.UseCompatibleTextRendering = true;
// UserNameField
this.UserNameField.Location = new System.Drawing.Point(102, 19);
this.UserNameField.MaximumSize = new System.Drawing.Size(246, 20);
this.UserNameField.Name = "UserNameField";
this.UserNameField.Size = new System.Drawing.Size(246, 20);
this.UserNameField.TabIndex = 0;
// timer1
this.timer1.Interval = 400D;
this.timer1.SynchronizingObject = this;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.Timer1Elapsed);
// Login
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(394, 332);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Login";
this.Text = "Login";
this.Load += new System.EventHandler(this.LoginLoad);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBox1;
private TextBox UserNameField;
private Label label1;
private Label label2;
private TextBox PasswordField;
private Button LoginButton;
private Label label3;
private Timer timer1;
private ComboBox LanuageSelector;
private Label label5;
private Label label6;
private TextBox ForumUrl;
private Label label4;
private ComboBox ForumList;
private CheckBox GuestLogin;
}
}
| |
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
namespace BalloonCS
{
/// <summary>
/// Summary description for FMSInPlaceTip.
/// </summary>
public class InPlaceBalloon : IDisposable
{
private Control m_parent;
private string m_text = "FMS Inplace Tooltip Control Display Message";
private string m_title = "FMS Inplace Tooltip Message";
private TooltipIcon m_titleIcon = TooltipIcon.None;
private int m_maxWidth = 250;
[StructLayout(LayoutKind.Sequential)]
private struct TOOLINFO
{
public int cbSize;
public int uFlags;
public IntPtr hwnd;
public IntPtr uId;
public Rectangle rect;
public IntPtr hinst;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszText;
public uint lParam;
}
private const string TOOLTIPS_CLASS = "tooltips_class32";
private const int WS_POPUP = unchecked((int)0x80000000);
private const int WM_USER = 0x0400;
private const int SWP_NOSIZE = 0x0001;
private const int SWP_NOMOVE = 0x0002;
private const int SWP_NOACTIVATE = 0x0010;
private const int TTS_ALWAYSTIP = 0x01;
private const int TTS_NOPREFIX = 0x02;
private const int TTF_TRANSPARENT = 0x0100;
private const int TTF_SUBCLASS = 0x0010;
private const int TTM_SETMAXTIPWIDTH = WM_USER + 24;
private const int TTM_ADJUSTRECT = WM_USER + 31;
private const int TTM_ADDTOOL = WM_USER + 50;
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
[DllImport("User32", SetLastError=true)]
private static extern bool SetWindowPos(
IntPtr hWnd,
IntPtr hWndInsertAfter,
int X,
int Y,
int cx,
int cy,
int uFlags);
[DllImport("User32", SetLastError=true)]
private static extern int SendMessage(
IntPtr hWnd,
int Msg,
int wParam,
IntPtr lParam);
private InPlaceTool m_tool = null;
public InPlaceBalloon()
{
m_tool = new InPlaceTool();
}
protected virtual void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
// release managed resources if any
}
// release unmanaged resource
m_tool.DestroyHandle();
// Note that this is not thread safe.
// Another thread could start disposing the object
// after the managed resources are disposed,
// but before the disposed flag is set to true.
// If thread safety is necessary, it must be
// implemented by the client.
}
disposed = true;
}
// Finalizer
~InPlaceBalloon()
{
Dispose(false);
}
public void SetToolTip(Control parent, Rectangle rect, string tipText)
{
System.Diagnostics.Debug.Assert(parent!=null, "parent is null", "parent cant be null");
m_text = tipText;
CreateParams cp = new CreateParams();
cp.ClassName = TOOLTIPS_CLASS;
cp.Style = WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP;
cp.Parent = parent.Handle;
// create the tool
m_tool.CreateHandle(cp);
// adjust the rectangle
Rectangle r = rect;
IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(r));
Marshal.StructureToPtr(r, p, true);
SendMessage(m_tool.Handle, TTM_ADJUSTRECT, -1, p);
r = (Rectangle)Marshal.PtrToStructure(p, typeof(Rectangle));
Marshal.FreeHGlobal(p);
// make sure we make it the top level window
SetWindowPos(
m_tool.Handle, HWND_TOPMOST, r.Left, r.Top, 0, 0,
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
// create and fill in the tool tip info
TOOLINFO ti = new TOOLINFO();
ti.cbSize = Marshal.SizeOf(ti);
ti.uFlags = TTF_TRANSPARENT | TTF_SUBCLASS;
ti.hwnd = parent.Handle;
ti.lpszText = m_text;
ti.rect = parent.ClientRectangle;
// add the tool tip
IntPtr ptrStruct = Marshal.AllocHGlobal(Marshal.SizeOf(ti));
Marshal.StructureToPtr(ti, ptrStruct, true);
SendMessage(m_tool.Handle, TTM_ADDTOOL, 0, ptrStruct);
Marshal.FreeHGlobal(ptrStruct);
SendMessage(m_tool.Handle, TTM_SETMAXTIPWIDTH,
0, new IntPtr(m_maxWidth));
// IntPtr ptrTitle = Marshal.StringToHGlobalAuto(m_title);
//
// WinDeclns.SendMessage(
// m_tool.Handle, TTDeclns.TTM_SETTITLE,
// (int)m_titleIcon, ptrTitle);
//
// Marshal.FreeHGlobal(ptrTitle);
}
/// <summary>
/// Sets or gets the Title.
/// </summary>
public string Title
{
get
{
return m_title;
}
set
{
m_title = value;
}
}
/// <summary>
/// Sets or gets the display icon.
/// </summary>
public TooltipIcon TitleIcon
{
get
{
return m_titleIcon;
}
set
{
m_titleIcon = value;
}
}
/// <summary>
/// Sets or gets the display text.
/// </summary>
public string Text
{
get
{
return m_text;
}
set
{
m_text = value;
}
}
/// <summary>
/// Sets or gets the parent.
/// </summary>
public Control Parent
{
get
{
return m_parent;
}
set
{
m_parent = value;
}
}
private bool disposed = false;
public void Dispose()
{
Dispose(true);
// Take yourself off the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
}
internal class InPlaceTool : NativeWindow
{
protected override void WndProc(ref Message m)
{
base.WndProc (ref m);
// if(m.Msg==5)//SW_SHOW
// {
// System.Diagnostics.Debug.WriteLine(m.Msg);
// }
// if(m.Msg==0)//SW_HIDE
// {
// System.Diagnostics.Debug.WriteLine(m.Msg);
// }
}
}
}
| |
namespace PaletteDesigner
{
partial class FormChromeTMS
{
/// <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(FormChromeTMS));
this.tmsMenuStrip = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printPreviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.customizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.indexToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.searchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tmsStatusStrip = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.tmsToolStrip = new System.Windows.Forms.ToolStrip();
this.newToolStripButton = new System.Windows.Forms.ToolStripButton();
this.openToolStripButton = new System.Windows.Forms.ToolStripButton();
this.saveToolStripButton = new System.Windows.Forms.ToolStripButton();
this.printToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripButton = new System.Windows.Forms.ToolStripButton();
this.copyToolStripButton = new System.Windows.Forms.ToolStripButton();
this.pasteToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.helpToolStripButton = new System.Windows.Forms.ToolStripButton();
this.tmsToolStripContainer = new System.Windows.Forms.ToolStripContainer();
this.tmsMenuStrip.SuspendLayout();
this.tmsStatusStrip.SuspendLayout();
this.tmsToolStrip.SuspendLayout();
this.tmsToolStripContainer.TopToolStripPanel.SuspendLayout();
this.tmsToolStripContainer.SuspendLayout();
this.SuspendLayout();
//
// tmsMenuStrip
//
this.tmsMenuStrip.Font = new System.Drawing.Font("Segoe UI", 8.25F);
this.tmsMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.toolsToolStripMenuItem,
this.helpToolStripMenuItem});
this.tmsMenuStrip.Location = new System.Drawing.Point(0, 0);
this.tmsMenuStrip.Name = "tmsMenuStrip";
this.tmsMenuStrip.Size = new System.Drawing.Size(251, 24);
this.tmsMenuStrip.TabIndex = 0;
this.tmsMenuStrip.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripMenuItem,
this.openToolStripMenuItem,
this.toolStripSeparator,
this.saveToolStripMenuItem,
this.saveAsToolStripMenuItem,
this.toolStripSeparator1,
this.printToolStripMenuItem,
this.printPreviewToolStripMenuItem,
this.toolStripSeparator2,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// newToolStripMenuItem
//
this.newToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripMenuItem.Image")));
this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
this.newToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.newToolStripMenuItem.Text = "&New";
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image")));
this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.openToolStripMenuItem.Text = "&Open";
//
// toolStripSeparator
//
this.toolStripSeparator.Name = "toolStripSeparator";
this.toolStripSeparator.Size = new System.Drawing.Size(144, 6);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image")));
this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.saveToolStripMenuItem.Text = "&Save";
//
// saveAsToolStripMenuItem
//
this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.saveAsToolStripMenuItem.Text = "Save &As";
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(144, 6);
//
// printToolStripMenuItem
//
this.printToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripMenuItem.Image")));
this.printToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printToolStripMenuItem.Name = "printToolStripMenuItem";
this.printToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P)));
this.printToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.printToolStripMenuItem.Text = "&Print";
//
// printPreviewToolStripMenuItem
//
this.printPreviewToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printPreviewToolStripMenuItem.Image")));
this.printPreviewToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printPreviewToolStripMenuItem.Name = "printPreviewToolStripMenuItem";
this.printPreviewToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.printPreviewToolStripMenuItem.Text = "Print Pre&view";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(144, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.exitToolStripMenuItem.Text = "E&xit";
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem,
this.toolStripSeparator3,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.toolStripSeparator4,
this.selectAllToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "&Edit";
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
this.undoToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.undoToolStripMenuItem.Text = "&Undo";
//
// redoToolStripMenuItem
//
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y)));
this.redoToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.redoToolStripMenuItem.Text = "&Redo";
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(146, 6);
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripMenuItem.Image")));
this.cutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X)));
this.cutToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.cutToolStripMenuItem.Text = "Cu&t";
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripMenuItem.Image")));
this.copyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.copyToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.copyToolStripMenuItem.Text = "&Copy";
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripMenuItem.Image")));
this.pasteToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.pasteToolStripMenuItem.Text = "&Paste";
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(146, 6);
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.selectAllToolStripMenuItem.Text = "Select &All";
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.customizeToolStripMenuItem,
this.optionsToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
this.toolsToolStripMenuItem.Size = new System.Drawing.Size(46, 20);
this.toolsToolStripMenuItem.Text = "&Tools";
//
// customizeToolStripMenuItem
//
this.customizeToolStripMenuItem.Name = "customizeToolStripMenuItem";
this.customizeToolStripMenuItem.Size = new System.Drawing.Size(134, 22);
this.customizeToolStripMenuItem.Text = "&Customize";
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(134, 22);
this.optionsToolStripMenuItem.Text = "&Options";
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.contentsToolStripMenuItem,
this.indexToolStripMenuItem,
this.searchToolStripMenuItem,
this.toolStripSeparator5,
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(43, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// contentsToolStripMenuItem
//
this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem";
this.contentsToolStripMenuItem.Size = new System.Drawing.Size(128, 22);
this.contentsToolStripMenuItem.Text = "&Contents";
//
// indexToolStripMenuItem
//
this.indexToolStripMenuItem.Name = "indexToolStripMenuItem";
this.indexToolStripMenuItem.Size = new System.Drawing.Size(128, 22);
this.indexToolStripMenuItem.Text = "&Index";
//
// searchToolStripMenuItem
//
this.searchToolStripMenuItem.Name = "searchToolStripMenuItem";
this.searchToolStripMenuItem.Size = new System.Drawing.Size(128, 22);
this.searchToolStripMenuItem.Text = "&Search";
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(125, 6);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(128, 22);
this.aboutToolStripMenuItem.Text = "&About...";
//
// tmsStatusStrip
//
this.tmsStatusStrip.Font = new System.Drawing.Font("Segoe UI", 8.25F);
this.tmsStatusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1});
this.tmsStatusStrip.Location = new System.Drawing.Point(0, 221);
this.tmsStatusStrip.Name = "tmsStatusStrip";
this.tmsStatusStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode;
this.tmsStatusStrip.Size = new System.Drawing.Size(251, 22);
this.tmsStatusStrip.TabIndex = 1;
this.tmsStatusStrip.Text = "statusStrip1";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(91, 17);
this.toolStripStatusLabel1.Text = "StatusStrip label";
//
// tmsToolStrip
//
this.tmsToolStrip.Dock = System.Windows.Forms.DockStyle.None;
this.tmsToolStrip.Font = new System.Drawing.Font("Segoe UI", 8.25F);
this.tmsToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripButton,
this.openToolStripButton,
this.saveToolStripButton,
this.printToolStripButton,
this.toolStripSeparator6,
this.cutToolStripButton,
this.copyToolStripButton,
this.pasteToolStripButton,
this.toolStripSeparator7,
this.helpToolStripButton});
this.tmsToolStrip.Location = new System.Drawing.Point(3, 0);
this.tmsToolStrip.Name = "tmsToolStrip";
this.tmsToolStrip.Size = new System.Drawing.Size(208, 25);
this.tmsToolStrip.TabIndex = 2;
this.tmsToolStrip.Text = "toolStrip1";
//
// newToolStripButton
//
this.newToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.newToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripButton.Image")));
this.newToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.newToolStripButton.Name = "newToolStripButton";
this.newToolStripButton.Size = new System.Drawing.Size(23, 22);
this.newToolStripButton.Text = "&New";
//
// openToolStripButton
//
this.openToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.openToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripButton.Image")));
this.openToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripButton.Name = "openToolStripButton";
this.openToolStripButton.Size = new System.Drawing.Size(23, 22);
this.openToolStripButton.Text = "&Open";
//
// saveToolStripButton
//
this.saveToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.saveToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripButton.Image")));
this.saveToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripButton.Name = "saveToolStripButton";
this.saveToolStripButton.Size = new System.Drawing.Size(23, 22);
this.saveToolStripButton.Text = "&Save";
//
// printToolStripButton
//
this.printToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.printToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripButton.Image")));
this.printToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.printToolStripButton.Name = "printToolStripButton";
this.printToolStripButton.Size = new System.Drawing.Size(23, 22);
this.printToolStripButton.Text = "&Print";
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25);
//
// cutToolStripButton
//
this.cutToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.cutToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripButton.Image")));
this.cutToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cutToolStripButton.Name = "cutToolStripButton";
this.cutToolStripButton.Size = new System.Drawing.Size(23, 22);
this.cutToolStripButton.Text = "C&ut";
//
// copyToolStripButton
//
this.copyToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.copyToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripButton.Image")));
this.copyToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.copyToolStripButton.Name = "copyToolStripButton";
this.copyToolStripButton.Size = new System.Drawing.Size(23, 22);
this.copyToolStripButton.Text = "&Copy";
//
// pasteToolStripButton
//
this.pasteToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.pasteToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripButton.Image")));
this.pasteToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pasteToolStripButton.Name = "pasteToolStripButton";
this.pasteToolStripButton.Size = new System.Drawing.Size(23, 22);
this.pasteToolStripButton.Text = "&Paste";
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(6, 25);
//
// helpToolStripButton
//
this.helpToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.helpToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("helpToolStripButton.Image")));
this.helpToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.helpToolStripButton.Name = "helpToolStripButton";
this.helpToolStripButton.Size = new System.Drawing.Size(23, 22);
this.helpToolStripButton.Text = "He&lp";
//
// tmsToolStripContainer
//
//
// tmsToolStripContainer.ContentPanel
//
this.tmsToolStripContainer.ContentPanel.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode;
this.tmsToolStripContainer.ContentPanel.Size = new System.Drawing.Size(251, 172);
this.tmsToolStripContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.tmsToolStripContainer.Location = new System.Drawing.Point(0, 24);
this.tmsToolStripContainer.Name = "tmsToolStripContainer";
this.tmsToolStripContainer.Size = new System.Drawing.Size(251, 197);
this.tmsToolStripContainer.TabIndex = 3;
this.tmsToolStripContainer.Text = "toolStripContainer1";
//
// tmsToolStripContainer.TopToolStripPanel
//
this.tmsToolStripContainer.TopToolStripPanel.Controls.Add(this.tmsToolStrip);
//
// FormChromeTMS
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(251, 243);
this.Controls.Add(this.tmsToolStripContainer);
this.Controls.Add(this.tmsStatusStrip);
this.Controls.Add(this.tmsMenuStrip);
this.MainMenuStrip = this.tmsMenuStrip;
this.Name = "FormChromeTMS";
this.Text = "Chrome + ToolMenuStatus Strips";
this.tmsMenuStrip.ResumeLayout(false);
this.tmsMenuStrip.PerformLayout();
this.tmsStatusStrip.ResumeLayout(false);
this.tmsStatusStrip.PerformLayout();
this.tmsToolStrip.ResumeLayout(false);
this.tmsToolStrip.PerformLayout();
this.tmsToolStripContainer.TopToolStripPanel.ResumeLayout(false);
this.tmsToolStripContainer.TopToolStripPanel.PerformLayout();
this.tmsToolStripContainer.ResumeLayout(false);
this.tmsToolStripContainer.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip tmsMenuStrip;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem printPreviewToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem customizeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem contentsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem indexToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem searchToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.StatusStrip tmsStatusStrip;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.ToolStrip tmsToolStrip;
private System.Windows.Forms.ToolStripButton newToolStripButton;
private System.Windows.Forms.ToolStripButton openToolStripButton;
private System.Windows.Forms.ToolStripButton saveToolStripButton;
private System.Windows.Forms.ToolStripButton printToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripButton cutToolStripButton;
private System.Windows.Forms.ToolStripButton copyToolStripButton;
private System.Windows.Forms.ToolStripButton pasteToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripButton helpToolStripButton;
private System.Windows.Forms.ToolStripContainer tmsToolStripContainer;
}
}
| |
// 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.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.AddImport;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Packaging;
using Microsoft.CodeAnalysis.SymbolSearch;
using Moq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.AddUsing
{
using FixProviderData = Tuple<IPackageInstallerService, ISymbolSearchService>;
public partial class AddUsingTests
{
const string NugetOrgSource = "nuget.org";
public class NuGet : AddUsingTests
{
private static readonly ImmutableArray<PackageSource> NugetPackageSources =
ImmutableArray.Create(new PackageSource(NugetOrgSource, "http://nuget.org/"));
protected override async Task<TestWorkspace> CreateWorkspaceFromFileAsync(string definition, ParseOptions parseOptions, CompilationOptions compilationOptions)
{
var workspace = await base.CreateWorkspaceFromFileAsync(definition, parseOptions, compilationOptions);
workspace.Options = workspace.Options
.WithChangedOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.CSharp, true)
.WithChangedOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.CSharp, true);
return workspace;
}
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(
Workspace workspace, object fixProviderData)
{
var data = (FixProviderData)fixProviderData;
return Tuple.Create<DiagnosticAnalyzer, CodeFixProvider>(
null,
new CSharpAddImportCodeFixProvider(data.Item1, data.Item2));
}
protected override IList<CodeAction> MassageActions(IList<CodeAction> actions)
{
return FlattenActions(actions);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestSearchPackageSingleName()
{
// Make a loose mock for the installer service. We don't care what this test
// calls on it.
var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose);
installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny<Workspace>(), It.IsAny<DocumentId>(), It.IsAny<string>(), "NuGetPackage", It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<CancellationToken>()))
.Returns(true);
var packageServiceMock = new Mock<ISymbolSearchService>();
packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync(
NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>()))
.Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace")));
await TestAsync(
@"class C
{
[|NuGetType|] n;
}",
@"using NuGetNamespace;
class C
{
NuGetType n;
}", systemSpecialCase: false, fixProviderData: new FixProviderData(installerServiceMock.Object, packageServiceMock.Object));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestSearchPackageMultipleNames()
{
// Make a loose mock for the installer service. We don't care what this test
// calls on it.
var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose);
installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny<Workspace>(), It.IsAny<DocumentId>(), It.IsAny<string>(), "NuGetPackage", It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<CancellationToken>()))
.Returns(true);
var packageServiceMock = new Mock<ISymbolSearchService>();
packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync(
NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>()))
.Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2")));
await TestAsync(
@"class C
{
[|NuGetType|] n;
}",
@"using NS1.NS2;
class C
{
NuGetType n;
}", systemSpecialCase: false, fixProviderData: new FixProviderData(installerServiceMock.Object, packageServiceMock.Object));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestMissingIfPackageAlreadyInstalled()
{
// Make a loose mock for the installer service. We don't care what this test
// calls on it.
var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose);
installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.IsInstalled(It.IsAny<Workspace>(), It.IsAny<ProjectId>(), "NuGetPackage"))
.Returns(true);
var packageServiceMock = new Mock<ISymbolSearchService>();
packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync(
NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>()))
.Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2")));
await TestMissingAsync(
@"class C
{
[|NuGetType|] n;
}", fixProviderData: new FixProviderData(installerServiceMock.Object, packageServiceMock.Object));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestOptionsOffered()
{
// Make a loose mock for the installer service. We don't care what this test
// calls on it.
var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose);
installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.GetInstalledVersions("NuGetPackage"))
.Returns(ImmutableArray.Create("1.0", "2.0"));
var packageServiceMock = new Mock<ISymbolSearchService>();
packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync(
NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>()))
.Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2")));
var data = new FixProviderData(installerServiceMock.Object, packageServiceMock.Object);
await TestSmartTagTextAsync(
@"class C
{
[|NuGetType|] n;
}",
"Use local version '1.0'",
index: 0,
fixProviderData: data);
await TestSmartTagTextAsync(
@"class C
{
[|NuGetType|] n;
}",
"Use local version '2.0'",
index: 1,
fixProviderData: data);
await TestSmartTagTextAsync(
@"class C
{
[|NuGetType|] n;
}",
"Find and install latest version",
index: 2,
fixProviderData: data);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestInstallGetsCalledNoVersion()
{
var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose);
installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny<Workspace>(), It.IsAny<DocumentId>(), It.IsAny<string>(), "NuGetPackage", /*versionOpt*/ null, It.IsAny<bool>(), It.IsAny<CancellationToken>()))
.Returns(true);
var packageServiceMock = new Mock<ISymbolSearchService>();
packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync(
NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>()))
.Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace")));
await TestAsync(
@"class C
{
[|NuGetType|] n;
}",
@"using NuGetNamespace;
class C
{
NuGetType n;
}", systemSpecialCase: false, fixProviderData: new FixProviderData(installerServiceMock.Object, packageServiceMock.Object));
installerServiceMock.Verify();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestInstallGetsCalledWithVersion()
{
var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose);
installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.GetInstalledVersions("NuGetPackage"))
.Returns(ImmutableArray.Create("1.0"));
installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny<Workspace>(), It.IsAny<DocumentId>(), It.IsAny<string>(), "NuGetPackage", "1.0", It.IsAny<bool>(), It.IsAny<CancellationToken>()))
.Returns(true);
var packageServiceMock = new Mock<ISymbolSearchService>();
packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>()))
.Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace")));
await TestAsync(
@"class C
{
[|NuGetType|] n;
}",
@"using NuGetNamespace;
class C
{
NuGetType n;
}", systemSpecialCase: false, fixProviderData: new FixProviderData(installerServiceMock.Object, packageServiceMock.Object));
installerServiceMock.Verify();
}
[WorkItem(14516, "https://github.com/dotnet/roslyn/pull/14516")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public async Task TestFailedInstallRollsBackFile()
{
var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose);
installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.GetInstalledVersions("NuGetPackage"))
.Returns(ImmutableArray.Create("1.0"));
installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny<Workspace>(), It.IsAny<DocumentId>(), It.IsAny<string>(), "NuGetPackage", "1.0", It.IsAny<bool>(), It.IsAny<CancellationToken>()))
.Returns(false);
var packageServiceMock = new Mock<ISymbolSearchService>();
packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>()))
.Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace")));
await TestAsync(
@"class C
{
[|NuGetType|] n;
}",
@"class C
{
NuGetType n;
}", systemSpecialCase: false, fixProviderData: new FixProviderData(installerServiceMock.Object, packageServiceMock.Object));
installerServiceMock.Verify();
}
private Task<ImmutableArray<PackageWithTypeResult>> CreateSearchResult(
string packageName, string typeName, IReadOnlyList<string> containingNamespaceNames)
{
return CreateSearchResult(new PackageWithTypeResult(
packageName: packageName, typeName: typeName, version: null,
rank: 0, containingNamespaceNames: containingNamespaceNames));
}
private Task<ImmutableArray<PackageWithTypeResult>> CreateSearchResult(params PackageWithTypeResult[] results)
=> Task.FromResult(ImmutableArray.Create(results));
private IReadOnlyList<string> CreateNameParts(params string[] parts) => parts;
}
}
}
| |
using System;
using System.Text;
/// <summary>
/// GetBytes(System.String,System.Int32,System.Int32,System.Byte[],System.Int32)
/// </summary>
public class EncodingGetBytes5
{
#region Private Fields
private const string c_TEST_STR = "za\u0306\u01FD\u03B2\uD8FF\uDCFF";
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method GetBytes(System.String) with UTF8.");
try
{
Encoding u8 = Encoding.UTF8;
byte[] bytes = new byte[u8.GetMaxByteCount(3)];
if (u8.GetBytes(c_TEST_STR, 4, 3, bytes, bytes.GetLowerBound(0)) != 6)
{
TestLibrary.TestFramework.LogError("002.1", "Method GetBytes Err.");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method GetBytes(System.String) with Unicode.");
try
{
Encoding u16LE = Encoding.Unicode;
byte[] bytes = new byte[u16LE.GetMaxByteCount(3)];
if (u16LE.GetBytes(c_TEST_STR, 4, 3, bytes, bytes.GetLowerBound(0)) != 6)
{
TestLibrary.TestFramework.LogError("003.1", "Method GetBytes Err.");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method GetBytes(System.String) with BigEndianUnicode.");
try
{
Encoding u16BE = Encoding.BigEndianUnicode;
byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
if (u16BE.GetBytes(c_TEST_STR, 4, 3, bytes, bytes.GetLowerBound(0)) != 6)
{
TestLibrary.TestFramework.LogError("004.1", "Method GetBytes Err.");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown.");
try
{
string testNullStr = null;
Encoding u16BE = Encoding.BigEndianUnicode;
byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
int i = u16BE.GetBytes(testNullStr, 4, 3, bytes, bytes.GetLowerBound(0));
TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown.");
retVal = false;
}
catch (ArgumentNullException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentNullException is not thrown.");
try
{
Encoding u16BE = Encoding.BigEndianUnicode;
byte[] bytes = null;
int i = u16BE.GetBytes(c_TEST_STR, 4, 3, bytes, 1);
TestLibrary.TestFramework.LogError("102.1", "ArgumentNullException is not thrown.");
retVal = false;
}
catch (ArgumentNullException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException is not thrown.");
try
{
Encoding u16BE = Encoding.BigEndianUnicode;
byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
int i = u16BE.GetBytes(c_TEST_STR, -1, 3, bytes, bytes.GetLowerBound(0));
TestLibrary.TestFramework.LogError("103.1", "ArgumentOutOfRangeException is not thrown.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException is not thrown.");
try
{
Encoding u16BE = Encoding.BigEndianUnicode;
byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
int i = u16BE.GetBytes(c_TEST_STR, 4, -1, bytes, bytes.GetLowerBound(0));
TestLibrary.TestFramework.LogError("104.1", "ArgumentOutOfRangeException is not thrown.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: ArgumentOutOfRangeException is not thrown.");
try
{
Encoding u16BE = Encoding.BigEndianUnicode;
byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
int i = u16BE.GetBytes(c_TEST_STR, 4, 3, bytes, -1);
TestLibrary.TestFramework.LogError("105.1", "ArgumentOutOfRangeException is not thrown.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("105.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: ArgumentOutOfRangeException is not thrown.");
try
{
Encoding u16BE = Encoding.BigEndianUnicode;
byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
int i = u16BE.GetBytes(c_TEST_STR, c_TEST_STR.Length - 1, 3, bytes, bytes.GetLowerBound(0));
TestLibrary.TestFramework.LogError("106.1", "ArgumentOutOfRangeException is not thrown.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest7: ArgumentException is not thrown.");
try
{
Encoding u16BE = Encoding.BigEndianUnicode;
byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
int i = u16BE.GetBytes(c_TEST_STR, 4, 3, bytes, bytes.Length - 1);
TestLibrary.TestFramework.LogError("107.1", "ArgumentException is not thrown.");
retVal = false;
}
catch (ArgumentException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("107.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
EncodingGetBytes5 test = new EncodingGetBytes5();
TestLibrary.TestFramework.BeginTestCase("EncodingGetBytes5");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Method
private bool VerifyByteItemValue(byte[] getBytes, byte[] actualBytes)
{
if (getBytes.Length != actualBytes.Length)
return false;
else
{
for (int i = 0; i < getBytes.Length; i++)
if (getBytes[i] != actualBytes[i])
return false;
}
return true;
}
#endregion
}
| |
/*!
@file
@author Generate utility by Albert Semenov
@date 01/2009
@module
*/
using System;
using System.Runtime.InteropServices;
namespace MyGUI.Sharp
{
public class ScrollBar :
Widget
{
#region ScrollBar
protected override string GetWidgetType() { return "ScrollBar"; }
internal static BaseWidget RequestWrapScrollBar(BaseWidget _parent, IntPtr _widget)
{
ScrollBar widget = new ScrollBar();
widget.WrapWidget(_parent, _widget);
return widget;
}
internal static BaseWidget RequestCreateScrollBar(BaseWidget _parent, WidgetStyle _style, string _skin, IntCoord _coord, Align _align, string _layer, string _name)
{
ScrollBar widget = new ScrollBar();
widget.CreateWidgetImpl(_parent, _style, _skin, _coord, _align, _layer, _name);
return widget;
}
#endregion
//InsertPoint
#region Event ScrollChangePosition
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportScrollBarEvent_AdviseScrollChangePosition(IntPtr _native, bool _advise);
public delegate void HandleScrollChangePosition(
ScrollBar _sender,
uint _position);
private HandleScrollChangePosition mEventScrollChangePosition;
public event HandleScrollChangePosition EventScrollChangePosition
{
add
{
if (ExportEventScrollChangePosition.mDelegate == null)
{
ExportEventScrollChangePosition.mDelegate = new ExportEventScrollChangePosition.ExportHandle(OnExportScrollChangePosition);
ExportEventScrollChangePosition.ExportScrollBarEvent_DelegateScrollChangePosition(ExportEventScrollChangePosition.mDelegate);
}
if (mEventScrollChangePosition == null)
ExportScrollBarEvent_AdviseScrollChangePosition(Native, true);
mEventScrollChangePosition += value;
}
remove
{
mEventScrollChangePosition -= value;
if (mEventScrollChangePosition == null)
ExportScrollBarEvent_AdviseScrollChangePosition(Native, false);
}
}
private struct ExportEventScrollChangePosition
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportScrollBarEvent_DelegateScrollChangePosition(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender,
uint _position);
public static ExportHandle mDelegate;
}
private static void OnExportScrollChangePosition(
IntPtr _sender,
uint _position)
{
ScrollBar sender = (ScrollBar)BaseWidget.GetByNative(_sender);
if (sender.mEventScrollChangePosition != null)
sender.mEventScrollChangePosition(
sender ,
_position);
}
#endregion
#region Property MoveToClick
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportScrollBar_GetMoveToClick(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportScrollBar_SetMoveToClick(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool MoveToClick
{
get { return ExportScrollBar_GetMoveToClick(Native); }
set { ExportScrollBar_SetMoveToClick(Native, value); }
}
#endregion
#region Property MinTrackSize
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern int ExportScrollBar_GetMinTrackSize(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportScrollBar_SetMinTrackSize(IntPtr _widget, int _value);
public int MinTrackSize
{
get { return ExportScrollBar_GetMinTrackSize(Native); }
set { ExportScrollBar_SetMinTrackSize(Native, value); }
}
#endregion
#region Property TrackSize
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern int ExportScrollBar_GetTrackSize(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportScrollBar_SetTrackSize(IntPtr _widget, int _value);
public int TrackSize
{
get { return ExportScrollBar_GetTrackSize(Native); }
set { ExportScrollBar_SetTrackSize(Native, value); }
}
#endregion
#region Property LineSize
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern int ExportScrollBar_GetLineSize(IntPtr _native);
public int LineSize
{
get { return ExportScrollBar_GetLineSize(Native); }
}
#endregion
#region Property ScrollViewPage
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportScrollBar_GetScrollViewPage(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportScrollBar_SetScrollViewPage(IntPtr _widget, uint _value);
public uint ScrollViewPage
{
get { return ExportScrollBar_GetScrollViewPage(Native); }
set { ExportScrollBar_SetScrollViewPage(Native, value); }
}
#endregion
#region Property ScrollPage
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportScrollBar_GetScrollPage(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportScrollBar_SetScrollPage(IntPtr _widget, uint _value);
public uint ScrollPage
{
get { return ExportScrollBar_GetScrollPage(Native); }
set { ExportScrollBar_SetScrollPage(Native, value); }
}
#endregion
#region Property ScrollPosition
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportScrollBar_GetScrollPosition(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportScrollBar_SetScrollPosition(IntPtr _widget, uint _value);
public uint ScrollPosition
{
get { return ExportScrollBar_GetScrollPosition(Native); }
set { ExportScrollBar_SetScrollPosition(Native, value); }
}
#endregion
#region Property ScrollRange
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportScrollBar_GetScrollRange(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportScrollBar_SetScrollRange(IntPtr _widget, uint _value);
public uint ScrollRange
{
get { return ExportScrollBar_GetScrollRange(Native); }
set { ExportScrollBar_SetScrollRange(Native, value); }
}
#endregion
#region Property VerticalAlignment
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportScrollBar_GetVerticalAlignment(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportScrollBar_SetVerticalAlignment(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool VerticalAlignment
{
get { return ExportScrollBar_GetVerticalAlignment(Native); }
set { ExportScrollBar_SetVerticalAlignment(Native, value); }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
namespace Platform.VirtualFileSystem.Providers.Overlayed
{
public delegate INode OverlayedNodeSelectorFunction(OverlayedFileSystem fileSystem, INodeAddress address, NodeType nodeType);
#region DelegateBasedOverlayedNodeSelector
public class DelegateBasedOverlayedNodeSelector
: OverlayedNodeSelector
{
private readonly OverlayedNodeSelectorFunction getReadNodeFunction;
private readonly OverlayedNodeSelectorFunction getWriteNodeFunction;
public DelegateBasedOverlayedNodeSelector(OverlayedNodeSelectorFunction getReadNodeFunction, OverlayedNodeSelectorFunction getWriteNodeFunction)
{
this.getReadNodeFunction = getReadNodeFunction;
this.getWriteNodeFunction = getWriteNodeFunction;
}
public override INode SelectWriteNode(OverlayedFileSystem fileSystem, INodeAddress address, NodeType nodeType)
{
return getWriteNodeFunction(fileSystem, address, nodeType);
}
public override INode SelectReadNode(OverlayedFileSystem fileSystem, INodeAddress address, NodeType nodeType)
{
return getReadNodeFunction(fileSystem, address, nodeType);
}
}
public abstract class OverlayedNodeSelector
{
public virtual INode SelectWriteNode(OverlayedFileSystem fileSystem, INodeAddress address, NodeType nodeType)
{
return SelectReadNode(fileSystem, address, nodeType);
}
public abstract INode SelectReadNode(OverlayedFileSystem fileSystem, INodeAddress address, NodeType nodeType);
public virtual bool SelectNodeForOperation(OverlayedFileSystem fileSystem, FileSystemActivity operation, INodeAddress address, NodeType nodeType, out INode[] nodes)
{
nodes = null;
return false;
}
}
#endregion
public class OverlayedFileSystemEventArgs
: EventArgs
{
}
public class OverlayedFileSystem
: AbstractFileSystem
{
private IList<IFileSystem> readonlyFileSystems;
private readonly IList<IFileSystem> fileSystems;
public override bool SupportsActivityEvents
{
get
{
return true;
}
}
public override event FileSystemActivityEventHandler Activity
{
add
{
lock (activityLock)
{
if (activityEvents == null)
{
AttachActivityHandlers();
}
activityEvents = (FileSystemActivityEventHandler)Delegate.Combine(activityEvents, value);
}
}
remove
{
lock (activityLock)
{
activityEvents = (FileSystemActivityEventHandler)Delegate.Remove(activityEvents, value);
if (activityEvents == null)
{
RemoveActivityHandlers();
}
}
}
}
private readonly object activityLock = new object();
private FileSystemActivityEventHandler activityEvents;
private void AttachActivityHandlers()
{
foreach (var fileSystem in this.FileSystems)
{
fileSystem.Activity += FileSystemsActivity;
}
}
private void RemoveActivityHandlers()
{
foreach (var fileSystem in this.FileSystems)
{
fileSystem.Activity -= FileSystemsActivity;
}
}
private void FileSystemsActivity(object sender, FileSystemActivityEventArgs eventArgs)
{
if (activityEvents != null)
{
if (this.SecurityManager.CurrentContext.IsEmpty)
{
activityEvents(this, eventArgs);
}
else
{
var node = this.Resolve(eventArgs.Path, eventArgs.NodeType);
if (this.SecurityManager.CurrentContext.HasAccess(new AccessVerificationContext(node, FileSystemSecuredOperation.View)))
{
activityEvents(this, eventArgs);
}
}
}
}
public virtual IList<IFileSystem> FileSystems
{
get
{
return fileSystems;
}
}
public OverlayedNodeSelector OverlayedNodeSelector
{
get; private set;
}
private static FileSystemOptions VerifyOptions(FileSystemOptions options)
{
options.NodeCacheType = typeof(PathKeyedNodeCache);
return options;
}
public override void Close()
{
RemoveActivityHandlers();
foreach (IFileSystem fs in this.FileSystems)
{
fs.Close();
}
}
/// <summary>
/// Checks if an address is ok.
/// </summary>
/// <remarks>
/// <see cref="AbstractFileSystem.AddressOk(INodeAddress)"/>
/// </remarks>
protected override bool AddressOk(INodeAddress address)
{
return true;
}
/// <summary>
/// Callback handler that removes file systems as they are closed.
/// </summary>
protected virtual void FileSystem_Closed(object sender, EventArgs e)
{
((IFileSystem)sender).Activity -= this.FileSystemsActivity;
this.fileSystems.Remove((IFileSystem)sender);
}
/// <summary>
/// Construct a new <see cref="OverlayedFileSystem"/>.
/// </summary>
/// <param name="fileSystems">The file systems to initially add to this file system.</param>
public OverlayedFileSystem(params IFileSystem[] fileSystems)
: this(fileSystems, FileSystemOptions.Default, new StandardOverlayedNodeSelector())
{
}
/// <summary>
/// Construct a new <see cref="OverlayedFileSystem"/>.
/// </summary>
/// <param name="fileSystems">The file systems to initially add to this file system.</param>
/// <param name="options">The options for the file system.</param>
public OverlayedFileSystem(FileSystemOptions options, params IFileSystem[] fileSystems)
: this(fileSystems, options, new StandardOverlayedNodeSelector())
{
}
/// <summary>
/// Construct a new <see cref="OverlayedFileSystem"/>.
/// </summary>
/// <param name="fileSystems">The file systems to initially add to this file system.</param>
/// <param name="options">The options for the file system.</param>
public OverlayedFileSystem(IEnumerable<IFileSystem> fileSystems, FileSystemOptions options)
: this(fileSystems, options, new StandardOverlayedNodeSelector())
{
}
/// <summary>
/// Construct a new <see cref="OverlayedFileSystem"/>.
/// </summary>
/// <param name="name">The name of the file system.</param>
/// <param name="fileSystems">The file systems to initially add to this file system.</param>
/// <param name="options">The options for the file system.</param>
public OverlayedFileSystem(string name, IEnumerable<IFileSystem> fileSystems, FileSystemOptions options)
: this(name, fileSystems, options, new StandardOverlayedNodeSelector())
{
}
/// <summary>
/// Construct a new <see cref="OverlayedFileSystem"/>.
/// </summary>
/// <param name="fileSystems">The file systems to initially add to this file system.</param>
/// <param name="options">The options for the file system.</param>
/// <param name="overlayedNodeSelector">The <c>OverlayedNodeSelector</c> to use to select/resolve files.</param>
public OverlayedFileSystem(IEnumerable<IFileSystem> fileSystems, FileSystemOptions options, OverlayedNodeSelector overlayedNodeSelector)
: this(null, fileSystems, options, overlayedNodeSelector)
{
}
/// <summary>
/// Construct a new <see cref="OverlayedFileSystem"/>.
/// </summary>
/// <param name="name">The name of the file system.</param>
/// <param name="fileSystems">The file systems to initially add to this file system.</param>
/// <param name="options">The options for the file system.</param>
/// <param name="overlayedNodeSelector">The <c>OverlayedNodeSelector</c> to use to select/resolve files.</param>
public OverlayedFileSystem(string name, IEnumerable<IFileSystem> fileSystems, FileSystemOptions options, OverlayedNodeSelector overlayedNodeSelector)
: base(new StandardNodeAddress(name == null ? "overlayed" : name, name != null ? null : OverlayedNodeProvider.NextUniqueName(), 0, 0, "", "", "/", "") , null, VerifyOptions(options))
{
this.fileSystems = new List<IFileSystem>();
foreach (IFileSystem fs in fileSystems)
{
fs.Closed += new EventHandler(FileSystem_Closed);
this.fileSystems.Add(fs);
}
readonlyFileSystems = ((List<IFileSystem>)this.fileSystems).AsReadOnly();
this.OverlayedNodeSelector = overlayedNodeSelector;
}
public class StandardOverlayedNodeSelector
: OverlayedNodeSelector
{
public override INode SelectReadNode(OverlayedFileSystem overlayedFileSystem, INodeAddress address, NodeType nodeType)
{
lock (overlayedFileSystem.FileSystems)
{
if (overlayedFileSystem.FileSystems.Count == 0)
{
throw new InvalidOperationException("Overlayed FileSystem isn't initialized with any file systems");
}
foreach (var fs in overlayedFileSystem.FileSystems)
{
var node = fs.Resolve(address.AbsolutePath, nodeType);
if (node.Exists)
{
return node;
}
}
return ((IFileSystem)overlayedFileSystem.FileSystems[0]).Resolve(address.AbsolutePath, nodeType);
}
}
}
/// <summary>
/// Gets a list of alternates for a certain node.
/// </summary>
/// <remarks>
/// Alternates of an <see cref="OverlayedFileSystem"/> are all the nodes on the underlying file systems that
/// make up the <see cref="OverlayedFileSystem"/>.
/// </remarks>
/// <param name="node">The node to get the alternates for.</param>
/// <returns>A list of the alternates.</returns>
internal IEnumerable<INode> GetAlternates(INode node)
{
var retvals = new List<INode>();
lock (this.SyncLock)
{
foreach (var fileSystem in fileSystems)
{
var alternateNode = fileSystem.Resolve(node.Address.AbsolutePath, node.NodeType);
// Don't yield directly here because we still hold the SyncLock
retvals.Add(alternateNode);
}
}
return retvals;
}
protected internal INode RefreshNode(INode node)
{
lock (this.FileSystems)
{
return this.OverlayedNodeSelector.SelectReadNode(this, node.Address, node.NodeType);
}
}
protected internal INode RefreshNodeForWrite(INode node)
{
lock (this.FileSystems)
{
return this.OverlayedNodeSelector.SelectWriteNode(this, node.Address, node.NodeType);
}
}
internal INode GetOverlay(INodeAddress nodeAddress, NodeType nodeType)
{
lock (this.FileSystems)
{
return OverlayNode(nodeAddress, this.OverlayedNodeSelector.SelectReadNode(this, nodeAddress, nodeType));
}
}
protected virtual INode OverlayNode(INodeAddress nodeAddress, INode node)
{
if (node.NodeType.Equals(NodeType.File))
{
return new OverlayedFile(this, nodeAddress, (IFile)node);
}
else if (node.NodeType.Equals(NodeType.Directory))
{
return new OverlayedDirectory(this, nodeAddress, (IDirectory)node);
}
else
{
throw new NodeTypeNotSupportedException(node.NodeType);
}
}
protected override INode CreateNode(INodeAddress address, NodeType nodeType)
{
return GetOverlay(address, nodeType);
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityModel;
using IdentityModel.Client;
using IdentityServer.IntegrationTests.Clients.Setup;
using IdentityServer.IntegrationTests.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
namespace IdentityServer.IntegrationTests.Clients
{
public class ClientAssertionClient
{
private const string TokenEndpoint = "https://idsvr4/connect/token";
private const string ClientId = "certificate_base64_valid";
private readonly HttpClient _client;
public ClientAssertionClient()
{
var builder = new WebHostBuilder()
.UseStartup<Startup>();
var server = new TestServer(builder);
_client = server.CreateClient();
}
[Fact]
public async Task Valid_client_with_manual_payload_should_succeed()
{
var token = CreateToken(ClientId);
var requestBody = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "client_id", ClientId },
{ "client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" },
{ "client_assertion", token },
{ "grant_type", "client_credentials" },
{ "scope", "api1" }
});
var response = await GetToken(requestBody);
AssertValidToken(response);
}
[Fact]
public async Task Valid_client_should_succeed()
{
var token = CreateToken(ClientId);
var response = await _client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = TokenEndpoint,
ClientId = ClientId,
ClientAssertion =
{
Type = OidcConstants.ClientAssertionTypes.JwtBearer,
Value = token
},
Scope = "api1"
});
AssertValidToken(response);
}
[Fact]
public async Task Valid_client_with_implicit_clientId_should_succeed()
{
var token = CreateToken(ClientId);
var response = await _client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = TokenEndpoint,
ClientId = "client",
ClientAssertion =
{
Type = OidcConstants.ClientAssertionTypes.JwtBearer,
Value = token
},
Scope = "api1"
});
AssertValidToken(response);
}
[Fact]
public async Task Valid_client_with_token_replay_should_fail()
{
var token = CreateToken(ClientId);
var response = await _client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = TokenEndpoint,
ClientId = ClientId,
ClientAssertion =
{
Type = OidcConstants.ClientAssertionTypes.JwtBearer,
Value = token
},
Scope = "api1"
});
AssertValidToken(response);
// replay
response = await _client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = TokenEndpoint,
ClientId = ClientId,
ClientAssertion =
{
Type = OidcConstants.ClientAssertionTypes.JwtBearer,
Value = token
},
Scope = "api1"
});
response.IsError.Should().BeTrue();
response.Error.Should().Be("invalid_client");
}
[Fact]
public async Task Client_with_invalid_secret_should_fail()
{
var response = await _client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = TokenEndpoint,
ClientId = ClientId,
ClientAssertion =
{
Type = OidcConstants.ClientAssertionTypes.JwtBearer,
Value = "invalid"
},
Scope = "api1"
});
response.IsError.Should().Be(true);
response.Error.Should().Be(OidcConstants.TokenErrors.InvalidClient);
response.ErrorType.Should().Be(ResponseErrorType.Protocol);
}
[Fact]
public async Task Invalid_client_should_fail()
{
const string clientId = "certificate_base64_invalid";
var token = CreateToken(clientId);
var response = await _client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = TokenEndpoint,
ClientId = clientId,
ClientAssertion =
{
Type = OidcConstants.ClientAssertionTypes.JwtBearer,
Value = token
},
Scope = "api1"
});
response.IsError.Should().Be(true);
response.Error.Should().Be(OidcConstants.TokenErrors.InvalidClient);
response.ErrorType.Should().Be(ResponseErrorType.Protocol);
}
private async Task<TokenResponse> GetToken(FormUrlEncodedContent body)
{
var response = await _client.PostAsync(TokenEndpoint, body);
return await ProtocolResponse.FromHttpResponseAsync<TokenResponse>(response);
}
private void AssertValidToken(TokenResponse response)
{
response.IsError.Should().Be(false);
response.ExpiresIn.Should().Be(3600);
response.TokenType.Should().Be("Bearer");
response.IdentityToken.Should().BeNull();
response.RefreshToken.Should().BeNull();
var payload = GetPayload(response);
payload.Count().Should().Be(8);
payload.Should().Contain("iss", "https://idsvr4");
payload.Should().Contain("client_id", ClientId);
payload.Keys.Should().Contain("iat");
var scopes = payload["scope"] as JArray;
scopes.First().ToString().Should().Be("api1");
payload["aud"].Should().Be("api");
}
private Dictionary<string, object> GetPayload(TokenResponse response)
{
var token = response.AccessToken.Split('.').Skip(1).Take(1).First();
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(
Encoding.UTF8.GetString(Base64Url.Decode(token)));
return dictionary;
}
private string CreateToken(string clientId, DateTime? nowOverride = null)
{
var certificate = TestCert.Load();
var now = nowOverride ?? DateTime.UtcNow;
var token = new JwtSecurityToken(
clientId,
TokenEndpoint,
new List<Claim>()
{
new Claim("jti", Guid.NewGuid().ToString()),
new Claim(JwtClaimTypes.Subject, clientId),
new Claim(JwtClaimTypes.IssuedAt, new DateTimeOffset(now).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
},
now,
now.AddMinutes(1),
new SigningCredentials(
new X509SecurityKey(certificate),
SecurityAlgorithms.RsaSha256
)
);
var tokenHandler = new JwtSecurityTokenHandler();
return tokenHandler.WriteToken(token);
}
}
}
| |
// 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.Linq;
using System.Xml.Linq;
namespace System.Xml.XPath
{
internal class XNodeNavigator : XPathNavigator, IXmlLineInfo
{
internal static readonly string xmlPrefixNamespace = XNamespace.Xml.NamespaceName;
internal static readonly string xmlnsPrefixNamespace = XNamespace.Xmlns.NamespaceName;
private const int DocumentContentMask =
(1 << (int)XmlNodeType.Element) |
(1 << (int)XmlNodeType.ProcessingInstruction) |
(1 << (int)XmlNodeType.Comment);
private static readonly int[] s_ElementContentMasks = {
0, // Root
(1 << (int)XmlNodeType.Element), // Element
0, // Attribute
0, // Namespace
(1 << (int)XmlNodeType.CDATA) |
(1 << (int)XmlNodeType.Text), // Text
0, // SignificantWhitespace
0, // Whitespace
(1 << (int)XmlNodeType.ProcessingInstruction), // ProcessingInstruction
(1 << (int)XmlNodeType.Comment), // Comment
(1 << (int)XmlNodeType.Element) |
(1 << (int)XmlNodeType.CDATA) |
(1 << (int)XmlNodeType.Text) |
(1 << (int)XmlNodeType.ProcessingInstruction) |
(1 << (int)XmlNodeType.Comment) // All
};
private const int TextMask =
(1 << (int)XmlNodeType.CDATA) |
(1 << (int)XmlNodeType.Text);
private static XAttribute s_XmlNamespaceDeclaration;
// The navigator position is encoded by the tuple (source, parent).
// Namespace declaration uses (instance, parent element).
// Common XObjects uses (instance, null).
private XObject _source;
private XElement _parent;
private XmlNameTable _nameTable;
public XNodeNavigator(XNode node, XmlNameTable nameTable)
{
_source = node;
_nameTable = nameTable != null ? nameTable : CreateNameTable();
}
public XNodeNavigator(XNodeNavigator other)
{
_source = other._source;
_parent = other._parent;
_nameTable = other._nameTable;
}
public override string BaseURI
{
get
{
if (_source != null)
{
return _source.BaseUri;
}
if (_parent != null)
{
return _parent.BaseUri;
}
return string.Empty;
}
}
public override bool HasAttributes
{
get
{
XElement element = _source as XElement;
if (element != null)
{
foreach (XAttribute attribute in element.Attributes())
{
if (!attribute.IsNamespaceDeclaration)
{
return true;
}
}
}
return false;
}
}
public override bool HasChildren
{
get
{
XContainer container = _source as XContainer;
if (container != null)
{
foreach (XNode node in container.Nodes())
{
if (IsContent(container, node))
{
return true;
}
}
}
return false;
}
}
public override bool IsEmptyElement
{
get
{
XElement e = _source as XElement;
return e != null && e.IsEmpty;
}
}
public override string LocalName
{
get { return _nameTable.Add(GetLocalName()); }
}
private string GetLocalName()
{
XElement e = _source as XElement;
if (e != null)
{
return e.Name.LocalName;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
if (_parent != null && a.Name.NamespaceName.Length == 0)
{
return string.Empty; // backcompat
}
return a.Name.LocalName;
}
XProcessingInstruction p = _source as XProcessingInstruction;
if (p != null)
{
return p.Target;
}
return string.Empty;
}
public override string Name
{
get
{
string prefix = GetPrefix();
if (prefix.Length == 0)
{
return _nameTable.Add(GetLocalName());
}
return _nameTable.Add(string.Concat(prefix, ":", GetLocalName()));
}
}
public override string NamespaceURI
{
get { return _nameTable.Add(GetNamespaceURI()); }
}
private string GetNamespaceURI()
{
XElement e = _source as XElement;
if (e != null)
{
return e.Name.NamespaceName;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
if (_parent != null)
{
return string.Empty; // backcompat
}
return a.Name.NamespaceName;
}
return string.Empty;
}
public override XmlNameTable NameTable
{
get { return _nameTable; }
}
public override XPathNodeType NodeType
{
get
{
if (_source != null)
{
switch (_source.NodeType)
{
case XmlNodeType.Element:
return XPathNodeType.Element;
case XmlNodeType.Attribute:
XAttribute attribute = (XAttribute)_source;
return attribute.IsNamespaceDeclaration ? XPathNodeType.Namespace : XPathNodeType.Attribute;
case XmlNodeType.Document:
return XPathNodeType.Root;
case XmlNodeType.Comment:
return XPathNodeType.Comment;
case XmlNodeType.ProcessingInstruction:
return XPathNodeType.ProcessingInstruction;
default:
return XPathNodeType.Text;
}
}
return XPathNodeType.Text;
}
}
public override string Prefix
{
get { return _nameTable.Add(GetPrefix()); }
}
private string GetPrefix()
{
XElement e = _source as XElement;
if (e != null)
{
string prefix = e.GetPrefixOfNamespace(e.Name.Namespace);
if (prefix != null)
{
return prefix;
}
return string.Empty;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
if (_parent != null)
{
return string.Empty; // backcompat
}
string prefix = a.GetPrefixOfNamespace(a.Name.Namespace);
if (prefix != null)
{
return prefix;
}
}
return string.Empty;
}
public override object UnderlyingObject
{
get
{
return _source;
}
}
public override string Value
{
get
{
if (_source != null)
{
switch (_source.NodeType)
{
case XmlNodeType.Element:
return ((XElement)_source).Value;
case XmlNodeType.Attribute:
return ((XAttribute)_source).Value;
case XmlNodeType.Document:
XElement root = ((XDocument)_source).Root;
return root != null ? root.Value : string.Empty;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
return CollectText((XText)_source);
case XmlNodeType.Comment:
return ((XComment)_source).Value;
case XmlNodeType.ProcessingInstruction:
return ((XProcessingInstruction)_source).Data;
default:
return string.Empty;
}
}
return string.Empty;
}
}
public override XPathNavigator Clone()
{
return new XNodeNavigator(this);
}
public override bool IsSamePosition(XPathNavigator navigator)
{
XNodeNavigator other = navigator as XNodeNavigator;
if (other == null)
{
return false;
}
return IsSamePosition(this, other);
}
public override bool MoveTo(XPathNavigator navigator)
{
XNodeNavigator other = navigator as XNodeNavigator;
if (other != null)
{
_source = other._source;
_parent = other._parent;
return true;
}
return false;
}
public override bool MoveToAttribute(string localName, string namespaceName)
{
XElement e = _source as XElement;
if (e != null)
{
foreach (XAttribute attribute in e.Attributes())
{
if (attribute.Name.LocalName == localName &&
attribute.Name.NamespaceName == namespaceName &&
!attribute.IsNamespaceDeclaration)
{
_source = attribute;
return true;
}
}
}
return false;
}
public override bool MoveToChild(string localName, string namespaceName)
{
XContainer c = _source as XContainer;
if (c != null)
{
foreach (XElement element in c.Elements())
{
if (element.Name.LocalName == localName &&
element.Name.NamespaceName == namespaceName)
{
_source = element;
return true;
}
}
}
return false;
}
public override bool MoveToChild(XPathNodeType type)
{
XContainer c = _source as XContainer;
if (c != null)
{
int mask = GetElementContentMask(type);
if ((TextMask & mask) != 0 && c.GetParent() == null && c is XDocument)
{
mask &= ~TextMask;
}
foreach (XNode node in c.Nodes())
{
if (((1 << (int)node.NodeType) & mask) != 0)
{
_source = node;
return true;
}
}
}
return false;
}
public override bool MoveToFirstAttribute()
{
XElement e = _source as XElement;
if (e != null)
{
foreach (XAttribute attribute in e.Attributes())
{
if (!attribute.IsNamespaceDeclaration)
{
_source = attribute;
return true;
}
}
}
return false;
}
public override bool MoveToFirstChild()
{
XContainer container = _source as XContainer;
if (container != null)
{
foreach (XNode node in container.Nodes())
{
if (IsContent(container, node))
{
_source = node;
return true;
}
}
}
return false;
}
public override bool MoveToFirstNamespace(XPathNamespaceScope scope)
{
XElement e = _source as XElement;
if (e != null)
{
XAttribute a = null;
switch (scope)
{
case XPathNamespaceScope.Local:
a = GetFirstNamespaceDeclarationLocal(e);
break;
case XPathNamespaceScope.ExcludeXml:
a = GetFirstNamespaceDeclarationGlobal(e);
while (a != null && a.Name.LocalName == "xml")
{
a = GetNextNamespaceDeclarationGlobal(a);
}
break;
case XPathNamespaceScope.All:
a = GetFirstNamespaceDeclarationGlobal(e);
if (a == null)
{
a = GetXmlNamespaceDeclaration();
}
break;
}
if (a != null)
{
_source = a;
_parent = e;
return true;
}
}
return false;
}
public override bool MoveToId(string id)
{
throw new NotSupportedException(SR.NotSupported_MoveToId);
}
public override bool MoveToNamespace(string localName)
{
XElement e = _source as XElement;
if (e != null)
{
if (localName == "xmlns")
{
return false; // backcompat
}
if (localName != null && localName.Length == 0)
{
localName = "xmlns"; // backcompat
}
XAttribute a = GetFirstNamespaceDeclarationGlobal(e);
while (a != null)
{
if (a.Name.LocalName == localName)
{
_source = a;
_parent = e;
return true;
}
a = GetNextNamespaceDeclarationGlobal(a);
}
if (localName == "xml")
{
_source = GetXmlNamespaceDeclaration();
_parent = e;
return true;
}
}
return false;
}
public override bool MoveToNext()
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
XContainer container = currentNode.GetParent();
if (container != null)
{
XNode next = null;
for (XNode node = currentNode; node != null; node = next)
{
next = node.NextNode;
if (next == null)
{
break;
}
if (IsContent(container, next) && !(node is XText && next is XText))
{
_source = next;
return true;
}
}
}
}
return false;
}
public override bool MoveToNext(string localName, string namespaceName)
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
foreach (XElement element in currentNode.ElementsAfterSelf())
{
if (element.Name.LocalName == localName &&
element.Name.NamespaceName == namespaceName)
{
_source = element;
return true;
}
}
}
return false;
}
public override bool MoveToNext(XPathNodeType type)
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
XContainer container = currentNode.GetParent();
if (container != null)
{
int mask = GetElementContentMask(type);
if ((TextMask & mask) != 0 && container.GetParent() == null && container is XDocument)
{
mask &= ~TextMask;
}
XNode next = null;
for (XNode node = currentNode; node != null; node = next)
{
next = node.NextNode;
if (((1 << (int)next.NodeType) & mask) != 0 && !(node is XText && next is XText))
{
_source = next;
return true;
}
}
}
}
return false;
}
public override bool MoveToNextAttribute()
{
XAttribute currentAttribute = _source as XAttribute;
if (currentAttribute != null && _parent == null)
{
XElement e = (XElement)currentAttribute.GetParent();
if (e != null)
{
for (XAttribute attribute = currentAttribute.NextAttribute; attribute != null; attribute = attribute.NextAttribute)
{
if (!attribute.IsNamespaceDeclaration)
{
_source = attribute;
return true;
}
}
}
}
return false;
}
public override bool MoveToNextNamespace(XPathNamespaceScope scope)
{
XAttribute a = _source as XAttribute;
if (a != null && _parent != null && !IsXmlNamespaceDeclaration(a))
{
switch (scope)
{
case XPathNamespaceScope.Local:
if (a.GetParent() != _parent)
{
return false;
}
a = GetNextNamespaceDeclarationLocal(a);
break;
case XPathNamespaceScope.ExcludeXml:
do
{
a = GetNextNamespaceDeclarationGlobal(a);
} while (a != null &&
(a.Name.LocalName == "xml" ||
HasNamespaceDeclarationInScope(a, _parent)));
break;
case XPathNamespaceScope.All:
do
{
a = GetNextNamespaceDeclarationGlobal(a);
} while (a != null &&
HasNamespaceDeclarationInScope(a, _parent));
if (a == null &&
!HasNamespaceDeclarationInScope(GetXmlNamespaceDeclaration(), _parent))
{
a = GetXmlNamespaceDeclaration();
}
break;
}
if (a != null)
{
_source = a;
return true;
}
}
return false;
}
public override bool MoveToParent()
{
if (_parent != null)
{
_source = _parent;
_parent = null;
return true;
}
XNode parentNode = _source.GetParent();
if (parentNode != null)
{
_source = parentNode;
return true;
}
return false;
}
public override bool MoveToPrevious()
{
XNode currentNode = _source as XNode;
if (currentNode != null)
{
XContainer container = currentNode.GetParent();
if (container != null)
{
XNode previous = null;
foreach (XNode node in container.Nodes())
{
if (node == currentNode)
{
if (previous != null)
{
_source = previous;
return true;
}
return false;
}
if (IsContent(container, node))
{
previous = node;
}
}
}
}
return false;
}
public override XmlReader ReadSubtree()
{
XContainer c = _source as XContainer;
if (c == null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadNodeType, NodeType));
return c.CreateReader();
}
bool IXmlLineInfo.HasLineInfo()
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.HasLineInfo();
}
return false;
}
int IXmlLineInfo.LineNumber
{
get
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.LineNumber;
}
return 0;
}
}
int IXmlLineInfo.LinePosition
{
get
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.LinePosition;
}
return 0;
}
}
private static string CollectText(XText n)
{
string s = n.Value;
if (n.GetParent() != null)
{
foreach (XNode node in n.NodesAfterSelf())
{
XText t = node as XText;
if (t == null) break;
s += t.Value;
}
}
return s;
}
private static XmlNameTable CreateNameTable()
{
XmlNameTable nameTable = new NameTable();
nameTable.Add(string.Empty);
nameTable.Add(xmlnsPrefixNamespace);
nameTable.Add(xmlPrefixNamespace);
return nameTable;
}
private static bool IsContent(XContainer c, XNode n)
{
if (c.GetParent() != null || c is XElement)
{
return true;
}
return ((1 << (int)n.NodeType) & DocumentContentMask) != 0;
}
private static bool IsSamePosition(XNodeNavigator n1, XNodeNavigator n2)
{
return n1._source == n2._source && n1._source.GetParent() == n2._source.GetParent();
}
private static bool IsXmlNamespaceDeclaration(XAttribute a)
{
return (object)a == (object)GetXmlNamespaceDeclaration();
}
private static int GetElementContentMask(XPathNodeType type)
{
return s_ElementContentMasks[(int)type];
}
private static XAttribute GetFirstNamespaceDeclarationGlobal(XElement e)
{
do
{
XAttribute a = GetFirstNamespaceDeclarationLocal(e);
if (a != null)
{
return a;
}
e = e.Parent;
} while (e != null);
return null;
}
private static XAttribute GetFirstNamespaceDeclarationLocal(XElement e)
{
foreach (XAttribute attribute in e.Attributes())
{
if (attribute.IsNamespaceDeclaration)
{
return attribute;
}
}
return null;
}
private static XAttribute GetNextNamespaceDeclarationGlobal(XAttribute a)
{
XElement e = (XElement)a.GetParent();
if (e == null)
{
return null;
}
XAttribute next = GetNextNamespaceDeclarationLocal(a);
if (next != null)
{
return next;
}
e = e.Parent;
if (e == null)
{
return null;
}
return GetFirstNamespaceDeclarationGlobal(e);
}
private static XAttribute GetNextNamespaceDeclarationLocal(XAttribute a)
{
XElement e = a.Parent;
if (e == null)
{
return null;
}
a = a.NextAttribute;
while (a != null)
{
if (a.IsNamespaceDeclaration)
{
return a;
}
a = a.NextAttribute;
}
return null;
}
private static XAttribute GetXmlNamespaceDeclaration()
{
if (s_XmlNamespaceDeclaration == null)
{
System.Threading.Interlocked.CompareExchange(ref s_XmlNamespaceDeclaration, new XAttribute(XNamespace.Xmlns.GetName("xml"), xmlPrefixNamespace), null);
}
return s_XmlNamespaceDeclaration;
}
private static bool HasNamespaceDeclarationInScope(XAttribute a, XElement e)
{
XName name = a.Name;
while (e != null && e != a.GetParent())
{
if (e.Attribute(name) != null)
{
return true;
}
e = e.Parent;
}
return false;
}
}
internal struct XPathEvaluator
{
public object Evaluate<T>(XNode node, string expression, IXmlNamespaceResolver resolver) where T : class
{
XPathNavigator navigator = node.CreateNavigator();
object result = navigator.Evaluate(expression, resolver);
XPathNodeIterator iterator = result as XPathNodeIterator;
if (iterator != null)
{
return EvaluateIterator<T>(iterator);
}
if (!(result is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, result.GetType()));
return (T)result;
}
private IEnumerable<T> EvaluateIterator<T>(XPathNodeIterator result)
{
foreach (XPathNavigator navigator in result)
{
object r = navigator.UnderlyingObject;
if (!(r is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, r.GetType()));
yield return (T)r;
XText t = r as XText;
if (t != null && t.GetParent() != null)
{
foreach (XNode node in t.GetParent().Nodes())
{
t = node as XText;
if (t == null) break;
yield return (T)(object)t;
}
}
}
}
}
/// <summary>
/// Extension methods
/// </summary>
public static class Extensions
{
/// <summary>
/// Creates an <see cref="XPathNavigator"/> for a given <see cref="XNode"/>
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <returns>An <see cref="XPathNavigator"/></returns>
public static XPathNavigator CreateNavigator(this XNode node)
{
return node.CreateNavigator(null);
}
/// <summary>
/// Creates an <see cref="XPathNavigator"/> for a given <see cref="XNode"/>
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="nameTable">The <see cref="XmlNameTable"/> to be used by
/// the <see cref="XPathNavigator"/></param>
/// <returns>An <see cref="XPathNavigator"/></returns>
public static XPathNavigator CreateNavigator(this XNode node, XmlNameTable nameTable)
{
if (node == null) throw new ArgumentNullException(nameof(node));
if (node is XDocumentType) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.DocumentType));
XText text = node as XText;
if (text != null)
{
if (text.GetParent() is XDocument) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.Whitespace));
node = CalibrateText(text);
}
return new XNodeNavigator(node, nameTable);
}
/// <summary>
/// Evaluates an XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <returns>The result of evaluating the expression which can be typed as bool, double, string or
/// IEnumerable</returns>
public static object XPathEvaluate(this XNode node, string expression)
{
return node.XPathEvaluate(expression, null);
}
/// <summary>
/// Evaluates an XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <param name="resolver">A <see cref="IXmlNamespaceResolver"> for the namespace
/// prefixes used in the XPath expression</see></param>
/// <returns>The result of evaluating the expression which can be typed as bool, double, string or
/// IEnumerable</returns>
public static object XPathEvaluate(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
if (node == null) throw new ArgumentNullException(nameof(node));
return new XPathEvaluator().Evaluate<object>(node, expression, resolver);
}
/// <summary>
/// Select an <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <returns>An <see cref="XElement"> or null</see></returns>
public static XElement XPathSelectElement(this XNode node, string expression)
{
return node.XPathSelectElement(expression, null);
}
/// <summary>
/// Select an <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <param name="resolver">A <see cref="IXmlNamespaceResolver"/> for the namespace
/// prefixes used in the XPath expression</param>
/// <returns>An <see cref="XElement"> or null</see></returns>
public static XElement XPathSelectElement(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
return node.XPathSelectElements(expression, resolver).FirstOrDefault();
}
/// <summary>
/// Select a set of <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <returns>An <see cref="IEnumerable<XElement>"/> corresponding to the resulting set of elements</returns>
public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression)
{
return node.XPathSelectElements(expression, null);
}
/// <summary>
/// Select a set of <see cref="XElement"/> using a XPath expression
/// </summary>
/// <param name="node">Extension point <see cref="XNode"/></param>
/// <param name="expression">The XPath expression</param>
/// <param name="resolver">A <see cref="IXmlNamespaceResolver"/> for the namespace
/// prefixes used in the XPath expression</param>
/// <returns>An <see cref="IEnumerable<XElement>"/> corresponding to the resulting set of elements</returns>
public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression, IXmlNamespaceResolver resolver)
{
if (node == null) throw new ArgumentNullException(nameof(node));
return (IEnumerable<XElement>)new XPathEvaluator().Evaluate<XElement>(node, expression, resolver);
}
private static XText CalibrateText(XText n)
{
XContainer parentNode = n.GetParent();
if (parentNode == null)
{
return n;
}
foreach (XNode node in parentNode.Nodes())
{
XText t = node as XText;
bool isTextNode = t != null;
if (isTextNode && node == n)
{
return t;
}
}
System.Diagnostics.Debug.Fail("Parent node doesn't contain itself.");
return null;
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System.Collections;
using System.Collections.Generic;
namespace IronPython.Runtime {
public class ListGenericWrapper<T> : IList<T> {
private IList<object> _value;
public ListGenericWrapper(IList<object> value) { this._value = value; }
#region IList<T> Members
public int IndexOf(T item) {
return _value.IndexOf(item);
}
public void Insert(int index, T item) {
_value.Insert(index, item);
}
public void RemoveAt(int index) {
_value.RemoveAt(index);
}
public T this[int index] {
get {
return (T)_value[index];
}
set {
this._value[index] = value;
}
}
#endregion
#region ICollection<T> Members
public void Add(T item) {
_value.Add(item);
}
public void Clear() {
_value.Clear();
}
public bool Contains(T item) {
return _value.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex) {
for (int i = 0; i < _value.Count; i++) {
array[arrayIndex + i] = (T)_value[i];
}
}
public int Count {
get { return _value.Count; }
}
public bool IsReadOnly {
get { return _value.IsReadOnly; }
}
public bool Remove(T item) {
return _value.Remove(item);
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator() {
return new IEnumeratorOfTWrapper<T>(_value.GetEnumerator());
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
return _value.GetEnumerator();
}
#endregion
}
public class DictionaryGenericWrapper<K, V> : IDictionary<K, V> {
private IDictionary<object, object> self;
public DictionaryGenericWrapper(IDictionary<object, object> self) {
this.self = self;
}
#region IDictionary<K,V> Members
public void Add(K key, V value) {
self.Add(key, value);
}
public bool ContainsKey(K key) {
return self.ContainsKey(key);
}
public ICollection<K> Keys {
get {
List<K> res = new List<K>();
foreach (object o in self.Keys) {
res.Add((K)o);
}
return res;
}
}
public bool Remove(K key) {
return self.Remove(key);
}
public bool TryGetValue(K key, out V value) {
object outValue;
if (self.TryGetValue(key, out outValue)) {
value = (V)outValue;
return true;
}
value = default(V);
return false;
}
public ICollection<V> Values {
get {
List<V> res = new List<V>();
foreach (object o in self.Values) {
res.Add((V)o);
}
return res;
}
}
public V this[K key] {
get {
return (V)self[key];
}
set {
self[key] = value;
}
}
#endregion
#region ICollection<KeyValuePair<K,V>> Members
public void Add(KeyValuePair<K, V> item) {
self.Add(new KeyValuePair<object, object>(item.Key, item.Value));
}
public void Clear() {
self.Clear();
}
public bool Contains(KeyValuePair<K, V> item) {
return self.Contains(new KeyValuePair<object, object>(item.Key, item.Value));
}
public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex) {
foreach (KeyValuePair<K, V> kvp in this) {
array[arrayIndex++] = kvp;
}
}
public int Count {
get { return self.Count; }
}
public bool IsReadOnly {
get { return self.IsReadOnly; }
}
public bool Remove(KeyValuePair<K, V> item) {
return self.Remove(new KeyValuePair<object, object>(item.Key, item.Value));
}
#endregion
#region IEnumerable<KeyValuePair<K,V>> Members
public IEnumerator<KeyValuePair<K, V>> GetEnumerator() {
foreach (KeyValuePair<object, object> kv in self) {
yield return new KeyValuePair<K, V>((K)kv.Key, (V)kv.Value);
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
return self.GetEnumerator();
}
#endregion
}
public class IEnumeratorOfTWrapper<T> : IEnumerator<T> {
IEnumerator enumerable;
public IEnumeratorOfTWrapper(IEnumerator enumerable) {
this.enumerable = enumerable;
}
#region IEnumerator<T> Members
public T Current
{
get
{
try
{
return (T)enumerable.Current;
}
catch (System.InvalidCastException iex)
{
throw new System.InvalidCastException(string.Format("Error in IEnumeratorOfTWrapper.Current. Could not cast: {0} in {0}", typeof(T).ToString(), enumerable.Current.GetType().ToString()), iex);
}
}
}
#endregion
#region IDisposable Members
public void Dispose() {
}
#endregion
#region IEnumerator Members
object IEnumerator.Current {
get { return enumerable.Current; }
}
public bool MoveNext() {
return enumerable.MoveNext();
}
public void Reset() {
enumerable.Reset();
}
#endregion
}
[PythonType("enumerable_wrapper")]
public class IEnumerableOfTWrapper<T> : IEnumerable<T>, IEnumerable {
IEnumerable enumerable;
public IEnumerableOfTWrapper(IEnumerable enumerable) {
this.enumerable = enumerable;
}
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator() {
return new IEnumeratorOfTWrapper<T>(enumerable.GetEnumerator());
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
#endregion
}
}
| |
//
// Copyright 2012 Hakan Kjellerstrand
//
// 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;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Google.OrTools.ConstraintSolver;
public class DiscreteTomography
{
// default problem
static int[] default_rowsums = { 0, 0, 8, 2, 6, 4, 5, 3, 7, 0, 0 };
static int[] default_colsums = { 0, 0, 7, 1, 6, 3, 4, 5, 2, 7, 0, 0 };
static int[] rowsums2;
static int[] colsums2;
/**
*
* Discrete tomography
*
* Problem from http://eclipse.crosscoreop.com/examples/tomo.ecl.txt
* """
* This is a little 'tomography' problem, taken from an old issue
* of Scientific American.
*
* A matrix which contains zeroes and ones gets "x-rayed" vertically and
* horizontally, giving the total number of ones in each row and column.
* The problem is to reconstruct the contents of the matrix from this
* information. Sample run:
*
* ?- go.
* 0 0 7 1 6 3 4 5 2 7 0 0
* 0
* 0
* 8 * * * * * * * *
* 2 * *
* 6 * * * * * *
* 4 * * * *
* 5 * * * * *
* 3 * * *
* 7 * * * * * * *
* 0
* 0
*
* Eclipse solution by Joachim Schimpf, IC-Parc
* """
*
* See http://www.hakank.org/or-tools/discrete_tomography.py
*
*/
private static void Solve(int[] rowsums, int[] colsums)
{
Solver solver = new Solver("DiscreteTomography");
//
// Data
//
int r = rowsums.Length;
int c = colsums.Length;
Console.Write("rowsums: ");
for (int i = 0; i < r; i++)
{
Console.Write(rowsums[i] + " ");
}
Console.Write("\ncolsums: ");
for (int j = 0; j < c; j++)
{
Console.Write(colsums[j] + " ");
}
Console.WriteLine("\n");
//
// Decision variables
//
IntVar[,] x = solver.MakeIntVarMatrix(r, c, 0, 1, "x");
IntVar[] x_flat = x.Flatten();
//
// Constraints
//
// row sums
for (int i = 0; i < r; i++)
{
var tmp = from j in Enumerable.Range(0, c) select x[i, j];
solver.Add(tmp.ToArray().Sum() == rowsums[i]);
}
// cols sums
for (int j = 0; j < c; j++)
{
var tmp = from i in Enumerable.Range(0, r) select x[i, j];
solver.Add(tmp.ToArray().Sum() == colsums[j]);
}
//
// Search
//
DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);
solver.NewSearch(db);
while (solver.NextSolution())
{
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
Console.Write("{0} ", x[i, j].Value() == 1 ? "#" : ".");
}
Console.WriteLine();
}
Console.WriteLine();
}
Console.WriteLine("\nSolutions: {0}", solver.Solutions());
Console.WriteLine("WallTime: {0}ms", solver.WallTime());
Console.WriteLine("Failures: {0}", solver.Failures());
Console.WriteLine("Branches: {0} ", solver.Branches());
solver.EndSearch();
}
/**
*
* Reads a discrete tomography file.
* File format:
* # a comment which is ignored
* % a comment which also is ignored
* rowsums separated by [,\s]
* colsums separated by [,\s]
*
* e.g.
* """
* 0,0,8,2,6,4,5,3,7,0,0
* 0,0,7,1,6,3,4,5,2,7,0,0
* # comment
* % another comment
* """
*
*/
private static void readFile(String file)
{
Console.WriteLine("readFile(" + file + ")");
TextReader inr = new StreamReader(file);
String str;
int lineCount = 0;
while ((str = inr.ReadLine()) != null && str.Length > 0)
{
str = str.Trim();
// ignore comments
if (str.StartsWith("#") || str.StartsWith("%"))
{
continue;
}
if (lineCount == 0)
{
rowsums2 = ConvLine(str);
}
else if (lineCount == 1)
{
colsums2 = ConvLine(str);
break;
}
lineCount++;
} // end while
inr.Close();
} // end readFile
private static int[] ConvLine(String str)
{
String[] tmp = Regex.Split(str, "[,\\s]+");
int len = tmp.Length;
int[] sums = new int[len];
for (int i = 0; i < len; i++)
{
sums[i] = Convert.ToInt32(tmp[i]);
}
return sums;
}
public static void Main(String[] args)
{
if (args.Length > 0)
{
readFile(args[0]);
Solve(rowsums2, colsums2);
}
else
{
Solve(default_rowsums, default_colsums);
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.Config.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.Config.Api.Tests
{
public class KanbanTests
{
public static KanbanController Fixture()
{
KanbanController controller = new KanbanController(new KanbanRepository());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.Config.Entities.Kanban kanban = Fixture().Get(0);
Assert.NotNull(kanban);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.Config.Entities.Kanban kanban = Fixture().GetFirst();
Assert.NotNull(kanban);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.Config.Entities.Kanban kanban = Fixture().GetPrevious(0);
Assert.NotNull(kanban);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.Config.Entities.Kanban kanban = Fixture().GetNext(0);
Assert.NotNull(kanban);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.Config.Entities.Kanban kanban = Fixture().GetLast();
Assert.NotNull(kanban);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.Config.Entities.Kanban> kanbans = Fixture().Get(new long[] { });
Assert.NotNull(kanbans);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(0, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(0);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
//
// SecKeychain.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013 Jeffrey Stedfast
//
// 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.IO;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Pkcs;
using MimeKit.Cryptography;
namespace MimeKit.MacInterop {
class SecKeychain : CFObject
{
const string SecurityLibrary = "/System/Library/Frameworks/Security.framework/Security";
/// <summary>
/// The default login keychain.
/// </summary>
public static readonly SecKeychain Default = GetDefault ();
bool disposed;
SecKeychain (IntPtr handle, bool owns) : base (handle, owns)
{
}
SecKeychain (IntPtr handle) : base (handle, false)
{
}
#region Managing Certificates
[DllImport (SecurityLibrary)]
static extern OSStatus SecCertificateAddToKeychain (IntPtr certificate, IntPtr keychain);
[DllImport (SecurityLibrary)]
static extern IntPtr SecCertificateCreateWithData (IntPtr allocator, IntPtr data);
[DllImport (SecurityLibrary)]
static extern IntPtr SecCertificateCopyData (IntPtr certificate);
[DllImport (SecurityLibrary)]
static extern OSStatus SecCertificateCopyCommonName (IntPtr certificate, out IntPtr commonName);
[DllImport (SecurityLibrary)]
static extern OSStatus SecPKCS12Import (IntPtr pkcs12DataRef, IntPtr options, ref IntPtr items);
#endregion
#region Managing Identities
[DllImport (SecurityLibrary)]
static extern OSStatus SecIdentityCopyCertificate (IntPtr identityRef, out IntPtr certificateRef);
[DllImport (SecurityLibrary)]
static extern OSStatus SecIdentityCopyPrivateKey (IntPtr identityRef, out IntPtr privateKeyRef);
// WARNING: deprecated in Mac OS X 10.7
[DllImport (SecurityLibrary)]
static extern OSStatus SecIdentitySearchCreate (IntPtr keychainOrArray, CssmKeyUse keyUsage, out IntPtr searchRef);
// WARNING: deprecated in Mac OS X 10.7
[DllImport (SecurityLibrary)]
static extern OSStatus SecIdentitySearchCopyNext (IntPtr searchRef, out IntPtr identity);
// Note: SecIdentitySearch* has been replaced with SecItemCopyMatching
//[DllImport (SecurityLib)]
//OSStatus SecItemCopyMatching (CFDictionaryRef query, CFTypeRef *result);
[DllImport (SecurityLibrary)]
static extern OSStatus SecItemImport (IntPtr importedData, IntPtr fileName, ref SecExternalFormat format, IntPtr type, SecItemImportExportFlags flags, IntPtr keyParams, IntPtr keychain, ref IntPtr items);
[DllImport (SecurityLibrary)]
static extern OSStatus SecItemExport (IntPtr itemRef, SecExternalFormat format, SecItemImportExportFlags flags, IntPtr keyParams, out IntPtr exportedData);
#endregion
#region Getting Information About Security Result Codes
[DllImport (SecurityLibrary)]
static extern IntPtr SecCopyErrorMessageString (OSStatus status, IntPtr reserved);
#endregion
#region Managing Keychains
[DllImport (SecurityLibrary)]
static extern OSStatus SecKeychainCopyDefault (ref IntPtr keychain);
[DllImport (SecurityLibrary)]
static extern OSStatus SecKeychainCreate (string path, uint passwordLength, byte[] password, bool promptUser, IntPtr initialAccess, ref IntPtr keychain);
[DllImport (SecurityLibrary)]
static extern OSStatus SecKeychainOpen (string path, ref IntPtr keychain);
[DllImport (SecurityLibrary)]
static extern OSStatus SecKeychainDelete (IntPtr keychain);
static SecKeychain GetDefault ()
{
IntPtr handle = IntPtr.Zero;
if (SecKeychainCopyDefault (ref handle) == OSStatus.Ok)
return new SecKeychain (handle, true);
return null;
}
/// <summary>
/// Create a keychain at the specified path with the specified password.
/// </summary>
/// <param name="path">The path to the keychain.</param>
/// <param name="password">The password for unlocking the keychain.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="path"/> was <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="password"/> was <c>null</c>.</para>
/// </exception>
/// <exception cref="System.Exception">
/// An unknown error creating the keychain occurred.
/// </exception>
public static SecKeychain Create (string path, string password)
{
if (path == null)
throw new ArgumentNullException ("path");
if (password == null)
throw new ArgumentNullException ("password");
var passwd = Encoding.UTF8.GetBytes (password);
var handle = IntPtr.Zero;
var status = SecKeychainCreate (path, (uint) passwd.Length, passwd, false, IntPtr.Zero, ref handle);
if (status != OSStatus.Ok)
throw new Exception (GetError (status));
return new SecKeychain (handle);
}
/// <summary>
/// Opens the keychain at the specified path.
/// </summary>
/// <param name="path">The path to the keychain.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="path"/> was <c>null</c>.
/// </exception>
/// <exception cref="System.Exception">
/// An unknown error opening the keychain occurred.
/// </exception>
public static SecKeychain Open (string path)
{
if (path == null)
throw new ArgumentNullException ("path");
var handle = IntPtr.Zero;
var status = SecKeychainOpen (path, ref handle);
if (status != OSStatus.Ok)
throw new Exception (GetError (status));
return new SecKeychain (handle);
}
/// <summary>
/// Deletes the specified keychain.
/// </summary>
/// <param name="keychain">Keychain.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="keychain"/> was <c>null</c>.
/// </exception>
/// <exception cref="System.ObjectDisposedException">
/// <paramref name="keychain"/> has been disposed.
/// </exception>
/// <exception cref="System.Exception">
/// An unknown error deleting the keychain occurred.
/// </exception>
public static void Delete (SecKeychain keychain)
{
if (keychain == null)
throw new ArgumentNullException ("keychain");
if (keychain.disposed)
throw new ObjectDisposedException ("SecKeychain");
if (keychain.Handle == IntPtr.Zero)
throw new InvalidOperationException ();
var status = SecKeychainDelete (keychain.Handle);
if (status != OSStatus.Ok)
throw new Exception (GetError (status));
keychain.Dispose ();
}
#endregion
#region Searching for Keychain Items
[DllImport (SecurityLibrary)]
static extern unsafe OSStatus SecKeychainSearchCreateFromAttributes (IntPtr keychainOrArray, SecItemClass itemClass, SecKeychainAttributeList *attrList, out IntPtr searchRef);
[DllImport (SecurityLibrary)]
static extern OSStatus SecKeychainSearchCopyNext (IntPtr searchRef, out IntPtr itemRef);
#endregion
#region Creating and Deleting Keychain Items
[DllImport (SecurityLibrary)]
static extern unsafe OSStatus SecKeychainItemCreateFromContent (SecItemClass itemClass, SecKeychainAttributeList *attrList,
uint passwordLength, byte[] password, IntPtr keychain,
IntPtr initialAccess, ref IntPtr itemRef);
[DllImport (SecurityLibrary)]
static extern OSStatus SecKeychainItemDelete (IntPtr itemRef);
#endregion
#region Managing Keychain Items
[DllImport (SecurityLibrary)]
static extern unsafe OSStatus SecKeychainItemModifyAttributesAndData (IntPtr itemRef, SecKeychainAttributeList *attrList, uint length, byte [] data);
[DllImport (SecurityLibrary)]
static extern OSStatus SecKeychainItemCopyContent (IntPtr itemRef, ref SecItemClass itemClass, IntPtr attrList, ref uint length, ref IntPtr data);
[DllImport (SecurityLibrary)]
static extern OSStatus SecKeychainItemFreeContent (IntPtr attrList, IntPtr data);
#endregion
static string GetError (OSStatus status)
{
CFString str = null;
try {
str = new CFString (SecCopyErrorMessageString (status, IntPtr.Zero), true);
return str.ToString ();
} catch {
return status.ToString ();
} finally {
if (str != null)
str.Dispose ();
}
}
/// <summary>
/// Gets a list of all certificates suitable for the given key usage.
/// </summary>
/// <returns>The matching certificates.</returns>
/// <param name="keyUsage">The key usage.</param>
/// <exception cref="System.ObjectDisposedException">
/// The keychain has been disposed.
/// </exception>
public IList<X509Certificate> GetCertificates (CssmKeyUse keyUsage)
{
if (disposed)
throw new ObjectDisposedException ("SecKeychain");
var parser = new X509CertificateParser ();
var certs = new List<X509Certificate> ();
IntPtr searchRef, itemRef, certRef;
OSStatus status;
status = SecIdentitySearchCreate (Handle, keyUsage, out searchRef);
if (status != OSStatus.Ok)
return certs;
while (SecIdentitySearchCopyNext (searchRef, out itemRef) == OSStatus.Ok) {
if (SecIdentityCopyCertificate (itemRef, out certRef) == OSStatus.Ok) {
using (var data = new CFData (SecCertificateCopyData (certRef), true)) {
var rawData = data.GetBuffer ();
try {
certs.Add (parser.ReadCertificate (rawData));
} catch (CertificateException ex) {
Debug.WriteLine ("Failed to parse X509 certificate from keychain: {0}", ex);
}
}
}
CFRelease (itemRef);
}
CFRelease (searchRef);
return certs;
}
public IList<CmsSigner> GetAllCmsSigners ()
{
if (disposed)
throw new ObjectDisposedException ("SecKeychain");
var signers = new List<CmsSigner> ();
IntPtr searchRef, itemRef, dataRef;
OSStatus status;
status = SecIdentitySearchCreate (Handle, CssmKeyUse.Sign, out searchRef);
if (status != OSStatus.Ok)
return signers;
while (SecIdentitySearchCopyNext (searchRef, out itemRef) == OSStatus.Ok) {
if (SecItemExport (itemRef, SecExternalFormat.PKCS12, SecItemImportExportFlags.None, IntPtr.Zero, out dataRef) == OSStatus.Ok) {
var data = new CFData (dataRef, true);
var rawData = data.GetBuffer ();
data.Dispose ();
try {
using (var memory = new MemoryStream (rawData, false)) {
var pkcs12 = new Pkcs12Store (memory, new char[0]);
foreach (string alias in pkcs12.Aliases) {
if (!pkcs12.IsKeyEntry (alias))
continue;
var chain = pkcs12.GetCertificateChain (alias);
var entry = pkcs12.GetKey (alias);
signers.Add (new CmsSigner (chain, entry.Key));
}
}
} catch (Exception ex) {
Debug.WriteLine ("Failed to decode keychain pkcs12 data: {0}", ex);
}
}
CFRelease (itemRef);
}
CFRelease (searchRef);
return signers;
}
public bool Add (AsymmetricKeyParameter key)
{
// FIXME: how do we convert an AsymmetricKeyParameter into something usable by MacOS?
throw new NotImplementedException ();
}
public bool Add (X509Certificate certificate)
{
using (var cert = SecCertificate.Create (certificate.GetEncoded ())) {
var status = SecCertificateAddToKeychain (cert.Handle, Handle);
return status == OSStatus.Ok || status == OSStatus.DuplicateItem;
}
}
public unsafe bool Contains (X509Certificate certificate)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
if (disposed)
throw new ObjectDisposedException ("SecKeychain");
// Note: we don't have to use an alias attribute, it's just that it might be faster to use it (fewer certificates we have to compare raw data for)
byte[] alias = Encoding.UTF8.GetBytes (certificate.GetCommonName ());
IntPtr searchRef, itemRef;
bool found = false;
byte[] certData;
OSStatus status;
fixed (byte* aliasPtr = alias) {
SecKeychainAttribute* attrs = stackalloc SecKeychainAttribute [1];
int n = 0;
if (alias != null)
attrs[n++] = new SecKeychainAttribute (SecItemAttr.Alias, (uint) alias.Length, (IntPtr) aliasPtr);
SecKeychainAttributeList attrList = new SecKeychainAttributeList (n, (IntPtr) attrs);
status = SecKeychainSearchCreateFromAttributes (Handle, SecItemClass.Certificate, &attrList, out searchRef);
if (status != OSStatus.Ok)
throw new Exception ("Could not enumerate certificates from the keychain. Error:\n" + GetError (status));
certData = certificate.GetEncoded ();
while (!found && SecKeychainSearchCopyNext (searchRef, out itemRef) == OSStatus.Ok) {
SecItemClass itemClass = 0;
IntPtr data = IntPtr.Zero;
uint length = 0;
status = SecKeychainItemCopyContent (itemRef, ref itemClass, IntPtr.Zero, ref length, ref data);
if (status == OSStatus.Ok) {
if (certData.Length == (int) length) {
byte[] rawData = new byte[(int) length];
Marshal.Copy (data, rawData, 0, (int) length);
found = true;
for (int i = 0; i < rawData.Length; i++) {
if (rawData[i] != certData[i]) {
found = false;
break;
}
}
}
SecKeychainItemFreeContent (IntPtr.Zero, data);
}
CFRelease (itemRef);
}
CFRelease (searchRef);
}
return found;
}
// public void ImportPkcs12 (byte[] rawData, string password)
// {
// if (rawData == null)
// throw new ArgumentNullException ("rawData");
//
// if (password == null)
// throw new ArgumentNullException ("password");
//
// if (disposed)
// throw new ObjectDisposedException ("SecKeychain");
//
// using (var data = new CFData (rawData)) {
// var options = IntPtr.Zero;
// var items = IntPtr.Zero;
//
// var status = SecPKCS12Import (data.Handle, options, ref items);
// CFRelease (options);
// CFRelease (items);
// }
// }
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
disposed = true;
}
}
}
| |
//
// System.Collections.CollectionBase
// Test suite for System.Collections.CollectionBase
//
// Authors:
// Nick D. Drochak II
// Gonzalo Paniagua Javier ([email protected])
//
// (C) 2001 Nick D. Drochak II
// (c) 2003 Ximian, Inc. (http://www.ximian.com)
//
using System;
using System.Collections;
using NUnit.Framework;
namespace MonoTests.System.Collections
{
[TestFixture]
public class CollectionBaseTest : Assertion
{
// We need a concrete class to test the abstract base class
public class ConcreteCollection : CollectionBase
{
// These fields are used as markers to test the On* hooks.
public bool onClearFired;
public bool onClearCompleteFired;
public bool onInsertFired;
public int onInsertIndex;
public bool onInsertCompleteFired;
public int onInsertCompleteIndex;
public bool onRemoveFired;
public int onRemoveIndex;
public bool onRemoveCompleteFired;
public int onRemoveCompleteIndex;
public bool onSetFired;
public int onSetOldValue;
public int onSetNewValue;
public bool onSetCompleteFired;
public int onSetCompleteOldValue;
public int onSetCompleteNewValue;
public int mustThrowException;
public bool onValidateFired;
// This constructor is used to test OnValid()
public ConcreteCollection()
{
IList listObj;
listObj = this;
listObj.Add(null);
}
// This constructor puts consecutive integers into the list
public ConcreteCollection(int i) {
IList listObj;
listObj = this;
int j;
for (j = 0; j< i; j++) {
listObj.Add(j);
}
}
void CheckIfThrow ()
{
if (mustThrowException > 0) {
mustThrowException--;
if (mustThrowException == 0)
throw new Exception ();
}
}
// A helper method to look at a value in the list at a specific index
public int PeekAt(int index)
{
IList listObj;
listObj = this;
return (int) listObj[index];
}
protected override void OnValidate (object value) {
this.onValidateFired = true;
CheckIfThrow ();
base.OnValidate (value);
}
// Mark the flag if this hook is fired
protected override void OnClear() {
this.onClearFired = true;
CheckIfThrow ();
}
// Mark the flag if this hook is fired
protected override void OnClearComplete()
{
this.onClearCompleteFired = true;
CheckIfThrow ();
}
// Mark the flag, and save the paramter if this hook is fired
protected override void OnInsert(int index, object value)
{
this.onInsertFired = true;
this.onInsertIndex = index;
CheckIfThrow ();
}
// Mark the flag, and save the paramter if this hook is fired
protected override void OnInsertComplete(int index, object value)
{
this.onInsertCompleteFired = true;
this.onInsertCompleteIndex = index;
CheckIfThrow ();
}
// Mark the flag, and save the paramter if this hook is fired
protected override void OnRemove(int index, object value)
{
this.onRemoveFired = true;
this.onRemoveIndex = index;
CheckIfThrow ();
}
// Mark the flag, and save the paramter if this hook is fired
protected override void OnRemoveComplete(int index, object value)
{
this.onRemoveCompleteFired = true;
this.onRemoveCompleteIndex = index;
CheckIfThrow ();
}
// Mark the flag, and save the paramters if this hook is fired
protected override void OnSet(int index, object oldValue, object newValue)
{
this.onSetFired = true;
this.onSetOldValue = (int) oldValue;
this.onSetNewValue = (int) newValue;
CheckIfThrow ();
}
// Mark the flag, and save the paramters if this hook is fired
protected override void OnSetComplete(int index, object oldValue, object newValue)
{
this.onSetCompleteFired = true;
this.onSetCompleteOldValue = (int) oldValue;
this.onSetCompleteNewValue = (int) newValue;
CheckIfThrow ();
}
public IList BaseList {
get { return base.List; }
}
} // public class ConcreteCollection
// Check the count property
[Test]
public void Count() {
ConcreteCollection myCollection;
myCollection = new ConcreteCollection(4);
Assert(4 == myCollection.Count);
}
// Make sure GetEnumerator returns an object
[Test]
public void GetEnumerator() {
ConcreteCollection myCollection;
myCollection = new ConcreteCollection(4);
Assert(null != myCollection.GetEnumerator());
}
// OnValid disallows nulls
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void OnValid() {
ConcreteCollection myCollection;
myCollection = new ConcreteCollection();
}
// Test various Insert paths
[Test]
public void Insert() {
ConcreteCollection myCollection;
int numberOfItems;
numberOfItems = 3;
// The constructor inserts
myCollection = new ConcreteCollection(numberOfItems);
Assert(myCollection.onInsertFired);
Assert(myCollection.onInsertCompleteFired);
// Using the IList interface, check inserts in the middle
IList listObj = myCollection;
listObj.Insert(1, 9);
Assert(myCollection.onInsertIndex == 1);
Assert(myCollection.onInsertCompleteIndex == 1);
Assert(myCollection.PeekAt(1) == 9);
}
// Test Clear and it's hooks
[Test]
public void Clear()
{
ConcreteCollection myCollection;
int numberOfItems;
numberOfItems = 1;
myCollection = new ConcreteCollection(numberOfItems);
myCollection.Clear();
Assert(myCollection.Count == 0);
Assert(myCollection.onClearFired);
Assert(myCollection.onClearCompleteFired);
}
// Test RemoveAt, other removes and the hooks
[Test]
public void Remove()
{
ConcreteCollection myCollection;
int numberOfItems;
numberOfItems = 3;
// Set up a test collection
myCollection = new ConcreteCollection(numberOfItems);
// The list is 0-based. So if we remove the second one
myCollection.RemoveAt(1);
// We should see the original third one in it's place
Assert(myCollection.PeekAt(1) == 2);
Assert(myCollection.onRemoveFired);
Assert(myCollection.onRemoveIndex == 1);
Assert(myCollection.onRemoveCompleteFired);
Assert(myCollection.onRemoveCompleteIndex == 1);
IList listObj = myCollection;
listObj.Remove(0);
// Confirm parameters are being passed to the hooks
Assert(myCollection.onRemoveIndex == 0);
Assert(myCollection.onRemoveCompleteIndex == 0);
}
// Test the random access feature
[Test]
public void Set()
{
ConcreteCollection myCollection;
int numberOfItems;
numberOfItems = 3;
myCollection = new ConcreteCollection(numberOfItems);
IList listObj = myCollection;
listObj[0] = 99;
Assert((int) listObj[0] == 99);
Assert(myCollection.onSetFired);
Assert(myCollection.onSetCompleteFired);
Assert(myCollection.onSetOldValue == 0);
Assert(myCollection.onSetCompleteOldValue == 0);
Assert(myCollection.onSetNewValue == 99);
Assert(myCollection.onSetCompleteNewValue == 99);
}
[Test]
public void InsertComplete_Add ()
{
ConcreteCollection coll = new ConcreteCollection (0);
coll.mustThrowException = 1;
try {
coll.BaseList.Add (0);
} catch {
}
AssertEquals (0, coll.Count);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void ValidateCalled ()
{
ConcreteCollection coll = new ConcreteCollection (0);
coll.mustThrowException = 1;
try {
coll.BaseList [5] = 8888;
} catch (ArgumentOutOfRangeException) {
throw;
} finally {
AssertEquals (false, coll.onValidateFired);
}
}
[Test]
public void SetCompleteCalled ()
{
ConcreteCollection coll = new ConcreteCollection (0);
coll.BaseList.Add (88);
coll.mustThrowException = 1;
try {
coll.BaseList [0] = 11;
} catch {
} finally {
AssertEquals (false, coll.onSetCompleteFired);
}
}
[Test]
public void SetCompleteUndo ()
{
ConcreteCollection coll = new ConcreteCollection (0);
bool throwsException = true;
coll.BaseList.Add (88);
coll.onValidateFired = false;
coll.onInsertFired = false;
coll.onSetCompleteFired = false;
coll.mustThrowException = 3;
try {
coll.BaseList [0] = 11;
throwsException = false;
} catch {
} finally {
Assert (throwsException);
Assert (coll.onValidateFired);
Assert (coll.onSetFired);
Assert (coll.onSetCompleteFired);
AssertEquals (88, coll.BaseList [0]);
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void InvalidRemove ()
{
ConcreteCollection coll = new ConcreteCollection (0);
coll.BaseList.Remove (10);
}
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Xml;
using System.Windows;
using System.Windows.Controls;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace ESRI.ArcLogistics.App.Controls
{
/// <summary>
/// Composition Type
/// </summary>
internal enum CompositionType
{
Terminal,
Horizontal,
Vertical
}
/// <summary>
/// Composition class
/// </summary>
internal class Composition : ILayoutSerializable
{
#region Constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Create composition
/// </summary>
/// <remarks>Used only for Deserialize</remarks>
public Composition()
{
_type = CompositionType.Terminal;
_isInited = false;
}
public Composition(Composition parent, DockablePane pane)
{
_attachedPane = pane;
_type = CompositionType.Terminal;
_isInited = true;
}
public Composition(Composition parent, Composition first, Composition second, Dock dockType)
{
_CreateLineComposition(first, second, dockType);
_isInited = true;
}
#endregion // Constructors
#region Public properties
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Type of composition.
/// </summary>
public CompositionType Type
{
get { return _type; }
}
/// <summary>
/// Composition children read-only collection.
/// </summary>
/// <remarks>Actual only for CompositionType.Horizontal or CompositionType.Vertical</remarks>
public ICollection<Composition> Children
{
get
{
Debug.Assert(CompositionType.Terminal != _type);
return _children.AsReadOnly();
}
}
/// <summary>
/// Attached pane
/// </summary>
/// <remarks>Actual only for CompositionType.Terminal</remarks>
public DockablePane AttachedPane
{
get
{
Debug.Assert(CompositionType.Terminal == _type);
return _attachedPane;
}
}
/// <summary>
/// Space arrange factor
/// </summary>
public double SpaceFactor
{
get { return _spaceFactor; }
set { _spaceFactor = value; }
}
/// <summary>
/// Is object initialized
/// </summary>
public bool IsInited
{
get { return _isInited; }
}
#endregion // Public properties
#region Public methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public void AddSpec(DockablePane pane, Dock dockType)
{
if (!_isInited)
return;
if (CompositionType.Terminal == _type)
_Add(pane, dockType);
else
{
_CalculateSpaceFactors();
// find largest pane
Size maxSize = new Size(0, 0);
DockablePane largestPane = null;
_FindLargestPane(ref maxSize, ref largestPane);
if (null == largestPane)
_FindLastPane(ref largestPane);
Debug.Assert(null != largestPane);
bool isVertical = (maxSize.Width <= maxSize.Height);
Add(pane, largestPane, (isVertical) ? Dock.Bottom : Dock.Right);
}
}
public void Add(DockablePane pane, Dock dockType)
{
if (!_isInited)
return;
_CalculateSpaceFactors();
_Add(pane, dockType);
}
public void Add(DockablePane pane, DockablePane relativePane, Dock relativeDock)
{
if (!_isInited)
return;
_CalculateSpaceFactors();
if (CompositionType.Terminal == _type)
{
if (_attachedPane.Equals(relativePane))
_Add(pane, relativeDock);
}
else
{
// find relative terminal element index
int relativeIndex = -1;
for (int index = 0; index < _children.Count; ++index)
{
Composition currentComposition = _children[index];
if (CompositionType.Terminal == currentComposition.Type)
{
if (currentComposition.AttachedPane.Equals(relativePane))
{
relativeIndex = index;
break; // NOTE: founded
}
}
else
currentComposition.Add(pane, relativePane, relativeDock);
}
// add new item
if (-1 != relativeIndex)
{
if (_DoesAdding2Line(relativeDock))
{ // add new item to current linear composition
// left\top insert to relative position, other - insert after relive
Composition newComposition = new Composition(this, pane);
_children[relativeIndex].SpaceFactor *= DEFAULT_SPACE_FACTOR; // new child requared part of relative pane
newComposition.SpaceFactor = _children[relativeIndex].SpaceFactor;
int insertIndex = ((Dock.Left == relativeDock) || (Dock.Top == relativeDock)) ?
relativeIndex : relativeIndex + 1;
_children.Insert(insertIndex, newComposition);
}
else
{ // add new pane to terminal composition
_children[relativeIndex].Add(pane, relativeDock);
}
}
Debug.Assert(_IsNormalized());
}
}
/// <summary>
/// Remove pane
/// </summary>
public bool Remove(DockablePane pane)
{
if (!_isInited)
return false;
Debug.Assert(CompositionType.Terminal != _type);
_CalculateSpaceFactors();
bool isRemoved = false;
// find terminal element to deleting
Composition terminalComposition2Delete = null;
for (int index = 0; index < _children.Count; ++index)
{
Composition currentComposition = _children[index];
if (CompositionType.Terminal == currentComposition.Type)
{
if (currentComposition.AttachedPane.Equals(pane))
{
terminalComposition2Delete = currentComposition;
break; // NOTE: founded
}
}
else
{ // remove from child composition
if (currentComposition.Remove(pane))
{
isRemoved = true;
break;
}
}
}
// remove terminal element
if (null != terminalComposition2Delete)
{
_children.Remove(terminalComposition2Delete);
isRemoved = true;
if (1 == _children.Count)
{ // change state to terminal
Composition lastChield = _children[0];
_children.Clear();
if (CompositionType.Terminal == lastChield.Type)
{
_type = CompositionType.Terminal;
_attachedPane = lastChield.AttachedPane;
}
else
{
_type = lastChield.Type;
ICollection<Composition> children = lastChield.Children;
foreach (Composition child in children)
_children.Add(child);
}
}
else
{
// recalculate new space factors
Size sz = _CalculateSpaceSize();
double fullSize = (_type == CompositionType.Horizontal) ? sz.Height : sz.Width;
fullSize += SPLITTER_SIZE;
double splitterFree = SPLITTER_SIZE / _children.Count;
Size freeSize = terminalComposition2Delete._CalculateSpaceSize();
for (int index = 0; index < _children.Count; ++index)
{
Composition child = _children[index];
Size childSize = child._CalculateSpaceSize();
child.SpaceFactor = (_type == CompositionType.Horizontal) ?
((childSize.Height + freeSize.Height * child.SpaceFactor + splitterFree) / Math.Max(fullSize, 1)) :
((childSize.Width + freeSize.Width * child.SpaceFactor + splitterFree) / Math.Max(fullSize, 1));
}
}
}
else if (isRemoved)
{ // normalize composition - if child presented as one line
for (int index = 0; index < _children.Count; ++index)
{
Composition currentChild = _children[index];
if (currentChild.Type == _type)
{
ICollection<Composition> children = currentChild.Children;
Debug.Assert(currentChild.Type != CompositionType.Terminal);
Debug.Assert(1 < currentChild.Children.Count);
Collection<Composition> fromRemoved = new Collection<Composition> ();
foreach (Composition child in children)
fromRemoved.Add(child);
_children.Remove(currentChild);
_children.InsertRange(index, fromRemoved);
}
}
_CalculateSpaceFactors();
}
Debug.Assert(_IsNormalized());
return isRemoved;
}
public Composition Find(DockablePane pane)
{
if (!_isInited)
return null;
Composition terminalComposition = null;
if (CompositionType.Terminal == _type)
{
if (_attachedPane.Equals(pane))
terminalComposition = this;
}
else
{
// find relative terminal element index
for (int index = 0; index < _children.Count; ++index)
{
Composition currentComposition = _children[index];
terminalComposition = currentComposition.Find(pane);
if (null != terminalComposition)
break;
}
}
return terminalComposition;
}
/// <summary>
/// Recalculate layout for this composition
/// </summary>
/// <param name="grid"></param>
public void Arrange(Grid grid)
{
Debug.Assert(CompositionType.Terminal != _type);
double value = 0;
if (_type == CompositionType.Horizontal)
_ArrangeHorizontal(grid, ref value);
else
_ArrangeVertical(grid, ref value);
}
#endregion // Public methods
#region ILayoutSerializable
/// <summary>
/// Serialize layout
/// </summary>
/// <param name="doc">Document to save</param>
/// <param name="nodeParent">Parent node</param>
public void Serialize(XmlDocument doc, XmlNode nodeParent)
{
XmlNode nodeChild = doc.CreateElement(ELEMENT_NAME_CHILD);
nodeChild.Attributes.Append(doc.CreateAttribute(ATTRIBUTE_NAME_TYPE));
nodeChild.Attributes[ATTRIBUTE_NAME_TYPE].Value = _type.ToString();
nodeChild.Attributes.Append(doc.CreateAttribute(ATTRIBUTE_NAME_SFACTOR));
nodeChild.Attributes[ATTRIBUTE_NAME_SFACTOR].Value = _spaceFactor.ToString(CultureInfo.GetCultureInfo(STORAGE_CULTURE));
if (_type == CompositionType.Terminal)
{
Debug.Assert(null != _attachedPane);
XmlNode nodeAttachedPane = doc.CreateElement(ELEMENT_NAME_DOCKPANE);
_attachedPane.Serialize(doc, nodeAttachedPane);
nodeChild.AppendChild(nodeAttachedPane);
}
else
{
_CalculateSpaceFactors();
XmlNode nodeChildGroups = doc.CreateElement(ELEMENT_NAME_CHILDGROUPS);
for (int index = 0; index < _children.Count; ++index)
_children[index].Serialize(doc, nodeChildGroups);
nodeChild.AppendChild(nodeChildGroups);
}
nodeParent.AppendChild(nodeChild);
}
/// <summary>
/// Deserialize layout
/// </summary>
/// <param name="manager">Dock manager for initing objects</param>
/// <param name="node">Node to parse</param>
/// <param name="handlerObject">Delegate used to get user defined dockable contents</param>
public void Deserialize(DockManager manager, XmlNode node, GetContentFromTypeString handlerObject)
{
_type = (CompositionType)Enum.Parse(typeof(CompositionType), node.Attributes[ATTRIBUTE_NAME_TYPE].Value);
_spaceFactor = double.Parse(node.Attributes[ATTRIBUTE_NAME_SFACTOR].Value, CultureInfo.GetCultureInfo(STORAGE_CULTURE));
if (_type == CompositionType.Terminal)
{
Debug.Assert(node.ChildNodes[0].Name == ELEMENT_NAME_DOCKPANE);
DockablePane pane = new DockablePane();
pane.Deserialize(manager, node.ChildNodes[0], handlerObject);
_attachedPane = pane;
if (pane.IsDragSupported)
manager.DragPaneServices.Register(pane);
}
else
{
Debug.Assert(node.ChildNodes[0].Name == ELEMENT_NAME_CHILDGROUPS);
foreach (XmlNode nodeChild in node.ChildNodes[0].ChildNodes)
{
Composition composition = new Composition();
composition.Deserialize(manager, nodeChild, handlerObject);
_children.Add(composition);
}
}
_isInited = true;
}
#endregion // ILayoutSerializable
#region Private helpers
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Calculate composition space size
/// </summary>
private Size _CalculateSpaceSize()
{
Size spaceSize = new Size(0, 0);
if (CompositionType.Terminal == _type)
spaceSize = new Size(_attachedPane.ActualWidth, _attachedPane.ActualHeight);
else
{
for (int index = 0; index < _children.Count; ++index)
{
Size currentSize = _children[index]._CalculateSpaceSize();
if (_type == CompositionType.Horizontal)
{
spaceSize.Width = Math.Max(spaceSize.Width, currentSize.Width);
spaceSize.Height += currentSize.Height;
}
else
{
spaceSize.Width += currentSize.Width;
spaceSize.Height = Math.Max(spaceSize.Height, currentSize.Height);
}
}
}
return spaceSize;
}
/// <summary>
/// Normalize factors - sum probably SPACE_FACTOR_FULL
/// </summary>
private void _NormalizeSpaceFactors(double sumFactor)
{
if (SPACE_FACTOR_FULL < sumFactor)
{
// find bigger pane
int biggerIndex = 0;
double maxFactor = _children[biggerIndex].SpaceFactor;
for (int index = biggerIndex + 1; index < _children.Count; ++index)
{
Composition child = _children[index];
if (maxFactor <= child.SpaceFactor)
{
maxFactor = child.SpaceFactor;
biggerIndex = index;
}
}
// gecrease bigger pane
_children[biggerIndex].SpaceFactor -= sumFactor - SPACE_FACTOR_FULL;
}
}
/// <summary>
/// Calculation space factors
/// </summary>
private void _CalculateSpaceFactors()
{
Size fullSize = _CalculateSpaceSize();
if ((fullSize.Height <= 0.0) && (fullSize.Height == fullSize.Width))
return; // NOTE: exit
// minimal factor - page have min size
double minFactor = (_type == CompositionType.Horizontal)?
(DockablePane.MIN_PANE_SIZE / Math.Max(fullSize.Height, 1)) :
(DockablePane.MIN_PANE_SIZE / Math.Max(fullSize.Width, 1));
double increaseFactorValue = 0; // pages with min size increase with this value
for (int index = 0; index < _children.Count; ++index)
{
Composition child = _children[index];
Size childSize = child._CalculateSpaceSize();
double newScale = (_type == CompositionType.Horizontal) ?
(childSize.Height / Math.Max(fullSize.Height, 1)) :
(childSize.Width / Math.Max(fullSize.Width, 1));
// reset tinkle - 1%
if (SPACE_FACTOR_TINKLE < Math.Abs(child.SpaceFactor - newScale))
child.SpaceFactor = newScale;
if (child.SpaceFactor < minFactor)
{
increaseFactorValue += minFactor - child.SpaceFactor;
child.SpaceFactor = minFactor;
}
}
// normalize factors - sum probably SPACE_FACTOR_FULL
double sumFactor = 0.0;
if (0 < increaseFactorValue)
{
// find count of pages for decreasing
int decreaseCount = 0;
for (int index = 0; index < _children.Count; ++index)
{
if (minFactor + increaseFactorValue < _children[index].SpaceFactor)
++decreaseCount;
}
// decrease big pages
double decreaseFactor = increaseFactorValue / decreaseCount;
for (int index = 0; index < _children.Count; ++index)
{
Composition child = _children[index];
if (minFactor + decreaseFactor < child.SpaceFactor)
child.SpaceFactor -= decreaseFactor;
sumFactor += child.SpaceFactor;
}
}
else
{
// callculate sum factors
for (int index = 0; index < _children.Count; ++index)
sumFactor += _children[index].SpaceFactor;
}
_NormalizeSpaceFactors(sumFactor);
}
/// <summary>
/// Check is composition normalized
/// </summary>
/// <remarks>Composition is normalized if all children have other type</remarks>
private bool _IsNormalized()
{
bool isNormalized = true;
for (int index = 0; index < _children.Count; ++index)
{
if (_children[index].Type != CompositionType.Terminal)
{
if (_children[index].Type == _type)
{
isNormalized = false;
break; // NOTE: result founded
}
}
}
return isNormalized;
}
/// <summary>
/// Calculate hypotenuse
/// </summary>
private double _CalculateHypotenuse(Size size)
{
return (size.Width * size.Width + size.Height * size.Height);
}
/// <summary>
/// Find largest pane
/// </summary>
/// <remarks>largest by hypotenuse</remarks>
private void _FindLargestPane(ref Size maxSize, ref DockablePane largestPane)
{
for (int index = 0; index < _children.Count; ++index)
{
Composition child = _children[index];
if (child.Type != CompositionType.Terminal)
child._FindLargestPane(ref maxSize, ref largestPane);
else
{
Size sz = child._CalculateSpaceSize();
if (_CalculateHypotenuse(maxSize) < _CalculateHypotenuse(sz))
{
largestPane = child.AttachedPane;
maxSize = sz;
}
}
}
}
/// <summary>
/// Find last pane
/// </summary>
private void _FindLastPane(ref DockablePane largestPane)
{
for (int index = _children.Count - 1; 0 <= index; --index)
{
Composition child = _children[index];
if (child.Type != CompositionType.Terminal)
child._FindLastPane(ref largestPane);
else
largestPane = child.AttachedPane;
if (null != largestPane)
break; // result founded
}
}
/// <summary>
/// Check is dock is horizontal
/// </summary>
private bool _IsHorizontalDock(Dock dockType)
{
return ((Dock.Top == dockType) || (Dock.Bottom == dockType));
}
/// <summary>
/// Check - if add new elemet to composition by dock - new composition is a line
/// </summary>
private bool _DoesAdding2Line(Dock dockType)
{
return ((_IsHorizontalDock(dockType) && (CompositionType.Horizontal == _type)) ||
(!_IsHorizontalDock(dockType) && (CompositionType.Vertical == _type)));
}
/// <summary>
/// Get composition type by dock
/// </summary>
private CompositionType _GetCompositionTypeByDock(Dock dockType)
{
return (_IsHorizontalDock(dockType)) ? CompositionType.Horizontal : CompositionType.Vertical;
}
/// <summary>
/// Insert new composition element by dock
/// </summary>
private void _InsertElement2Line(Composition newElement, Dock dockType)
{
if ((Dock.Left == dockType) || (Dock.Top == dockType))
_children.Insert(0, newElement);
else if ((Dock.Right == dockType) || (Dock.Bottom == dockType))
_children.Add(newElement);
else
{
Debug.Assert(false); // NOTE: not supported
}
}
/// <summary>
/// Create line composition
/// </summary>
private void _CreateLineComposition(Composition first, Composition second, Dock dockType)
{
_attachedPane = null;
_type = _GetCompositionTypeByDock(dockType);
_children.Add(first);
_InsertElement2Line(second , dockType);
}
/// <summary>
/// Do copy of this composition
/// </summary>
private Composition _CreateCopy()
{
Composition obj = new Composition();
obj._children.AddRange(this._children);
obj._type = this._type;
obj._attachedPane = this._attachedPane;
obj._isInited = this._isInited;
return obj;
}
/// <summary>
/// Add pane to composition
/// </summary>
private void _Add(DockablePane pane, Dock dockType)
{
Composition newElement = new Composition(this, pane);
if (CompositionType.Terminal == _type)
{ // change compostion from terminal to linear
Debug.Assert(0 == _children.Count);
Composition first = new Composition(this, _attachedPane);
_CreateLineComposition(first, newElement, dockType);
}
else
{
if (_DoesAdding2Line(dockType))
{ // add new element to linear composition
// update children space factors
// new child - requared 50% of all layout
for (int index = 0; index < _children.Count; ++index)
_children[index].SpaceFactor /= 2;
_InsertElement2Line(newElement, dockType);
}
else
{
// do copy from current composition - it is linear composition
Composition compositionCopy = _CreateCopy();
// remove old composition elements
_children.Clear();
// do one linear composition:
// add old elements as one linear composition and
// add new element to linear composition
_CreateLineComposition(compositionCopy, newElement, dockType);
}
}
Debug.Assert(_IsNormalized());
}
/// <summary>
/// Arrange vertical composition (creating grid with collumns)
/// </summary>
private void _ArrangeVertical(Grid grid, ref double minHeight)
{
minHeight = DockablePane.MIN_PANE_SIZE;
for (int index = 0; index < _children.Count; ++index)
{
Composition currentComposition = _children[index];
// create column for child
ColumnDefinition column = new ColumnDefinition();
column.Width = new GridLength(currentComposition.SpaceFactor, GridUnitType.Star);
grid.ColumnDefinitions.Add(column);
double minWidth = DockablePane.MIN_PANE_SIZE;
UIElement gridElement = null;
if (CompositionType.Terminal == currentComposition.Type)
gridElement = currentComposition.AttachedPane;
else
{ // if child is compostition - create grid for children
Grid lineGrid = new Grid();
currentComposition._ArrangeHorizontal(lineGrid, ref minWidth);
gridElement = lineGrid;
double splittersSpace = SPLITTER_SIZE * (currentComposition.Children.Count - 1);
lineGrid.MinHeight = grid.MinHeight = DockablePane.MIN_PANE_SIZE * currentComposition.Children.Count + splittersSpace;
minHeight = Math.Max(minHeight, grid.MinHeight);
}
column.MinWidth = minWidth;
// inited column number in new element
grid.Children.Add(gridElement);
Grid.SetColumn(gridElement, index);
// set margin for splitter
Thickness margin = new Thickness(0);
if ((index < _children.Count - 1) && (1 < _children.Count))
margin = new Thickness(0, 0, SPLITTER_SIZE, 0);
gridElement.SetValue(FrameworkElement.MarginProperty, margin);
if (0 < index)
{ // add splitter
GridSplitter splitter = new GridSplitter();
splitter.Width = SPLITTER_SIZE;
splitter.HorizontalAlignment = HorizontalAlignment.Right;
splitter.VerticalAlignment = VerticalAlignment.Stretch;
splitter.Style = (Style)Application.Current.FindResource("DockingSplitterStyle");
Grid.SetColumn(splitter, index - 1);
grid.Children.Add(splitter);
}
}
}
/// <summary>
/// Arrange horizontal composition (creating grid with rows)
/// </summary>
private void _ArrangeHorizontal(Grid grid, ref double minWidth)
{
Debug.Assert(CompositionType.Terminal != _type);
minWidth = DockablePane.MIN_PANE_SIZE;
for (int index = 0; index < _children.Count; ++index)
{
Composition currentComposition = _children[index];
// create row for child
RowDefinition row = new RowDefinition();
row.Height = new GridLength(currentComposition.SpaceFactor, GridUnitType.Star);
grid.RowDefinitions.Add(row);
double minHeight = DockablePane.MIN_PANE_SIZE;
UIElement gridElement = null;
if (CompositionType.Terminal == currentComposition.Type)
gridElement = currentComposition.AttachedPane;
else
{ // if child is compostition - create grid for children
Grid lineGrid = new Grid();
currentComposition._ArrangeVertical(lineGrid, ref minHeight);
gridElement = lineGrid;
double splittersSpace = SPLITTER_SIZE * (currentComposition.Children.Count - 1);
lineGrid.MinWidth = grid.MinWidth = DockablePane.MIN_PANE_SIZE * currentComposition.Children.Count + splittersSpace;
minWidth = Math.Max(minWidth, grid.MinWidth);
}
row.MinHeight = minHeight;
// inited row number in new element
grid.Children.Add(gridElement);
Grid.SetRow(gridElement, index);
// set margin for splitter
Thickness margin = new Thickness(0);
if ((index < _children.Count - 1) && (1 < _children.Count))
margin = new Thickness(0, 0, 0, SPLITTER_SIZE);
gridElement.SetValue(FrameworkElement.MarginProperty, margin);
if (0 < index)
{ // add splitter
GridSplitter splitter = new GridSplitter();
splitter.Height = SPLITTER_SIZE;
splitter.HorizontalAlignment = HorizontalAlignment.Stretch;
splitter.VerticalAlignment = VerticalAlignment.Bottom;
splitter.Style = (Style)Application.Current.FindResource("DockingSplitterStyle");
Grid.SetRow(splitter, index - 1);
grid.Children.Add(splitter);
}
}
}
#endregion // Private helpers
#region Private members
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Type of composition
/// </summary>
private CompositionType _type = CompositionType.Terminal;
/// <summary>
/// Children collection
/// </summary>
/// <remarks>Actual only for CompositionType.Horizontal or CompositionType.Vertical</remarks>
private List<Composition> _children = new List<Composition>();
/// <summary>
/// Attached pane
/// </summary>
/// <remarks>Actual only for CompositionType.Terminal</remarks>
private DockablePane _attachedPane = null;
/// <summary>
/// Space arrange factor
/// </summary>
private double _spaceFactor = DEFAULT_SPACE_FACTOR;
/// <summary>
/// Is object inited
/// </summary>
private bool _isInited = false;
/// <summary>
/// Splitter size
/// </summary>
private const int SPLITTER_SIZE = 4;
/// <summary>
/// Default space factor
/// </summary>
private const double DEFAULT_SPACE_FACTOR = 0.5;
/// <summary>
/// Full space factor - 100%
/// </summary>
private const double SPACE_FACTOR_FULL = 1.0;
/// <summary>
/// Tinkle space factor - 1%
/// </summary>
private const double SPACE_FACTOR_TINKLE = 0.01;
/// <summary>
/// Serialize\Deserialize const
/// </summary>
private const string ELEMENT_NAME_CHILD = "Child";
private const string ELEMENT_NAME_DOCKPANE = "DockablePane";
private const string ELEMENT_NAME_CHILDGROUPS = "ChildGroups";
private const string ATTRIBUTE_NAME_TYPE = "Type";
private const string ATTRIBUTE_NAME_SFACTOR = "SpaceFactor";
private const string STORAGE_CULTURE = "en-US";
#endregion // Private members
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using MLAPI.Serialization.Pooled;
using MLAPI.Serialization;
using MLAPI.Configuration;
using MLAPI.Profiling;
using MLAPI.Transports;
namespace MLAPI.Messaging
{
internal class RpcBatcher
{
public class SendStream
{
public NetworkChannel NetworkChannel;
public PooledNetworkBuffer Buffer;
public PooledNetworkWriter Writer;
public bool IsEmpty = true;
public SendStream()
{
Buffer = PooledNetworkBuffer.Get();
Writer = PooledNetworkWriter.Get(Buffer);
}
}
// Stores the stream of batched RPC to send to each client, by ClientId
private readonly Dictionary<ulong, SendStream> k_SendDict = new Dictionary<ulong, SendStream>();
// Used to store targets, internally
private ulong[] m_TargetList = new ulong[0];
// Used to mark longer lengths. Works because we can't have zero-sized messages
private const byte k_LongLenMarker = 0;
private void PushLength(int length, ref PooledNetworkWriter writer)
{
// If length is single byte we write it
if (length < 256)
{
writer.WriteByte((byte)length); // write the amounts of bytes that are coming up
}
else
{
// otherwise we write a two-byte length
writer.WriteByte(k_LongLenMarker); // mark larger size
writer.WriteByte((byte)(length % 256)); // write the length modulo 256
writer.WriteByte((byte)(length / 256)); // write the length divided by 256
}
}
private int PopLength(in NetworkBuffer messageBuffer)
{
int read = messageBuffer.ReadByte();
// if we read a non-zero value, we have a single byte length
// or a -1 error we can return
if (read != k_LongLenMarker)
{
return read;
}
// otherwise, a two-byte length follows. We'll read in len1, len2
int len1 = messageBuffer.ReadByte();
if (len1 < 0)
{
// pass errors back to caller
return len1;
}
int len2 = messageBuffer.ReadByte();
if (len2 < 0)
{
// pass errors back to caller
return len2;
}
return len1 + len2 * 256;
}
/// <summary>
/// FillTargetList
/// Fills a list with the ClientId's an item is targeted to
/// </summary>
/// <param name="queueItem">the FrameQueueItem we want targets for</param>
/// <param name="networkIdList">the list to fill</param>
private static void FillTargetList(in RpcFrameQueueItem queueItem, ref ulong[] networkIdList)
{
switch (queueItem.QueueItemType)
{
// todo: revisit .resize() and .ToArry() usage, for performance
case RpcQueueContainer.QueueItemType.ServerRpc:
Array.Resize(ref networkIdList, 1);
networkIdList[0] = queueItem.NetworkId;
break;
default:
// todo: consider the implications of default usage of queueItem.clientIds
case RpcQueueContainer.QueueItemType.ClientRpc:
// copy the list
networkIdList = queueItem.ClientNetworkIds.ToArray();
break;
}
}
/// <summary>
/// QueueItem
/// Add a FrameQueueItem to be sent
/// </summary>queueItem
/// <param name="queueItem">the threshold in bytes</param>
public void QueueItem(in RpcFrameQueueItem queueItem)
{
FillTargetList(queueItem, ref m_TargetList);
foreach (ulong clientId in m_TargetList)
{
if (!k_SendDict.ContainsKey(clientId))
{
// todo: consider what happens if many clients join and leave the game consecutively
// we probably need a cleanup mechanism at some point
k_SendDict[clientId] = new SendStream();
}
if (k_SendDict[clientId].IsEmpty)
{
k_SendDict[clientId].IsEmpty = false;
k_SendDict[clientId].NetworkChannel = queueItem.NetworkChannel;
switch (queueItem.QueueItemType)
{
// 8 bits are used for the message type, which is an NetworkConstants
case RpcQueueContainer.QueueItemType.ServerRpc:
k_SendDict[clientId].Writer.WriteByte(NetworkConstants.SERVER_RPC); // MessageType
break;
case RpcQueueContainer.QueueItemType.ClientRpc:
k_SendDict[clientId].Writer.WriteByte(NetworkConstants.CLIENT_RPC); // MessageType
break;
}
}
// write the amounts of bytes that are coming up
PushLength(queueItem.MessageData.Count, ref k_SendDict[clientId].Writer);
// write the message to send
k_SendDict[clientId].Writer.WriteBytes(queueItem.MessageData.Array, queueItem.MessageData.Count, queueItem.MessageData.Offset);
ProfilerStatManager.BytesSent.Record(queueItem.MessageData.Count);
ProfilerStatManager.RpcsSent.Record();
PerformanceDataManager.Increment(ProfilerConstants.ByteSent, queueItem.MessageData.Count);
PerformanceDataManager.Increment(ProfilerConstants.RpcSent);
}
}
public delegate void SendCallbackType(ulong clientId, SendStream messageStream);
public delegate void ReceiveCallbackType(NetworkBuffer messageStream, RpcQueueContainer.QueueItemType messageType, ulong clientId, float receiveTime);
/// <summary>
/// SendItems
/// Send any batch of RPC that are of length above threshold
/// </summary>
/// <param name="thresholdBytes"> the threshold in bytes</param>
/// <param name="sendCallback"> the function to call for sending the batch</param>
public void SendItems(int thresholdBytes, SendCallbackType sendCallback)
{
foreach (KeyValuePair<ulong, SendStream> entry in k_SendDict)
{
if (!entry.Value.IsEmpty)
{
// read the queued message
int length = (int)k_SendDict[entry.Key].Buffer.Length;
if (length >= thresholdBytes)
{
sendCallback(entry.Key, entry.Value);
// clear the batch that was sent from the SendDict
entry.Value.Buffer.SetLength(0);
entry.Value.Buffer.Position = 0;
entry.Value.IsEmpty = true;
ProfilerStatManager.RpcBatchesSent.Record();
PerformanceDataManager.Increment(ProfilerConstants.RpcBatchesSent);
}
}
}
}
/// <summary>
/// ReceiveItems
/// Process the messageStream and call the callback with individual RPC messages
/// </summary>
/// <param name="messageBuffer"> the messageStream containing the batched RPC</param>
/// <param name="receiveCallback"> the callback to call has type int f(message, type, clientId, time) </param>
/// <param name="messageType"> the message type to pass back to callback</param>
/// <param name="clientId"> the clientId to pass back to callback</param>
/// <param name="receiveTime"> the packet receive time to pass back to callback</param>
public void ReceiveItems(in NetworkBuffer messageBuffer, ReceiveCallbackType receiveCallback, RpcQueueContainer.QueueItemType messageType, ulong clientId, float receiveTime)
{
using (var copy = PooledNetworkBuffer.Get())
{
do
{
// read the length of the next RPC
int rpcSize = PopLength(messageBuffer);
if (rpcSize < 0)
{
// abort if there's an error reading lengths
return;
}
// copy what comes after current stream position
long position = messageBuffer.Position;
copy.SetLength(rpcSize);
copy.Position = 0;
Buffer.BlockCopy(messageBuffer.GetBuffer(), (int)position, copy.GetBuffer(), 0, rpcSize);
receiveCallback(copy, messageType, clientId, receiveTime);
// seek over the RPC
// RPCReceiveQueueItem peeks at content, it doesn't advance
messageBuffer.Seek(rpcSize, SeekOrigin.Current);
} while (messageBuffer.Position < messageBuffer.Length);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics; // for TraceInformation
using System.Threading;
using System.Runtime.CompilerServices;
namespace System.Threading
{
public enum LockRecursionPolicy
{
NoRecursion = 0,
SupportsRecursion = 1,
}
//
// ReaderWriterCount tracks how many of each kind of lock is held by each thread.
// We keep a linked list for each thread, attached to a ThreadStatic field.
// These are reused wherever possible, so that a given thread will only
// allocate N of these, where N is the maximum number of locks held simultaneously
// by that thread.
//
internal class ReaderWriterCount
{
// Which lock does this object belong to? This is a numeric ID for two reasons:
// 1) We don't want this field to keep the lock object alive, and a WeakReference would
// be too expensive.
// 2) Setting the value of a long is faster than setting the value of a reference.
// The "hot" paths in ReaderWriterLockSlim are short enough that this actually
// matters.
public long lockID;
// How many reader locks does this thread hold on this ReaderWriterLockSlim instance?
public int readercount;
// Ditto for writer/upgrader counts. These are only used if the lock allows recursion.
// But we have to have the fields on every ReaderWriterCount instance, because
// we reuse it for different locks.
public int writercount;
public int upgradecount;
// Next RWC in this thread's list.
public ReaderWriterCount next;
}
/// <summary>
/// A reader-writer lock implementation that is intended to be simple, yet very
/// efficient. In particular only 1 interlocked operation is taken for any lock
/// operation (we use spin locks to achieve this). The spin lock is never held
/// for more than a few instructions (in particular, we never call event APIs
/// or in fact any non-trivial API while holding the spin lock).
/// </summary>
public class ReaderWriterLockSlim : IDisposable
{
//Specifying if locked can be reacquired recursively.
private bool _fIsReentrant;
// Lock specification for myLock: This lock protects exactly the local fields associated with this
// instance of ReaderWriterLockSlim. It does NOT protect the memory associated with
// the events that hang off this lock (eg writeEvent, readEvent upgradeEvent).
private int _myLock;
//The variables controlling spinning behavior of Mylock(which is a spin-lock)
private const int LockSpinCycles = 20;
private const int LockSpinCount = 10;
private const int LockSleep0Count = 5;
// These variables allow use to avoid Setting events (which is expensive) if we don't have to.
private uint _numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent
private uint _numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent
private uint _numWriteUpgradeWaiters; // maximum number of threads that can be doing a WaitOne on the upgradeEvent (at most 1).
private uint _numUpgradeWaiters;
//Variable used for quick check when there are no waiters.
private bool _fNoWaiters;
private int _upgradeLockOwnerId;
private int _writeLockOwnerId;
// conditions we wait on.
private EventWaitHandle _writeEvent; // threads waiting to acquire a write lock go here.
private EventWaitHandle _readEvent; // threads waiting to acquire a read lock go here (will be released in bulk)
private EventWaitHandle _upgradeEvent; // thread waiting to acquire the upgrade lock
private EventWaitHandle _waitUpgradeEvent; // thread waiting to upgrade from the upgrade lock to a write lock go here (at most one)
// Every lock instance has a unique ID, which is used by ReaderWriterCount to associate itself with the lock
// without holding a reference to it.
private static long s_nextLockID;
private long _lockID;
// See comments on ReaderWriterCount.
[ThreadStatic]
private static ReaderWriterCount t_rwc;
private bool _fUpgradeThreadHoldingRead;
private const int MaxSpinCount = 20;
//The uint, that contains info like if the writer lock is held, num of
//readers etc.
private uint _owners;
//Various R/W masks
//Note:
//The Uint is divided as follows:
//
//Writer-Owned Waiting-Writers Waiting Upgraders Num-Readers
// 31 30 29 28.......0
//
//Dividing the uint, allows to vastly simplify logic for checking if a
//reader should go in etc. Setting the writer bit will automatically
//make the value of the uint much larger than the max num of readers
//allowed, thus causing the check for max_readers to fail.
private const uint WRITER_HELD = 0x80000000;
private const uint WAITING_WRITERS = 0x40000000;
private const uint WAITING_UPGRADER = 0x20000000;
//The max readers is actually one less then its theoretical max.
//This is done in order to prevent reader count overflows. If the reader
//count reaches max, other readers will wait.
private const uint MAX_READER = 0x10000000 - 2;
private const uint READER_MASK = 0x10000000 - 1;
private bool _fDisposed;
private void InitializeThreadCounts()
{
_upgradeLockOwnerId = -1;
_writeLockOwnerId = -1;
}
public ReaderWriterLockSlim()
: this(LockRecursionPolicy.NoRecursion)
{
}
public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy)
{
if (recursionPolicy == LockRecursionPolicy.SupportsRecursion)
{
_fIsReentrant = true;
}
InitializeThreadCounts();
_fNoWaiters = true;
_lockID = Interlocked.Increment(ref s_nextLockID);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsRWEntryEmpty(ReaderWriterCount rwc)
{
if (rwc.lockID == 0)
return true;
else if (rwc.readercount == 0 && rwc.writercount == 0 && rwc.upgradecount == 0)
return true;
else
return false;
}
private bool IsRwHashEntryChanged(ReaderWriterCount lrwc)
{
return lrwc.lockID != _lockID;
}
/// <summary>
/// This routine retrieves/sets the per-thread counts needed to enforce the
/// various rules related to acquiring the lock.
///
/// DontAllocate is set to true if the caller just wants to get an existing
/// entry for this thread, but doesn't want to add one if an existing one
/// could not be found.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ReaderWriterCount GetThreadRWCount(bool dontAllocate)
{
ReaderWriterCount rwc = t_rwc;
ReaderWriterCount empty = null;
while (rwc != null)
{
if (rwc.lockID == _lockID)
return rwc;
if (!dontAllocate && empty == null && IsRWEntryEmpty(rwc))
empty = rwc;
rwc = rwc.next;
}
if (dontAllocate)
return null;
if (empty == null)
{
empty = new ReaderWriterCount();
empty.next = t_rwc;
t_rwc = empty;
}
empty.lockID = _lockID;
return empty;
}
public void EnterReadLock()
{
TryEnterReadLock(-1);
}
//
// Common timeout support
//
private struct TimeoutTracker
{
private int _total;
private int _start;
public TimeoutTracker(TimeSpan timeout)
{
long ltm = (long)timeout.TotalMilliseconds;
if (ltm < -1 || ltm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout));
_total = (int)ltm;
if (_total != -1 && _total != 0)
_start = Environment.TickCount;
else
_start = 0;
}
public TimeoutTracker(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
_total = millisecondsTimeout;
if (_total != -1 && _total != 0)
_start = Environment.TickCount;
else
_start = 0;
}
public int RemainingMilliseconds
{
get
{
if (_total == -1 || _total == 0)
return _total;
int elapsed = Environment.TickCount - _start;
// elapsed may be negative if TickCount has overflowed by 2^31 milliseconds.
if (elapsed < 0 || elapsed >= _total)
return 0;
return _total - elapsed;
}
}
public bool IsExpired
{
get
{
return RemainingMilliseconds == 0;
}
}
}
public bool TryEnterReadLock(TimeSpan timeout)
{
return TryEnterReadLock(new TimeoutTracker(timeout));
}
public bool TryEnterReadLock(int millisecondsTimeout)
{
return TryEnterReadLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterReadLock(TimeoutTracker timeout)
{
return TryEnterReadLockCore(timeout);
}
private bool TryEnterReadLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
ReaderWriterCount lrwc = null;
int id = Environment.CurrentManagedThreadId;
if (!_fIsReentrant)
{
if (id == _writeLockOwnerId)
{
//Check for AW->AR
throw new LockRecursionException(SR.LockRecursionException_ReadAfterWriteNotAllowed);
}
EnterMyLock();
lrwc = GetThreadRWCount(false);
//Check if the reader lock is already acquired. Note, we could
//check the presence of a reader by not allocating rwc (But that
//would lead to two lookups in the common case. It's better to keep
//a count in the structure).
if (lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_RecursiveReadNotAllowed);
}
else if (id == _upgradeLockOwnerId)
{
//The upgrade lock is already held.
//Update the global read counts and exit.
lrwc.readercount++;
_owners++;
ExitMyLock();
return true;
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (lrwc.readercount > 0)
{
lrwc.readercount++;
ExitMyLock();
return true;
}
else if (id == _upgradeLockOwnerId)
{
//The upgrade lock is already held.
//Update the global read counts and exit.
lrwc.readercount++;
_owners++;
ExitMyLock();
_fUpgradeThreadHoldingRead = true;
return true;
}
else if (id == _writeLockOwnerId)
{
//The write lock is already held.
//Update global read counts here,
lrwc.readercount++;
_owners++;
ExitMyLock();
return true;
}
}
bool retVal = true;
int spincount = 0;
for (; ;)
{
// We can enter a read lock if there are only read-locks have been given out
// and a writer is not trying to get in.
if (_owners < MAX_READER)
{
// Good case, there is no contention, we are basically done
_owners++; // Indicate we have another reader
lrwc.readercount++;
break;
}
if (spincount < MaxSpinCount)
{
ExitMyLock();
if (timeout.IsExpired)
return false;
spincount++;
SpinWait(spincount);
EnterMyLock();
//The per-thread structure may have been recycled as the lock is acquired (due to message pumping), load again.
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
continue;
}
// Drat, we need to wait. Mark that we have waiters and wait.
if (_readEvent == null) // Create the needed event
{
LazyCreateEvent(ref _readEvent, false);
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
continue; // since we left the lock, start over.
}
retVal = WaitOnEvent(_readEvent, ref _numReadWaiters, timeout, isWriteWaiter: false);
if (!retVal)
{
return false;
}
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
}
ExitMyLock();
return retVal;
}
public void EnterWriteLock()
{
TryEnterWriteLock(-1);
}
public bool TryEnterWriteLock(TimeSpan timeout)
{
return TryEnterWriteLock(new TimeoutTracker(timeout));
}
public bool TryEnterWriteLock(int millisecondsTimeout)
{
return TryEnterWriteLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterWriteLock(TimeoutTracker timeout)
{
return TryEnterWriteLockCore(timeout);
}
private bool TryEnterWriteLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
int id = Environment.CurrentManagedThreadId;
ReaderWriterCount lrwc;
bool upgradingToWrite = false;
if (!_fIsReentrant)
{
if (id == _writeLockOwnerId)
{
//Check for AW->AW
throw new LockRecursionException(SR.LockRecursionException_RecursiveWriteNotAllowed);
}
else if (id == _upgradeLockOwnerId)
{
//AU->AW case is allowed once.
upgradingToWrite = true;
}
EnterMyLock();
lrwc = GetThreadRWCount(true);
//Can't acquire write lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (id == _writeLockOwnerId)
{
lrwc.writercount++;
ExitMyLock();
return true;
}
else if (id == _upgradeLockOwnerId)
{
upgradingToWrite = true;
}
else if (lrwc.readercount > 0)
{
//Write locks may not be acquired if only read locks have been
//acquired.
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
}
}
int spincount = 0;
bool retVal = true;
for (; ;)
{
if (IsWriterAcquired())
{
// Good case, there is no contention, we are basically done
SetWriterAcquired();
break;
}
//Check if there is just one upgrader, and no readers.
//Assumption: Only one thread can have the upgrade lock, so the
//following check will fail for all other threads that may sneak in
//when the upgrading thread is waiting.
if (upgradingToWrite)
{
uint readercount = GetNumReaders();
if (readercount == 1)
{
//Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
else if (readercount == 2)
{
if (lrwc != null)
{
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
if (lrwc.readercount > 0)
{
//This check is needed for EU->ER->EW case, as the owner count will be two.
Debug.Assert(_fIsReentrant);
Debug.Assert(_fUpgradeThreadHoldingRead);
//Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
}
}
}
if (spincount < MaxSpinCount)
{
ExitMyLock();
if (timeout.IsExpired)
return false;
spincount++;
SpinWait(spincount);
EnterMyLock();
continue;
}
if (upgradingToWrite)
{
if (_waitUpgradeEvent == null) // Create the needed event
{
LazyCreateEvent(ref _waitUpgradeEvent, true);
continue; // since we left the lock, start over.
}
Debug.Assert(_numWriteUpgradeWaiters == 0, "There can be at most one thread with the upgrade lock held.");
retVal = WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout, isWriteWaiter: true);
//The lock is not held in case of failure.
if (!retVal)
return false;
}
else
{
// Drat, we need to wait. Mark that we have waiters and wait.
if (_writeEvent == null) // create the needed event.
{
LazyCreateEvent(ref _writeEvent, true);
continue; // since we left the lock, start over.
}
retVal = WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout, isWriteWaiter: true);
//The lock is not held in case of failure.
if (!retVal)
return false;
}
}
Debug.Assert((_owners & WRITER_HELD) > 0);
if (_fIsReentrant)
{
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
lrwc.writercount++;
}
ExitMyLock();
_writeLockOwnerId = id;
return true;
}
public void EnterUpgradeableReadLock()
{
TryEnterUpgradeableReadLock(-1);
}
public bool TryEnterUpgradeableReadLock(TimeSpan timeout)
{
return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout));
}
public bool TryEnterUpgradeableReadLock(int millisecondsTimeout)
{
return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout)
{
return TryEnterUpgradeableReadLockCore(timeout);
}
private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
int id = Environment.CurrentManagedThreadId;
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (id == _upgradeLockOwnerId)
{
//Check for AU->AU
throw new LockRecursionException(SR.LockRecursionException_RecursiveUpgradeNotAllowed);
}
else if (id == _writeLockOwnerId)
{
//Check for AU->AW
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterWriteNotAllowed);
}
EnterMyLock();
lrwc = GetThreadRWCount(true);
//Can't acquire upgrade lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (id == _upgradeLockOwnerId)
{
lrwc.upgradecount++;
ExitMyLock();
return true;
}
else if (id == _writeLockOwnerId)
{
//Write lock is already held, Just update the global state
//to show presence of upgrader.
Debug.Assert((_owners & WRITER_HELD) > 0);
_owners++;
_upgradeLockOwnerId = id;
lrwc.upgradecount++;
if (lrwc.readercount > 0)
_fUpgradeThreadHoldingRead = true;
ExitMyLock();
return true;
}
else if (lrwc.readercount > 0)
{
//Upgrade locks may not be acquired if only read locks have been
//acquired.
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
}
}
bool retVal = true;
int spincount = 0;
for (; ;)
{
//Once an upgrade lock is taken, it's like having a reader lock held
//until upgrade or downgrade operations are performed.
if ((_upgradeLockOwnerId == -1) && (_owners < MAX_READER))
{
_owners++;
_upgradeLockOwnerId = id;
break;
}
if (spincount < MaxSpinCount)
{
ExitMyLock();
if (timeout.IsExpired)
return false;
spincount++;
SpinWait(spincount);
EnterMyLock();
continue;
}
// Drat, we need to wait. Mark that we have waiters and wait.
if (_upgradeEvent == null) // Create the needed event
{
LazyCreateEvent(ref _upgradeEvent, true);
continue; // since we left the lock, start over.
}
//Only one thread with the upgrade lock held can proceed.
retVal = WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout, isWriteWaiter: false);
if (!retVal)
return false;
}
if (_fIsReentrant)
{
//The lock may have been dropped getting here, so make a quick check to see whether some other
//thread did not grab the entry.
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
lrwc.upgradecount++;
}
ExitMyLock();
return true;
}
public void ExitReadLock()
{
ReaderWriterCount lrwc = null;
EnterMyLock();
lrwc = GetThreadRWCount(true);
if (lrwc == null || lrwc.readercount < 1)
{
//You have to be holding the read lock to make this call.
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedRead);
}
if (_fIsReentrant)
{
if (lrwc.readercount > 1)
{
lrwc.readercount--;
ExitMyLock();
return;
}
if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
{
_fUpgradeThreadHoldingRead = false;
}
}
Debug.Assert(_owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
--_owners;
Debug.Assert(lrwc.readercount == 1);
lrwc.readercount--;
ExitAndWakeUpAppropriateWaiters();
}
public void ExitWriteLock()
{
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (Environment.CurrentManagedThreadId != _writeLockOwnerId)
{
//You have to be holding the write lock to make this call.
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
EnterMyLock();
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (lrwc == null)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
if (lrwc.writercount < 1)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
lrwc.writercount--;
if (lrwc.writercount > 0)
{
ExitMyLock();
return;
}
}
Debug.Assert((_owners & WRITER_HELD) > 0, "Calling ReleaseWriterLock when no write lock is held");
ClearWriterAcquired();
_writeLockOwnerId = -1;
ExitAndWakeUpAppropriateWaiters();
}
public void ExitUpgradeableReadLock()
{
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId)
{
//You have to be holding the upgrade lock to make this call.
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
EnterMyLock();
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(true);
if (lrwc == null)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
if (lrwc.upgradecount < 1)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
lrwc.upgradecount--;
if (lrwc.upgradecount > 0)
{
ExitMyLock();
return;
}
_fUpgradeThreadHoldingRead = false;
}
_owners--;
_upgradeLockOwnerId = -1;
ExitAndWakeUpAppropriateWaiters();
}
/// <summary>
/// A routine for lazily creating a event outside the lock (so if errors
/// happen they are outside the lock and that we don't do much work
/// while holding a spin lock). If all goes well, reenter the lock and
/// set 'waitEvent'
/// </summary>
private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent)
{
#if DEBUG
Debug.Assert(MyLockHeld);
Debug.Assert(waitEvent == null);
#endif
ExitMyLock();
EventWaitHandle newEvent;
if (makeAutoResetEvent)
newEvent = new AutoResetEvent(false);
else
newEvent = new ManualResetEvent(false);
EnterMyLock();
if (waitEvent == null) // maybe someone snuck in.
waitEvent = newEvent;
else
newEvent.Dispose();
}
/// <summary>
/// Waits on 'waitEvent' with a timeout
/// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
/// </summary>
private bool WaitOnEvent(
EventWaitHandle waitEvent,
ref uint numWaiters,
TimeoutTracker timeout,
bool isWriteWaiter)
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
waitEvent.Reset();
numWaiters++;
_fNoWaiters = false;
//Setting these bits will prevent new readers from getting in.
if (_numWriteWaiters == 1)
SetWritersWaiting();
if (_numWriteUpgradeWaiters == 1)
SetUpgraderWaiting();
bool waitSuccessful = false;
ExitMyLock(); // Do the wait outside of any lock
try
{
waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds);
}
finally
{
EnterMyLock();
--numWaiters;
if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0)
_fNoWaiters = true;
if (_numWriteWaiters == 0)
ClearWritersWaiting();
if (_numWriteUpgradeWaiters == 0)
ClearUpgraderWaiting();
if (!waitSuccessful) // We may also be about to throw for some reason. Exit myLock.
{
if (isWriteWaiter)
{
// Write waiters block read waiters from acquiring the lock. Since this was the last write waiter, try
// to wake up the appropriate read waiters.
ExitAndWakeUpAppropriateReadWaiters();
}
else
ExitMyLock();
}
}
return waitSuccessful;
}
/// <summary>
/// Determines the appropriate events to set, leaves the locks, and sets the events.
/// </summary>
private void ExitAndWakeUpAppropriateWaiters()
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
if (_fNoWaiters)
{
ExitMyLock();
return;
}
ExitAndWakeUpAppropriateWaitersPreferringWriters();
}
private void ExitAndWakeUpAppropriateWaitersPreferringWriters()
{
uint readercount = GetNumReaders();
//We need this case for EU->ER->EW case, as the read count will be 2 in
//that scenario.
if (_fIsReentrant)
{
if (_numWriteUpgradeWaiters > 0 && _fUpgradeThreadHoldingRead && readercount == 2)
{
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
_waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
return;
}
}
if (readercount == 1 && _numWriteUpgradeWaiters > 0)
{
//We have to be careful now, as we are dropping the lock.
//No new writes should be allowed to sneak in if an upgrade
//was pending.
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
_waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
}
else if (readercount == 0 && _numWriteWaiters > 0)
{
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
_writeEvent.Set(); // release one writer.
}
else
{
ExitAndWakeUpAppropriateReadWaiters();
}
}
private void ExitAndWakeUpAppropriateReadWaiters()
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || _fNoWaiters)
{
ExitMyLock();
return;
}
Debug.Assert(_numReadWaiters != 0 || _numUpgradeWaiters != 0);
bool setReadEvent = _numReadWaiters != 0;
bool setUpgradeEvent = _numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1;
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
if (setReadEvent)
_readEvent.Set(); // release all readers.
if (setUpgradeEvent)
_upgradeEvent.Set(); //release one upgrader.
}
private bool IsWriterAcquired()
{
return (_owners & ~WAITING_WRITERS) == 0;
}
private void SetWriterAcquired()
{
_owners |= WRITER_HELD; // indicate we have a writer.
}
private void ClearWriterAcquired()
{
_owners &= ~WRITER_HELD;
}
private void SetWritersWaiting()
{
_owners |= WAITING_WRITERS;
}
private void ClearWritersWaiting()
{
_owners &= ~WAITING_WRITERS;
}
private void SetUpgraderWaiting()
{
_owners |= WAITING_UPGRADER;
}
private void ClearUpgraderWaiting()
{
_owners &= ~WAITING_UPGRADER;
}
private uint GetNumReaders()
{
return _owners & READER_MASK;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnterMyLock()
{
if (Interlocked.CompareExchange(ref _myLock, 1, 0) != 0)
EnterMyLockSpin();
}
private void EnterMyLockSpin()
{
int pc = Environment.ProcessorCount;
for (int i = 0; ; i++)
{
if (i < LockSpinCount && pc > 1)
{
Helpers.Spin(LockSpinCycles * (i + 1)); // Wait a few dozen instructions to let another processor release lock.
}
else if (i < (LockSpinCount + LockSleep0Count))
{
Helpers.Sleep(0); // Give up my quantum.
}
else
{
Helpers.Sleep(1); // Give up my quantum.
}
if (_myLock == 0 && Interlocked.CompareExchange(ref _myLock, 1, 0) == 0)
return;
}
}
private void ExitMyLock()
{
Debug.Assert(_myLock != 0, "Exiting spin lock that is not held");
Volatile.Write(ref _myLock, 0);
}
#if DEBUG
private bool MyLockHeld { get { return _myLock != 0; } }
#endif
private static void SpinWait(int SpinCount)
{
//Exponential back-off
if ((SpinCount < 5) && (Environment.ProcessorCount > 1))
{
Helpers.Spin(LockSpinCycles * SpinCount);
}
else if (SpinCount < MaxSpinCount - 3)
{
Helpers.Sleep(0);
}
else
{
Helpers.Sleep(1);
}
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (disposing && !_fDisposed)
{
if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0)
throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld)
throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
if (_writeEvent != null)
{
_writeEvent.Dispose();
_writeEvent = null;
}
if (_readEvent != null)
{
_readEvent.Dispose();
_readEvent = null;
}
if (_upgradeEvent != null)
{
_upgradeEvent.Dispose();
_upgradeEvent = null;
}
if (_waitUpgradeEvent != null)
{
_waitUpgradeEvent.Dispose();
_waitUpgradeEvent = null;
}
_fDisposed = true;
}
}
public bool IsReadLockHeld
{
get
{
if (RecursiveReadCount > 0)
return true;
else
return false;
}
}
public bool IsUpgradeableReadLockHeld
{
get
{
if (RecursiveUpgradeCount > 0)
return true;
else
return false;
}
}
public bool IsWriteLockHeld
{
get
{
if (RecursiveWriteCount > 0)
return true;
else
return false;
}
}
public LockRecursionPolicy RecursionPolicy
{
get
{
if (_fIsReentrant)
{
return LockRecursionPolicy.SupportsRecursion;
}
else
{
return LockRecursionPolicy.NoRecursion;
}
}
}
public int CurrentReadCount
{
get
{
int numreaders = (int)GetNumReaders();
if (_upgradeLockOwnerId != -1)
return numreaders - 1;
else
return numreaders;
}
}
public int RecursiveReadCount
{
get
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if (lrwc != null)
count = lrwc.readercount;
return count;
}
}
public int RecursiveUpgradeCount
{
get
{
if (_fIsReentrant)
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if (lrwc != null)
count = lrwc.upgradecount;
return count;
}
else
{
if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
return 1;
else
return 0;
}
}
}
public int RecursiveWriteCount
{
get
{
if (_fIsReentrant)
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if (lrwc != null)
count = lrwc.writercount;
return count;
}
else
{
if (Environment.CurrentManagedThreadId == _writeLockOwnerId)
return 1;
else
return 0;
}
}
}
public int WaitingReadCount
{
get
{
return (int)_numReadWaiters;
}
}
public int WaitingUpgradeCount
{
get
{
return (int)_numUpgradeWaiters;
}
}
public int WaitingWriteCount
{
get
{
return (int)_numWriteWaiters;
}
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace FloydPink.Flickr.Downloadr.UI.Windows
{
public partial class AboutWindow
{
private global::Gtk.VBox vbox3;
private global::Gtk.VBox vbox4;
private global::Gtk.HBox hbox7;
private global::Gtk.Alignment alignment6;
private global::Gtk.Image image2;
private global::Gtk.Alignment alignment7;
private global::Gtk.Label labelVersion;
private global::Gtk.VBox vbox5;
private global::Gtk.HBox hbox6;
private global::Gtk.Alignment alignment1;
private global::Gtk.EventBox eventboxHyperlink;
private global::Gtk.Label labelLink;
private global::Gtk.Alignment alignment2;
private global::Gtk.HBox hbox2;
private global::Gtk.Alignment alignment3;
private global::Gtk.EventBox eventboxDonate;
private global::Gtk.Label labelDonate;
private global::Gtk.Alignment alignment4;
private global::Gtk.HBox hbox5;
private global::Gtk.Button buttonClose;
protected virtual void Build()
{
global::Stetic.Gui.Initialize(this);
// Widget FloydPink.Flickr.Downloadr.UI.Windows.AboutWindow
this.WidthRequest = 360;
this.HeightRequest = 220;
this.Name = "FloydPink.Flickr.Downloadr.UI.Windows.AboutWindow";
this.Title = global::Mono.Unix.Catalog.GetString("About - flickr downloadr");
this.Icon = global::Gdk.Pixbuf.LoadFromResource("FloydPink.Flickr.Downloadr.UI.Assets.icon.png");
this.TypeHint = ((global::Gdk.WindowTypeHint)(1));
this.WindowPosition = ((global::Gtk.WindowPosition)(3));
this.Modal = true;
this.Resizable = false;
this.AllowGrow = false;
// Container child FloydPink.Flickr.Downloadr.UI.Windows.AboutWindow.Gtk.Container+ContainerChild
this.vbox3 = new global::Gtk.VBox();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.vbox4 = new global::Gtk.VBox();
this.vbox4.Name = "vbox4";
this.vbox4.Homogeneous = true;
this.vbox4.Spacing = 6;
// Container child vbox4.Gtk.Box+BoxChild
this.hbox7 = new global::Gtk.HBox();
this.hbox7.Name = "hbox7";
this.hbox7.Spacing = 6;
// Container child hbox7.Gtk.Box+BoxChild
this.alignment6 = new global::Gtk.Alignment(0.5F, 0.5F, 1F, 1F);
this.alignment6.Name = "alignment6";
this.hbox7.Add(this.alignment6);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.hbox7[this.alignment6]));
w1.Position = 0;
// Container child hbox7.Gtk.Box+BoxChild
this.image2 = new global::Gtk.Image();
this.image2.Name = "image2";
this.image2.Pixbuf = global::Gdk.Pixbuf.LoadFromResource("FloydPink.Flickr.Downloadr.UI.Assets.logo-Small-About.png");
this.hbox7.Add(this.image2);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.hbox7[this.image2]));
w2.Position = 1;
w2.Expand = false;
w2.Fill = false;
// Container child hbox7.Gtk.Box+BoxChild
this.alignment7 = new global::Gtk.Alignment(0.5F, 0.5F, 1F, 1F);
this.alignment7.Name = "alignment7";
this.hbox7.Add(this.alignment7);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox7[this.alignment7]));
w3.Position = 2;
this.vbox4.Add(this.hbox7);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.hbox7]));
w4.Position = 0;
w4.Expand = false;
w4.Fill = false;
// Container child vbox4.Gtk.Box+BoxChild
this.labelVersion = new global::Gtk.Label();
this.labelVersion.Name = "labelVersion";
this.labelVersion.LabelProp = global::Mono.Unix.Catalog.GetString("flickr downloadr");
this.labelVersion.UseMarkup = true;
this.vbox4.Add(this.labelVersion);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.labelVersion]));
w5.Position = 2;
w5.Expand = false;
w5.Fill = false;
this.vbox3.Add(this.vbox4);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.vbox4]));
w6.Position = 0;
// Container child vbox3.Gtk.Box+BoxChild
this.vbox5 = new global::Gtk.VBox();
this.vbox5.Name = "vbox5";
this.vbox5.Homogeneous = true;
this.vbox5.Spacing = 6;
// Container child vbox5.Gtk.Box+BoxChild
this.hbox6 = new global::Gtk.HBox();
this.hbox6.Name = "hbox6";
this.hbox6.Spacing = 6;
// Container child hbox6.Gtk.Box+BoxChild
this.alignment1 = new global::Gtk.Alignment(0.5F, 0.5F, 1F, 1F);
this.alignment1.Name = "alignment1";
this.hbox6.Add(this.alignment1);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.hbox6[this.alignment1]));
w7.Position = 0;
// Container child hbox6.Gtk.Box+BoxChild
this.eventboxHyperlink = new global::Gtk.EventBox();
this.eventboxHyperlink.Name = "eventboxHyperlink";
// Container child eventboxHyperlink.Gtk.Container+ContainerChild
this.labelLink = new global::Gtk.Label();
this.labelLink.Name = "labelLink";
this.labelLink.LabelProp = global::Mono.Unix.Catalog.GetString("<a href=\"#\"><b><big><span color=\"blue\">http://flickrdownloadr.com</span></big></b" +
"></a>");
this.labelLink.UseMarkup = true;
this.labelLink.UseUnderline = true;
this.eventboxHyperlink.Add(this.labelLink);
this.hbox6.Add(this.eventboxHyperlink);
global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.hbox6[this.eventboxHyperlink]));
w9.Position = 1;
w9.Expand = false;
w9.Fill = false;
// Container child hbox6.Gtk.Box+BoxChild
this.alignment2 = new global::Gtk.Alignment(0.5F, 0.5F, 1F, 1F);
this.alignment2.Name = "alignment2";
this.hbox6.Add(this.alignment2);
global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.hbox6[this.alignment2]));
w10.Position = 2;
this.vbox5.Add(this.hbox6);
global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.vbox5[this.hbox6]));
w11.Position = 1;
w11.Expand = false;
w11.Fill = false;
// Container child vbox5.Gtk.Box+BoxChild
this.hbox2 = new global::Gtk.HBox();
this.hbox2.Name = "hbox2";
this.hbox2.Spacing = 6;
// Container child hbox2.Gtk.Box+BoxChild
this.alignment3 = new global::Gtk.Alignment(0.5F, 0.5F, 1F, 1F);
this.alignment3.Name = "alignment3";
this.hbox2.Add(this.alignment3);
global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.alignment3]));
w12.Position = 0;
// Container child hbox2.Gtk.Box+BoxChild
this.eventboxDonate = new global::Gtk.EventBox();
this.eventboxDonate.Name = "eventboxDonate";
// Container child eventboxDonate.Gtk.Container+ContainerChild
this.labelDonate = new global::Gtk.Label();
this.labelDonate.Name = "labelDonate";
this.labelDonate.LabelProp = global::Mono.Unix.Catalog.GetString("<a href=\"#\"><b><span color=\"blue\">Donate</span></b></a>");
this.labelDonate.UseMarkup = true;
this.labelDonate.UseUnderline = true;
this.eventboxDonate.Add(this.labelDonate);
this.hbox2.Add(this.eventboxDonate);
global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.eventboxDonate]));
w14.Position = 1;
w14.Expand = false;
w14.Fill = false;
// Container child hbox2.Gtk.Box+BoxChild
this.alignment4 = new global::Gtk.Alignment(0.5F, 0.5F, 1F, 1F);
this.alignment4.Name = "alignment4";
this.hbox2.Add(this.alignment4);
global::Gtk.Box.BoxChild w15 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.alignment4]));
w15.Position = 2;
this.vbox5.Add(this.hbox2);
global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.vbox5[this.hbox2]));
w16.Position = 2;
w16.Expand = false;
w16.Fill = false;
// Container child vbox5.Gtk.Box+BoxChild
this.hbox5 = new global::Gtk.HBox();
this.hbox5.Name = "hbox5";
this.hbox5.Homogeneous = true;
this.hbox5.Spacing = 6;
// Container child hbox5.Gtk.Box+BoxChild
this.buttonClose = new global::Gtk.Button();
this.buttonClose.WidthRequest = 50;
this.buttonClose.CanFocus = true;
this.buttonClose.Name = "buttonClose";
this.buttonClose.UseUnderline = true;
this.buttonClose.Label = global::Mono.Unix.Catalog.GetString("Close");
this.hbox5.Add(this.buttonClose);
global::Gtk.Box.BoxChild w17 = ((global::Gtk.Box.BoxChild)(this.hbox5[this.buttonClose]));
w17.Position = 2;
w17.Expand = false;
w17.Fill = false;
this.vbox5.Add(this.hbox5);
global::Gtk.Box.BoxChild w18 = ((global::Gtk.Box.BoxChild)(this.vbox5[this.hbox5]));
w18.Position = 3;
w18.Expand = false;
w18.Fill = false;
this.vbox3.Add(this.vbox5);
global::Gtk.Box.BoxChild w19 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.vbox5]));
w19.Position = 1;
this.Add(this.vbox3);
if ((this.Child != null))
{
this.Child.ShowAll();
}
this.DefaultWidth = 400;
this.DefaultHeight = 300;
this.Show();
this.eventboxHyperlink.ButtonPressEvent += new global::Gtk.ButtonPressEventHandler(this.eventboxHyperlinkClicked);
this.eventboxDonate.ButtonPressEvent += new global::Gtk.ButtonPressEventHandler(this.eventboxDonateClicked);
this.buttonClose.Clicked += new global::System.EventHandler(this.buttonCloseClick);
}
}
}
| |
namespace PokerTell.LiveTracker.Tests.Tracking
{
using System;
using System.Collections.Generic;
using Infrastructure.Interfaces.LiveTracker;
using Machine.Specifications;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Presentation.Events;
using Moq;
using PokerTell.Infrastructure.Events;
using PokerTell.Infrastructure.Interfaces;
using PokerTell.Infrastructure.Interfaces.PokerHand;
using PokerTell.Infrastructure.Services;
using PokerTell.LiveTracker.Events;
using PokerTell.LiveTracker.Interfaces;
using PokerTell.LiveTracker.Tracking;
using It = Machine.Specifications.It;
// Resharper disable InconsistentNaming
public abstract class GamesTrackerSpecs
{
protected static IEventAggregator _eventAggregator;
protected static Mock<IGameController> _gameController_Mock;
protected static Mock<ILiveTrackerSettingsViewModel> _settings_Stub;
protected static Mock<INewHandsTracker> _newHandsTracker_Mock;
protected static GamesTrackerSut _sut;
Establish specContext = () => {
_eventAggregator = new EventAggregator();
_gameController_Mock = new Mock<IGameController>();
_newHandsTracker_Mock = new Mock<INewHandsTracker>();
_settings_Stub = new Mock<ILiveTrackerSettingsViewModel>();
_settings_Stub
.SetupGet(ls => ls.HandHistoryFilesPaths).Returns(new string[] { });
_sut = new GamesTrackerSut(_eventAggregator,
_newHandsTracker_Mock.Object,
new Constructor<IGameController>(() => _gameController_Mock.Object))
{ ThreadOption = ThreadOption.PublisherThread };
};
public abstract class Ctx_InitializedWithLiveTrackerSettings : GamesTrackerSpecs
{
Establish initializedContext = () => _sut.InitializeWith(_settings_Stub.Object);
}
[Subject(typeof(GamesTracker), "InitializeWith")]
public class when_initialized_with_live_tracker_settings : GamesTrackerSpecs
{
const string path = "firstPath";
static string[] thePaths;
Establish context = () => {
thePaths = new[] { path };
_sut.GameControllers.Add("somePath", _gameController_Mock.Object);
_settings_Stub
.SetupGet(ls => ls.HandHistoryFilesPaths).Returns(thePaths);
};
Because of = () => _sut.InitializeWith(_settings_Stub.Object);
It should_set_the_LiveTrackerSettings_to_the_ones_that_were_passed = () => _sut._LiveTrackerSettings.ShouldBeTheSameAs(_settings_Stub.Object);
It should_set_the_GameController_LiveTracker_Settings_to_ones_that_were_passed
= () => _gameController_Mock.VerifySet(gc => gc.LiveTrackerSettings = _settings_Stub.Object);
It should_tell_the_new_hands_trakcer_to_track_the_HandHistory_Paths_returned_by_the_live_tracker_settings
= () => _newHandsTracker_Mock.Verify(ht => ht.TrackFolders(thePaths));
}
[Subject(typeof(GamesTracker), "LiveTrackerSettings changed")]
public class when_it_contains_one_game_controller_and_the_LiveTrackerSettings_changed : Ctx_InitializedWithLiveTrackerSettings
{
const string firstPath = "firstPath";
const string secondPath = "secondPath";
static string[] thePaths;
static Mock<ILiveTrackerSettingsViewModel> newSettings_Stub;
Establish context = () => {
_sut.GameControllers.Add("somePath", _gameController_Mock.Object);
thePaths = new[] { firstPath, secondPath };
newSettings_Stub = new Mock<ILiveTrackerSettingsViewModel>();
newSettings_Stub
.SetupGet(ls => ls.HandHistoryFilesPaths).Returns(thePaths);
};
Because of = () => _eventAggregator
.GetEvent<LiveTrackerSettingsChangedEvent>()
.Publish(newSettings_Stub.Object);
It should_set_the_LiveTrackerSettings_to_the_ones_that_were_passed = () => _sut._LiveTrackerSettings.ShouldBeTheSameAs(newSettings_Stub.Object);
It should_set_the_GameController_LiveTracker_Settings_to_the_new_ones
= () => _gameController_Mock.VerifySet(gc => gc.LiveTrackerSettings = newSettings_Stub.Object);
It should_tell_the_new_hands_tracker_to_track_the_HandHistory_Paths_returned_by_the_live_tracker_settings
= () => _newHandsTracker_Mock.Verify(ht => ht.TrackFolders(thePaths));
}
[Subject(typeof(GamesTracker), "StartTracking")]
public class when_told_to_start_tracking_a_file_that_is_tracked_already : Ctx_InitializedWithLiveTrackerSettings
{
const string directory = @"c:\someDir\";
const string filename = "someFile.txt";
const string fullPath = directory + filename;
static string userMessage;
Establish context = () => {
_sut.GameControllers.Add(fullPath, new Mock<IGameController>().Object);
_eventAggregator
.GetEvent<UserMessageEvent>()
.Subscribe(args => userMessage = args.UserMessage);
};
Because of = () => _sut.StartTracking(fullPath);
It should_not_add_the_file_to_the_GameControllers = () => _sut.GameControllers.Count.ShouldEqual(1);
It should_raise_a_user_message_containing_the_filename = () => userMessage.ShouldContain("\"" + filename + "\"");
}
[Subject(typeof(GamesTracker), "StartTracking")]
public class when_told_to_start_tracking_a_file_that_is_not_tracked_yet : Ctx_InitializedWithLiveTrackerSettings
{
const string folder = @"c:\someFolder";
const string fullPath = folder + @"\someFileName";
Because of = () => _sut.StartTracking(fullPath);
It should_add_a_GameController_for_the_full_path_of_the_file = () => _sut.GameControllers.Keys.ShouldContain(fullPath);
It should_set_the_GameController_LiveTracker_Settings_to_the_ones_passed_in
= () => _gameController_Mock.VerifySet(gc => gc.LiveTrackerSettings = _settings_Stub.Object);
It should_tell_the_NewHandsTracker_to_process_the_file = () => _newHandsTracker_Mock.Verify(ht => ht.ProcessHandHistoriesInFile(fullPath));
It should_tell_the_NewHandsTracker_to_start_tracking_the_folder_that_contains_the_file
= () => _newHandsTracker_Mock.Verify(ht => ht.TrackFolder(folder));
}
[Subject(typeof(GamesTracker), "New Hand found")]
public class when_told_that_a_new_hand_for_a_file_that_it_is_tracking_was_found : Ctx_InitializedWithLiveTrackerSettings
{
const string fullPath = "somePath";
static Mock<IConvertedPokerHand> newHand_Stub;
Establish context = () => {
newHand_Stub = new Mock<IConvertedPokerHand>();
_sut.GameControllers.Add(fullPath, _gameController_Mock.Object);
};
Because of = () => _eventAggregator
.GetEvent<NewHandEvent>()
.Publish(new NewHandEventArgs(fullPath, newHand_Stub.Object));
It should_tell_the_GameController_about_the_new_hand = () => _gameController_Mock.Verify(gc => gc.NewHand(newHand_Stub.Object));
}
[Subject(typeof(GamesTracker), "New Hand found")]
public class when_a_new_hand_was_found_and_it_is_currently_tracking_no_files_and_it_is_supposed_to_AutoTrack :
Ctx_InitializedWithLiveTrackerSettings
{
const string fullPath = "somePath";
static Mock<IConvertedPokerHand> newHand_Stub;
Establish context = () => {
newHand_Stub = new Mock<IConvertedPokerHand>();
_settings_Stub.SetupGet(s => s.AutoTrack).Returns(true);
};
Because of = () => _eventAggregator
.GetEvent<NewHandEvent>()
.Publish(new NewHandEventArgs(fullPath, newHand_Stub.Object));
It should_add_a_new_GameController_for_the_full_path = () => _sut.GameControllers.Keys.ShouldContain(fullPath);
It should_set_the_GameController_LiveTracker_Settings_to_the_ones_passed_in
= () => _gameController_Mock.VerifySet(gc => gc.LiveTrackerSettings = _settings_Stub.Object);
It should_tell_the_GameController_about_the_new_hand = () => _gameController_Mock.Verify(gc => gc.NewHand(newHand_Stub.Object));
}
[Subject(typeof(GamesTracker), "New Hand found")]
public class when_a_new_hand_was_found_and_it_is_currently_tracking_no_files_but_it_is_not_supposed_to_AutoTrack :
Ctx_InitializedWithLiveTrackerSettings
{
const string fullPath = "somePath";
static Mock<IConvertedPokerHand> newHand_Stub;
Establish context = () => {
newHand_Stub = new Mock<IConvertedPokerHand>();
_settings_Stub.SetupGet(s => s.AutoTrack).Returns(false);
};
Because of = () => _eventAggregator
.GetEvent<NewHandEvent>()
.Publish(new NewHandEventArgs(fullPath, newHand_Stub.Object));
It should_not_add_a_new_GameController_for_the_full_path = () => _sut.GameControllers.Keys.ShouldNotContain(fullPath);
}
[Subject(typeof(GamesTracker), "GameController shuts down")]
public class when_a_GameController_signals_shut_down : Ctx_InitializedWithLiveTrackerSettings
{
const string fullPath = "somePath";
Establish context = () => _sut.StartTracking(fullPath);
Because of = () => _gameController_Mock.Raise(gc => gc.ShuttingDown += null);
It should_remove_it_from_the_GameControllers = () => _sut.GameControllers.Values.ShouldNotContain(_gameController_Mock.Object);
}
}
public class GamesTrackerSut : GamesTracker
{
public GamesTrackerSut(IEventAggregator eventAggregator, INewHandsTracker newHandsTracker, IConstructor<IGameController> gameControllerMake)
: base(eventAggregator, newHandsTracker, gameControllerMake)
{
}
internal ILiveTrackerSettingsViewModel _LiveTrackerSettings
{
get { return _liveTrackerSettings; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void AsUInt16()
{
var test = new VectorAs__AsUInt16();
// Validates basic functionality works
test.RunBasicScenario();
// Validates basic functionality works using the generic form, rather than the type-specific form of the method
test.RunGenericScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorAs__AsUInt16
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Vector64<UInt16> value;
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<byte> byteResult = value.AsByte();
ValidateResult(byteResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<double> doubleResult = value.AsDouble();
ValidateResult(doubleResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<short> shortResult = value.AsInt16();
ValidateResult(shortResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<int> intResult = value.AsInt32();
ValidateResult(intResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<long> longResult = value.AsInt64();
ValidateResult(longResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<sbyte> sbyteResult = value.AsSByte();
ValidateResult(sbyteResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<float> floatResult = value.AsSingle();
ValidateResult(floatResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<ushort> ushortResult = value.AsUInt16();
ValidateResult(ushortResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<uint> uintResult = value.AsUInt32();
ValidateResult(uintResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<ulong> ulongResult = value.AsUInt64();
ValidateResult(ulongResult, value);
}
public void RunGenericScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario));
Vector64<UInt16> value;
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<byte> byteResult = value.As<UInt16, byte>();
ValidateResult(byteResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<double> doubleResult = value.As<UInt16, double>();
ValidateResult(doubleResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<short> shortResult = value.As<UInt16, short>();
ValidateResult(shortResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<int> intResult = value.As<UInt16, int>();
ValidateResult(intResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<long> longResult = value.As<UInt16, long>();
ValidateResult(longResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<sbyte> sbyteResult = value.As<UInt16, sbyte>();
ValidateResult(sbyteResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<float> floatResult = value.As<UInt16, float>();
ValidateResult(floatResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<ushort> ushortResult = value.As<UInt16, ushort>();
ValidateResult(ushortResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<uint> uintResult = value.As<UInt16, uint>();
ValidateResult(uintResult, value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
Vector64<ulong> ulongResult = value.As<UInt16, ulong>();
ValidateResult(ulongResult, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Vector64<UInt16> value;
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
object byteResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsByte))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<byte>)(byteResult), value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
object doubleResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsDouble))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<double>)(doubleResult), value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
object shortResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsInt16))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<short>)(shortResult), value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
object intResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsInt32))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<int>)(intResult), value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
object longResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsInt64))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<long>)(longResult), value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
object sbyteResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsSByte))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<sbyte>)(sbyteResult), value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
object floatResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsSingle))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<float>)(floatResult), value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
object ushortResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsUInt16))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<ushort>)(ushortResult), value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
object uintResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsUInt32))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<uint>)(uintResult), value);
value = Vector64.Create(TestLibrary.Generator.GetUInt16());
object ulongResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsUInt64))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<ulong>)(ulongResult), value);
}
private void ValidateResult<T>(Vector64<T> result, Vector64<UInt16> value, [CallerMemberName] string method = "")
where T : struct
{
UInt16[] resultElements = new UInt16[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result);
UInt16[] valueElements = new UInt16[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref valueElements[0]), value);
ValidateResult(resultElements, valueElements, typeof(T), method);
}
private void ValidateResult(UInt16[] resultElements, UInt16[] valueElements, Type targetType, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < ElementCount; i++)
{
if (resultElements[i] != valueElements[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<UInt16>.As{targetType.Name}: {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// 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.IO;
using System.Text;
using System.Globalization;
using Xunit;
namespace System.Json.Tests
{
public class JsonValueTests
{
// Facts that a trailing comma is allowed in dictionary definitions
[Fact]
public void JsonValue_Load_LoadWithTrailingComma()
{
JsonValue j = JsonValue.Load(new StringReader("{ \"a\": \"b\",}"));
Assert.Equal(1, j.Count);
Assert.Equal(JsonType.String, j["a"].JsonType);
Assert.Equal("b", j["a"]);
JsonValue.Parse("[{ \"a\": \"b\",}]");
}
// Fact that we correctly serialize JsonArray with null elements.
[Fact]
public void JsonValue_Load_ToString_JsonArrayWithNulls()
{
JsonValue j = JsonValue.Load(new StringReader("[1,2,3,null]"));
Assert.Equal(4, j.Count);
Assert.Equal(JsonType.Array, j.JsonType);
Assert.Equal("[1, 2, 3, null]", j.ToString());
}
// Fact that we correctly serialize JsonObject with null elements.
[Fact]
public void JsonValue_ToString_JsonObjectWithNulls()
{
JsonValue j = JsonValue.Load(new StringReader("{\"a\":null,\"b\":2}"));
Assert.Equal(2, j.Count);
Assert.Equal(JsonType.Object, j.JsonType);
Assert.Equal("{\"a\": null, \"b\": 2}", j.ToString());
}
[Fact]
public void JsonObject_ToString_OrderingMaintained()
{
var obj = new JsonObject();
obj["a"] = 1;
obj["c"] = 3;
obj["b"] = 2;
Assert.Equal("{\"a\": 1, \"b\": 2, \"c\": 3}", obj.ToString());
}
[Fact]
public void JsonPrimitive_QuoteEscape()
{
Assert.Equal((new JsonPrimitive("\"\"")).ToString(), "\"\\\"\\\"\"");
}
// Fact whether an exception is thrown for invalid JSON
[Theory]
[InlineData("-")]
[InlineData("- ")]
[InlineData("1.")]
[InlineData("1. ")]
[InlineData("1e+")]
[InlineData("1 2")]
[InlineData("077")]
[InlineData("[1,]")]
[InlineData("NaN")]
[InlineData("Infinity")]
[InlineData("-Infinity")]
public void JsonValue_Parse_InvalidInput_ThrowsArgumentException(string value)
{
Assert.Throws<ArgumentException>(() => JsonValue.Parse(value));
}
// Parse a json string and compare to the expected value
[Theory]
[InlineData(0, "0")]
[InlineData(0, "-0")]
[InlineData(0, "0.00")]
[InlineData(0, "-0.00")]
[InlineData(1, "1")]
[InlineData(1.1, "1.1")]
[InlineData(-1, "-1")]
[InlineData(-1.1, "-1.1")]
[InlineData(1e-10, "1e-10")]
[InlineData(1e+10, "1e+10")]
[InlineData(1e-30, "1e-30")]
[InlineData(1e+30, "1e+30")]
[InlineData(1, "\"1\"")]
[InlineData(1.1, "\"1.1\"")]
[InlineData(-1, "\"-1\"")]
[InlineData(-1.1, "\"-1.1\"")]
[InlineData(double.NaN, "\"NaN\"")]
[InlineData(double.PositiveInfinity, "\"Infinity\"")]
[InlineData(double.NegativeInfinity, "\"-Infinity\"")]
[InlineData(1.1E-29, "0.000000000000000000000000000011")]
public void JsonValue_Parse_Double(double expected, string json)
{
foreach (string culture in new[] { "en", "fr", "de" })
{
CultureInfo old = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = new CultureInfo(culture);
Assert.Equal(expected, (double)JsonValue.Parse(json));
}
finally
{
CultureInfo.CurrentCulture = old;
}
}
}
// Convert a number to json and parse the string, then compare the result to the original value
[Theory]
[InlineData(1)]
[InlineData(1.1)]
[InlineData(1.25)]
[InlineData(-1)]
[InlineData(-1.1)]
[InlineData(-1.25)]
[InlineData(1e-20)]
[InlineData(1e+20)]
[InlineData(1e-30)]
[InlineData(1e+30)]
[InlineData(3.1415926535897932384626433)]
[InlineData(3.1415926535897932384626433e-20)]
[InlineData(3.1415926535897932384626433e+20)]
[InlineData(double.NaN)]
[InlineData(double.PositiveInfinity)]
[InlineData(double.NegativeInfinity)]
[InlineData(double.MinValue)]
[InlineData(double.MaxValue)]
[InlineData(18014398509481982.0)] // A number which needs 17 digits (see http://stackoverflow.com/questions/6118231/why-do-i-need-17-significant-digits-and-not-16-to-represent-a-double)
[InlineData(1.123456789e-29)]
[InlineData(1.123456789e-28)] // Values around the smallest positive decimal value
public void JsonValue_Parse_Double_ViaJsonPrimitive(double number)
{
foreach (string culture in new[] { "en", "fr", "de" })
{
CultureInfo old = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = new CultureInfo(culture);
Assert.Equal(number, (double)JsonValue.Parse(new JsonPrimitive(number).ToString()));
}
finally
{
CultureInfo.CurrentCulture = old;
}
}
}
[Fact]
public void JsonValue_Parse_MinMax_Integers_ViaJsonPrimitive()
{
Assert.Equal(sbyte.MinValue, (sbyte)JsonValue.Parse(new JsonPrimitive(sbyte.MinValue).ToString()));
Assert.Equal(sbyte.MaxValue, (sbyte)JsonValue.Parse(new JsonPrimitive(sbyte.MaxValue).ToString()));
Assert.Equal(byte.MinValue, (byte)JsonValue.Parse(new JsonPrimitive(byte.MinValue).ToString()));
Assert.Equal(byte.MaxValue, (byte)JsonValue.Parse(new JsonPrimitive(byte.MaxValue).ToString()));
Assert.Equal(short.MinValue, (short)JsonValue.Parse(new JsonPrimitive(short.MinValue).ToString()));
Assert.Equal(short.MaxValue, (short)JsonValue.Parse(new JsonPrimitive(short.MaxValue).ToString()));
Assert.Equal(ushort.MinValue, (ushort)JsonValue.Parse(new JsonPrimitive(ushort.MinValue).ToString()));
Assert.Equal(ushort.MaxValue, (ushort)JsonValue.Parse(new JsonPrimitive(ushort.MaxValue).ToString()));
Assert.Equal(int.MinValue, (int)JsonValue.Parse(new JsonPrimitive(int.MinValue).ToString()));
Assert.Equal(int.MaxValue, (int)JsonValue.Parse(new JsonPrimitive(int.MaxValue).ToString()));
Assert.Equal(uint.MinValue, (uint)JsonValue.Parse(new JsonPrimitive(uint.MinValue).ToString()));
Assert.Equal(uint.MaxValue, (uint)JsonValue.Parse(new JsonPrimitive(uint.MaxValue).ToString()));
Assert.Equal(long.MinValue, (long)JsonValue.Parse(new JsonPrimitive(long.MinValue).ToString()));
Assert.Equal(long.MaxValue, (long)JsonValue.Parse(new JsonPrimitive(long.MaxValue).ToString()));
Assert.Equal(ulong.MinValue, (ulong)JsonValue.Parse(new JsonPrimitive(ulong.MinValue).ToString()));
Assert.Equal(ulong.MaxValue, (ulong)JsonValue.Parse(new JsonPrimitive(ulong.MaxValue).ToString()));
}
[Fact]
public void JsonPrimitive_ToString()
{
Assert.Equal("1.1", new JsonPrimitive(1.1).ToString());
Assert.Equal("-1.1", new JsonPrimitive(-1.1).ToString());
Assert.Equal("1E-20", new JsonPrimitive(1e-20).ToString());
Assert.Equal("1E+20", new JsonPrimitive(1e+20).ToString());
Assert.Equal("1E-30", new JsonPrimitive(1e-30).ToString());
Assert.Equal("1E+30", new JsonPrimitive(1e+30).ToString());
Assert.Equal("\"NaN\"", new JsonPrimitive(double.NaN).ToString());
Assert.Equal("\"Infinity\"", new JsonPrimitive(double.PositiveInfinity).ToString());
Assert.Equal("\"-Infinity\"", new JsonPrimitive(double.NegativeInfinity).ToString());
Assert.Equal("1E-30", JsonValue.Parse("1e-30").ToString());
Assert.Equal("1E+30", JsonValue.Parse("1e+30").ToString());
}
// Convert a string to json and parse the string, then compare the result to the original value
[Theory]
[InlineData("Fact\b\f\n\r\t\"\\/</\0x")]
[InlineData("\ud800")]
[InlineData("x\ud800")]
[InlineData("\udfff\ud800")]
[InlineData("\ude03\ud912")]
[InlineData("\uc000\ubfff")]
[InlineData("\udfffx")]
public void JsonPrimitive_Roundtrip_ValidUnicode(string str)
{
string json = new JsonPrimitive(str).ToString();
new UTF8Encoding(false, true).GetBytes(json);
Assert.Equal(str, JsonValue.Parse(json));
}
[Fact]
public void JsonPrimitive_Roundtrip_ValidUnicode_AllChars()
{
for (int i = 0; i <= char.MaxValue; i++)
{
JsonPrimitive_Roundtrip_ValidUnicode("x" + (char)i);
}
}
// String handling: http://tools.ietf.org/html/rfc7159#section-7
[Fact]
public void JsonPrimitive_StringHandling()
{
Assert.Equal("\"Fact\"", new JsonPrimitive("Fact").ToString());
// Handling of characters
Assert.Equal("\"f\"", new JsonPrimitive('f').ToString());
Assert.Equal('f', (char)JsonValue.Parse("\"f\""));
// Control characters with special escape sequence
Assert.Equal("\"\\b\\f\\n\\r\\t\"", new JsonPrimitive("\b\f\n\r\t").ToString());
// Other characters which must be escaped
Assert.Equal(@"""\""\\""", new JsonPrimitive("\"\\").ToString());
// Control characters without special escape sequence
for (int i = 0; i < 32; i++)
{
if (i != '\b' && i != '\f' && i != '\n' && i != '\r' && i != '\t')
{
Assert.Equal("\"\\u" + i.ToString("x04") + "\"", new JsonPrimitive("" + (char)i).ToString());
}
}
// JSON does not require U+2028 and U+2029 to be escaped, but
// JavaScript does require this:
// http://stackoverflow.com/questions/2965293/javascript-parse-error-on-u2028-unicode-character/9168133#9168133
Assert.Equal("\"\\u2028\\u2029\"", new JsonPrimitive("\u2028\u2029").ToString());
// '/' also does not have to be escaped, but escaping it when
// preceeded by a '<' avoids problems with JSON in HTML <script> tags
Assert.Equal("\"<\\/\"", new JsonPrimitive("</").ToString());
// Don't escape '/' in other cases as this makes the JSON hard to read
Assert.Equal("\"/bar\"", new JsonPrimitive("/bar").ToString());
Assert.Equal("\"foo/bar\"", new JsonPrimitive("foo/bar").ToString());
// Valid strings should not be escaped:
Assert.Equal("\"\ud7ff\"", new JsonPrimitive("\ud7ff").ToString());
Assert.Equal("\"\ue000\"", new JsonPrimitive("\ue000").ToString());
Assert.Equal("\"\ud800\udc00\"", new JsonPrimitive("\ud800\udc00").ToString());
Assert.Equal("\"\ud912\ude03\"", new JsonPrimitive("\ud912\ude03").ToString());
Assert.Equal("\"\udbff\udfff\"", new JsonPrimitive("\udbff\udfff").ToString());
}
}
}
| |
// <copyright file="WebDriverCommandProcessor.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.Collections.Generic;
using System.Globalization;
using OpenQA.Selenium;
using Selenium.Internal;
using Selenium.Internal.SeleniumEmulation;
namespace Selenium
{
/// <summary>
/// Provides an implementation the ICommandProcessor interface which uses WebDriver to complete
/// the Selenium commands.
/// </summary>
public class WebDriverCommandProcessor : ICommandProcessor
{
#region Private members
private IWebDriver driver;
private Uri baseUrl;
private Dictionary<string, SeleneseCommand> seleneseMethods = new Dictionary<string, SeleneseCommand>();
private ElementFinder elementFinder = new ElementFinder();
private CommandTimer timer;
private AlertOverride alertOverride;
private IScriptMutator mutator;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="WebDriverCommandProcessor"/> class.
/// </summary>
/// <param name="baseUrl">The base URL of the Selenium server.</param>
/// <param name="baseDriver">The IWebDriver object used for executing commands.</param>
public WebDriverCommandProcessor(string baseUrl, IWebDriver baseDriver)
: this(new Uri(baseUrl), baseDriver)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebDriverCommandProcessor"/> class.
/// </summary>
/// <param name="baseUrl">The base URL of the Selenium server.</param>
/// <param name="baseDriver">The IWebDriver object used for executing commands.</param>
public WebDriverCommandProcessor(Uri baseUrl, IWebDriver baseDriver)
{
if (baseUrl == null)
{
throw new ArgumentNullException(nameof(baseUrl), "baseUrl cannot be null");
}
this.driver = baseDriver;
this.baseUrl = baseUrl;
this.mutator = new CompoundMutator(baseUrl.ToString());
this.timer = new CommandTimer(30000);
this.alertOverride = new AlertOverride(baseDriver);
}
/// <summary>
/// Gets the <see cref="IWebDriver"/> object that executes the commands for this command processor.
/// </summary>
public IWebDriver UnderlyingWebDriver
{
get { return this.driver; }
}
/// <summary>
/// Sends the specified remote command to the browser to be performed
/// </summary>
/// <param name="command">The remote command verb.</param>
/// <param name="args">The arguments to the remote command (depends on the verb).</param>
/// <returns>the command result, defined by the remote JavaScript. "getX" style
/// commands may return data from the browser</returns>
public string DoCommand(string command, string[] args)
{
object val = this.Execute(command, args);
if (val == null)
{
return null;
}
return val.ToString();
}
/// <summary>
/// Sets the script to use as user extensions.
/// </summary>
/// <param name="extensionJs">The script to use as user extensions.</param>
public void SetExtensionJs(string extensionJs)
{
throw new NotImplementedException();
}
/// <summary>
/// Starts the command processor.
/// </summary>
public void Start()
{
this.PopulateSeleneseMethods();
}
/// <summary>
/// Starts the command processor using the specified options.
/// </summary>
/// <param name="optionsString">A string representing the options to use.</param>
public void Start(string optionsString)
{
// Not porting this till other process is decided
throw new NotImplementedException("This is not been ported to WebDriverBackedSelenium");
}
/// <summary>
/// Starts the command processor using the specified options.
/// </summary>
/// <param name="optionsObject">An object representing the options to use.</param>
public void Start(object optionsObject)
{
// Not porting this till other process is decided
throw new NotImplementedException("This is not been ported to WebDriverBackedSelenium");
}
/// <summary>
/// Stops the command processor.
/// </summary>
public void Stop()
{
if (this.driver != null)
{
this.driver.Quit();
}
this.driver = null;
}
/// <summary>
/// Gets a string from the command processor.
/// </summary>
/// <param name="command">The command to send.</param>
/// <param name="args">The arguments of the command.</param>
/// <returns>The result of the command.</returns>
public string GetString(string command, string[] args)
{
return (string)this.Execute(command, args);
}
/// <summary>
/// Gets a string array from the command processor.
/// </summary>
/// <param name="command">The command to send.</param>
/// <param name="args">The arguments of the command.</param>
/// <returns>The result of the command.</returns>
public string[] GetStringArray(string command, string[] args)
{
return (string[])this.Execute(command, args);
}
/// <summary>
/// Gets a number from the command processor.
/// </summary>
/// <param name="command">The command to send.</param>
/// <param name="args">The arguments of the command.</param>
/// <returns>The result of the command.</returns>
public decimal GetNumber(string command, string[] args)
{
return Convert.ToDecimal(this.Execute(command, args), CultureInfo.InvariantCulture);
}
/// <summary>
/// Gets a number array from the command processor.
/// </summary>
/// <param name="command">The command to send.</param>
/// <param name="args">The arguments of the command.</param>
/// <returns>The result of the command.</returns>
public decimal[] GetNumberArray(string command, string[] args)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets a boolean value from the command processor.
/// </summary>
/// <param name="command">The command to send.</param>
/// <param name="args">The arguments of the command.</param>
/// <returns>The result of the command.</returns>
public bool GetBoolean(string command, string[] args)
{
return (bool)this.Execute(command, args);
}
/// <summary>
/// Gets an array of boolean values from the command processor.
/// </summary>
/// <param name="command">The command to send.</param>
/// <param name="args">The arguments of the command.</param>
/// <returns>The result of the command.</returns>
public bool[] GetBooleanArray(string command, string[] args)
{
throw new NotImplementedException();
}
private object Execute(string commandName, string[] args)
{
SeleneseCommand command;
if (!this.seleneseMethods.TryGetValue(commandName, out command))
{
if (this.seleneseMethods.Count == 0)
{
throw new NotSupportedException(commandName + " is not supported\n" +
"Note: Start() must be called before any other methods may be called - make sure you've called Start().");
}
throw new NotSupportedException(commandName);
}
// return command.Apply(driver, args);
return this.timer.Execute(command, this.driver, args);
}
private void PopulateSeleneseMethods()
{
KeyState keyState = new KeyState();
WindowSelector windows = new WindowSelector(this.driver);
// Note the we use the names used by the CommandProcessor
this.seleneseMethods.Add("addLocationStrategy", new AddLocationStrategy(this.elementFinder));
this.seleneseMethods.Add("addSelection", new AddSelection(this.elementFinder));
this.seleneseMethods.Add("altKeyDown", new AltKeyDown(keyState));
this.seleneseMethods.Add("altKeyUp", new AltKeyUp(keyState));
this.seleneseMethods.Add("assignId", new AssignId(this.elementFinder));
this.seleneseMethods.Add("attachFile", new AttachFile(this.elementFinder));
this.seleneseMethods.Add("captureScreenshotToString", new CaptureScreenshotToString());
this.seleneseMethods.Add("click", new Click(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("clickAt", new ClickAt(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("check", new Check(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("chooseCancelOnNextConfirmation", new SetNextConfirmationState(false));
this.seleneseMethods.Add("chooseOkOnNextConfirmation", new SetNextConfirmationState(true));
this.seleneseMethods.Add("close", new Close());
this.seleneseMethods.Add("createCookie", new CreateCookie());
this.seleneseMethods.Add("controlKeyDown", new ControlKeyDown(keyState));
this.seleneseMethods.Add("controlKeyUp", new ControlKeyUp(keyState));
this.seleneseMethods.Add("deleteAllVisibleCookies", new DeleteAllVisibleCookies());
this.seleneseMethods.Add("deleteCookie", new DeleteCookie());
this.seleneseMethods.Add("doubleClick", new DoubleClick(this.elementFinder));
this.seleneseMethods.Add("dragdrop", new DragAndDrop(this.elementFinder));
this.seleneseMethods.Add("dragAndDrop", new DragAndDrop(this.elementFinder));
this.seleneseMethods.Add("dragAndDropToObject", new DragAndDropToObject(this.elementFinder));
this.seleneseMethods.Add("fireEvent", new FireEvent(this.elementFinder));
this.seleneseMethods.Add("focus", new FireNamedEvent(this.elementFinder, "focus"));
this.seleneseMethods.Add("getAlert", new GetAlert(this.alertOverride));
this.seleneseMethods.Add("getAllButtons", new GetAllButtons());
this.seleneseMethods.Add("getAllFields", new GetAllFields());
this.seleneseMethods.Add("getAllLinks", new GetAllLinks());
this.seleneseMethods.Add("getAllWindowTitles", new GetAllWindowTitles());
this.seleneseMethods.Add("getAttribute", new GetAttribute(this.elementFinder));
this.seleneseMethods.Add("getAttributeFromAllWindows", new GetAttributeFromAllWindows());
this.seleneseMethods.Add("getBodyText", new GetBodyText());
this.seleneseMethods.Add("getConfirmation", new GetConfirmation(this.alertOverride));
this.seleneseMethods.Add("getCookie", new GetCookie());
this.seleneseMethods.Add("getCookieByName", new GetCookieByName());
this.seleneseMethods.Add("getElementHeight", new GetElementHeight(this.elementFinder));
this.seleneseMethods.Add("getElementIndex", new GetElementIndex(this.elementFinder));
this.seleneseMethods.Add("getElementPositionLeft", new GetElementPositionLeft(this.elementFinder));
this.seleneseMethods.Add("getElementPositionTop", new GetElementPositionTop(this.elementFinder));
this.seleneseMethods.Add("getElementWidth", new GetElementWidth(this.elementFinder));
this.seleneseMethods.Add("getEval", new GetEval(this.mutator));
this.seleneseMethods.Add("getHtmlSource", new GetHtmlSource());
this.seleneseMethods.Add("getLocation", new GetLocation());
this.seleneseMethods.Add("getSelectedId", new FindFirstSelectedOptionProperty(this.elementFinder, "id"));
this.seleneseMethods.Add("getSelectedIds", new FindSelectedOptionProperties(this.elementFinder, "id"));
this.seleneseMethods.Add("getSelectedIndex", new FindFirstSelectedOptionProperty(this.elementFinder, "index"));
this.seleneseMethods.Add("getSelectedIndexes", new FindSelectedOptionProperties(this.elementFinder, "index"));
this.seleneseMethods.Add("getSelectedLabel", new FindFirstSelectedOptionProperty(this.elementFinder, "text"));
this.seleneseMethods.Add("getSelectedLabels", new FindSelectedOptionProperties(this.elementFinder, "text"));
this.seleneseMethods.Add("getSelectedValue", new FindFirstSelectedOptionProperty(this.elementFinder, "value"));
this.seleneseMethods.Add("getSelectedValues", new FindSelectedOptionProperties(this.elementFinder, "value"));
this.seleneseMethods.Add("getSelectOptions", new GetSelectOptions(this.elementFinder));
this.seleneseMethods.Add("getSpeed", new NoOp("0"));
this.seleneseMethods.Add("getTable", new GetTable(this.elementFinder));
this.seleneseMethods.Add("getText", new GetText(this.elementFinder));
this.seleneseMethods.Add("getTitle", new GetTitle());
this.seleneseMethods.Add("getValue", new GetValue(this.elementFinder));
this.seleneseMethods.Add("getXpathCount", new GetXpathCount());
this.seleneseMethods.Add("getCssCount", new GetCssCount());
this.seleneseMethods.Add("goBack", new GoBack());
this.seleneseMethods.Add("highlight", new Highlight(this.elementFinder));
this.seleneseMethods.Add("isAlertPresent", new IsAlertPresent(this.alertOverride));
this.seleneseMethods.Add("isChecked", new IsChecked(this.elementFinder));
this.seleneseMethods.Add("isConfirmationPresent", new IsConfirmationPresent(this.alertOverride));
this.seleneseMethods.Add("isCookiePresent", new IsCookiePresent());
this.seleneseMethods.Add("isEditable", new IsEditable(this.elementFinder));
this.seleneseMethods.Add("isElementPresent", new IsElementPresent(this.elementFinder));
this.seleneseMethods.Add("isOrdered", new IsOrdered(this.elementFinder));
this.seleneseMethods.Add("isSomethingSelected", new IsSomethingSelected());
this.seleneseMethods.Add("isTextPresent", new IsTextPresent());
this.seleneseMethods.Add("isVisible", new IsVisible(this.elementFinder));
this.seleneseMethods.Add("keyDown", new KeyEvent(this.elementFinder, keyState, "doKeyDown"));
this.seleneseMethods.Add("keyPress", new TypeKeys(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("keyUp", new KeyEvent(this.elementFinder, keyState, "doKeyUp"));
this.seleneseMethods.Add("metaKeyDown", new MetaKeyDown(keyState));
this.seleneseMethods.Add("metaKeyUp", new MetaKeyUp(keyState));
this.seleneseMethods.Add("mouseOver", new MouseEvent(this.elementFinder, "mouseover"));
this.seleneseMethods.Add("mouseOut", new MouseEvent(this.elementFinder, "mouseout"));
this.seleneseMethods.Add("mouseDown", new MouseEvent(this.elementFinder, "mousedown"));
this.seleneseMethods.Add("mouseDownAt", new MouseEventAt(this.elementFinder, "mousedown"));
this.seleneseMethods.Add("mouseMove", new MouseEvent(this.elementFinder, "mousemove"));
this.seleneseMethods.Add("mouseMoveAt", new MouseEventAt(this.elementFinder, "mousemove"));
this.seleneseMethods.Add("mouseUp", new MouseEvent(this.elementFinder, "mouseup"));
this.seleneseMethods.Add("mouseUpAt", new MouseEventAt(this.elementFinder, "mouseup"));
this.seleneseMethods.Add("open", new Open(this.baseUrl));
this.seleneseMethods.Add("openWindow", new OpenWindow(new GetEval(this.mutator)));
this.seleneseMethods.Add("refresh", new Refresh());
this.seleneseMethods.Add("removeAllSelections", new RemoveAllSelections(this.elementFinder));
this.seleneseMethods.Add("removeSelection", new RemoveSelection(this.elementFinder));
this.seleneseMethods.Add("runScript", new RunScript(this.mutator));
this.seleneseMethods.Add("select", new SelectOption(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("selectFrame", new SelectFrame(windows));
this.seleneseMethods.Add("selectWindow", new SelectWindow(windows));
this.seleneseMethods.Add("setBrowserLogLevel", new NoOp(null));
this.seleneseMethods.Add("setContext", new NoOp(null));
this.seleneseMethods.Add("setSpeed", new NoOp(null));
this.seleneseMethods.Add("setTimeout", new SetTimeout(this.timer));
this.seleneseMethods.Add("shiftKeyDown", new ShiftKeyDown(keyState));
this.seleneseMethods.Add("shiftKeyUp", new ShiftKeyUp(keyState));
this.seleneseMethods.Add("submit", new Submit(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("type", new Selenium.Internal.SeleniumEmulation.Type(this.alertOverride, this.elementFinder, keyState));
this.seleneseMethods.Add("typeKeys", new TypeKeys(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("uncheck", new Uncheck(this.elementFinder));
this.seleneseMethods.Add("useXpathLibrary", new NoOp(null));
this.seleneseMethods.Add("waitForCondition", new WaitForCondition(this.mutator));
this.seleneseMethods.Add("waitForFrameToLoad", new NoOp(null));
this.seleneseMethods.Add("waitForPageToLoad", new WaitForPageToLoad());
this.seleneseMethods.Add("waitForPopUp", new WaitForPopup(windows));
this.seleneseMethods.Add("windowFocus", new WindowFocus());
this.seleneseMethods.Add("windowMaximize", new WindowMaximize());
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Networking/Requests/Messages/MarkTutorialCompleteMessage.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 POGOProtos.Networking.Requests.Messages {
/// <summary>Holder for reflection information generated from POGOProtos/Networking/Requests/Messages/MarkTutorialCompleteMessage.proto</summary>
public static partial class MarkTutorialCompleteMessageReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Networking/Requests/Messages/MarkTutorialCompleteMessage.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static MarkTutorialCompleteMessageReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CklQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVxdWVzdHMvTWVzc2FnZXMvTWFy",
"a1R1dG9yaWFsQ29tcGxldGVNZXNzYWdlLnByb3RvEidQT0dPUHJvdG9zLk5l",
"dHdvcmtpbmcuUmVxdWVzdHMuTWVzc2FnZXMaJFBPR09Qcm90b3MvRW51bXMv",
"VHV0b3JpYWxTdGF0ZS5wcm90byKbAQobTWFya1R1dG9yaWFsQ29tcGxldGVN",
"ZXNzYWdlEjwKE3R1dG9yaWFsc19jb21wbGV0ZWQYASADKA4yHy5QT0dPUHJv",
"dG9zLkVudW1zLlR1dG9yaWFsU3RhdGUSHQoVc2VuZF9tYXJrZXRpbmdfZW1h",
"aWxzGAIgASgIEh8KF3NlbmRfcHVzaF9ub3RpZmljYXRpb25zGAMgASgIYgZw",
"cm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Enums.TutorialStateReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Requests.Messages.MarkTutorialCompleteMessage), global::POGOProtos.Networking.Requests.Messages.MarkTutorialCompleteMessage.Parser, new[]{ "TutorialsCompleted", "SendMarketingEmails", "SendPushNotifications" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class MarkTutorialCompleteMessage : pb::IMessage<MarkTutorialCompleteMessage> {
private static readonly pb::MessageParser<MarkTutorialCompleteMessage> _parser = new pb::MessageParser<MarkTutorialCompleteMessage>(() => new MarkTutorialCompleteMessage());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<MarkTutorialCompleteMessage> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Networking.Requests.Messages.MarkTutorialCompleteMessageReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MarkTutorialCompleteMessage() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MarkTutorialCompleteMessage(MarkTutorialCompleteMessage other) : this() {
tutorialsCompleted_ = other.tutorialsCompleted_.Clone();
sendMarketingEmails_ = other.sendMarketingEmails_;
sendPushNotifications_ = other.sendPushNotifications_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MarkTutorialCompleteMessage Clone() {
return new MarkTutorialCompleteMessage(this);
}
/// <summary>Field number for the "tutorials_completed" field.</summary>
public const int TutorialsCompletedFieldNumber = 1;
private static readonly pb::FieldCodec<global::POGOProtos.Enums.TutorialState> _repeated_tutorialsCompleted_codec
= pb::FieldCodec.ForEnum(10, x => (int) x, x => (global::POGOProtos.Enums.TutorialState) x);
private readonly pbc::RepeatedField<global::POGOProtos.Enums.TutorialState> tutorialsCompleted_ = new pbc::RepeatedField<global::POGOProtos.Enums.TutorialState>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::POGOProtos.Enums.TutorialState> TutorialsCompleted {
get { return tutorialsCompleted_; }
}
/// <summary>Field number for the "send_marketing_emails" field.</summary>
public const int SendMarketingEmailsFieldNumber = 2;
private bool sendMarketingEmails_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool SendMarketingEmails {
get { return sendMarketingEmails_; }
set {
sendMarketingEmails_ = value;
}
}
/// <summary>Field number for the "send_push_notifications" field.</summary>
public const int SendPushNotificationsFieldNumber = 3;
private bool sendPushNotifications_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool SendPushNotifications {
get { return sendPushNotifications_; }
set {
sendPushNotifications_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as MarkTutorialCompleteMessage);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(MarkTutorialCompleteMessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!tutorialsCompleted_.Equals(other.tutorialsCompleted_)) return false;
if (SendMarketingEmails != other.SendMarketingEmails) return false;
if (SendPushNotifications != other.SendPushNotifications) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= tutorialsCompleted_.GetHashCode();
if (SendMarketingEmails != false) hash ^= SendMarketingEmails.GetHashCode();
if (SendPushNotifications != false) hash ^= SendPushNotifications.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) {
tutorialsCompleted_.WriteTo(output, _repeated_tutorialsCompleted_codec);
if (SendMarketingEmails != false) {
output.WriteRawTag(16);
output.WriteBool(SendMarketingEmails);
}
if (SendPushNotifications != false) {
output.WriteRawTag(24);
output.WriteBool(SendPushNotifications);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += tutorialsCompleted_.CalculateSize(_repeated_tutorialsCompleted_codec);
if (SendMarketingEmails != false) {
size += 1 + 1;
}
if (SendPushNotifications != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(MarkTutorialCompleteMessage other) {
if (other == null) {
return;
}
tutorialsCompleted_.Add(other.tutorialsCompleted_);
if (other.SendMarketingEmails != false) {
SendMarketingEmails = other.SendMarketingEmails;
}
if (other.SendPushNotifications != false) {
SendPushNotifications = other.SendPushNotifications;
}
}
[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:
case 8: {
tutorialsCompleted_.AddEntriesFrom(input, _repeated_tutorialsCompleted_codec);
break;
}
case 16: {
SendMarketingEmails = input.ReadBool();
break;
}
case 24: {
SendPushNotifications = input.ReadBool();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
#region License
// Copyright 2013-2014 Matthew Ducker
//
// 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;
namespace Obscur.Core.Cryptography.Authentication
{
/// <summary>
/// Base class for MAC function implementations.
/// </summary>
public abstract class MacEngine : IMac
{
/// <summary>
/// Type of MAC function, as-per the <see cref="MacFunction" /> enumeration.
/// </summary>
protected readonly MacFunction MacIdentity;
/// <summary>
/// If MAC function has been initialised.
/// </summary>
protected bool IsInitialised;
/// <summary>
/// Key for the MAC function.
/// </summary>
protected byte[] Key;
/// <summary>
/// Instantiate a new MAC function engine.
/// </summary>
/// <param name="macIdentity">Identity of the MAC function.</param>
protected MacEngine(MacFunction macIdentity)
{
MacIdentity = macIdentity;
Key = null;
}
/// <summary>
/// Display-friendly name of the MAC function.
/// </summary>
/// <value>The display name of the MAC function.</value>
public virtual string DisplayName
{
get { return Athena.Cryptography.MacFunctions[MacIdentity].DisplayName; }
}
/// <summary>
/// The size of operation in bytes the MAC function implements internally, e.g. block buffer.
/// </summary>
/// <value>The size of the internal operation in bytes.</value>
public abstract int StateSize { get; }
#region IMac Members
/// <summary>
/// The name of the MAC function algorithm,
/// including any configuration-specific identifiers.
/// </summary>
public virtual string AlgorithmName
{
get { return MacIdentity.ToString(); }
}
/// <summary>
/// Size of output in bytes that the MAC function emits upon finalisation.
/// </summary>
public virtual int OutputSize
{
get { return Athena.Cryptography.MacFunctions[MacIdentity].OutputSize ?? 0; }
}
/// <summary>
/// Enumerated identity of the MAC function.
/// </summary>
public MacFunction Identity
{
get { return MacIdentity; }
}
/// <summary>
/// Set the initial state of the MAC function. Required before other use.
/// </summary>
/// <param name="key">Key for the MAC function.</param>
/// <exception cref="ArgumentException">
/// If the parameter argument is invalid (e.g. incorrect length).
/// </exception>
public virtual void Init(byte[] key)
{
if (key == null) {
throw new ArgumentNullException("key", AlgorithmName + " initialisation requires a key.");
}
int? correctKeySize = Athena.Cryptography.MacFunctions[MacIdentity].OutputSize;
if (correctKeySize.HasValue) {
if (key.Length.BytesToBits() != correctKeySize) {
throw new ArgumentException(AlgorithmName + " does not support a " + key.Length + " byte key.");
}
}
this.Key = key;
this.IsInitialised = true;
InitState();
}
/// <summary>
/// Update the internal state of the MAC function with a single byte.
/// </summary>
/// <param name="input">Byte to input.</param>
/// <exception cref="InvalidOperationException">The MAC function is not initialised.</exception>
public void Update(byte input)
{
if (IsInitialised == false) {
throw new InvalidOperationException(AlgorithmName + " not initialised.");
}
UpdateInternal(input);
}
/// <summary>
/// Update the internal state of the MAC function with a chunk of bytes.
/// </summary>
/// <param name="input">The array containing the input.</param>
/// <param name="inOff">The offset in <paramref name="input" /> that the input begins at.</param>
/// <param name="length">The length of the input starting at <paramref name="inOff" />.</param>
/// <exception cref="InvalidOperationException">The MAC function is not initialised.</exception>
/// <exception cref="ArgumentOutOfRangeException">An input parameter is out of range (e.g. offset or length is under 0).</exception>
/// <exception cref="DataLengthException">
/// A input or output buffer is of insufficient length.
/// </exception>
public void BlockUpdate(byte[] input, int inOff, int length)
{
if (IsInitialised == false) {
throw new InvalidOperationException(AlgorithmName + " not initialised.");
}
if (input == null) {
throw new ArgumentNullException("input");
}
if (inOff < 0) {
throw new ArgumentOutOfRangeException("inOff");
}
if (length < 0) {
throw new ArgumentOutOfRangeException("length");
}
if ((inOff + length) > input.Length) {
throw new DataLengthException("Input buffer too short.");
}
if (length < 1) {
return;
}
BlockUpdateInternal(input, inOff, length);
}
/// <summary>
/// Compute and output the final state, and reset the internal state of the MAC function.
/// </summary>
/// <param name="output">Array that the MAC is to be output to.</param>
/// <param name="outOff">
/// The offset into <paramref name="output" /> that the output is to start at.
/// </param>
/// <exception cref="InvalidOperationException">The MAC function is not initialised.</exception>
/// <exception cref="ArgumentOutOfRangeException">An input parameter is out of range (e.g. offset is under 0).</exception>
/// <exception cref="DataLengthException">
/// A input or output buffer is of insufficient length.
/// </exception>
/// <returns>Size of the output in bytes.</returns>
public int DoFinal(byte[] output, int outOff)
{
if (IsInitialised == false) {
throw new InvalidOperationException(AlgorithmName + " not initialised.");
}
if (output == null) {
throw new ArgumentNullException("output");
}
if (outOff < 0) {
throw new ArgumentOutOfRangeException("outOff");
}
if ((outOff + OutputSize) > output.Length) {
throw new DataLengthException("Output buffer too short.");
}
return DoFinalInternal(output, outOff);
}
/// <summary>
/// Reset the MAC function to the same state as it was after the last init (if there was one).
/// </summary>
public abstract void Reset();
#endregion
/// <summary>
/// Update the internal state of the MAC function with a single byte.
/// Performs no checks on state validity - use only when pre-validated!
/// </summary>
/// <param name="input">Byte to input.</param>
protected internal abstract void UpdateInternal(byte input);
/// <summary>
/// Set up MAC function's internal state.
/// </summary>
protected abstract void InitState();
/// <summary>
/// Process bytes from <paramref name="input" />.
/// Performs no checks on argument or state validity - use only when pre-validated!
/// </summary>
/// <param name="input">The input byte array.</param>
/// <param name="inOff">
/// The offset in <paramref name="input" /> at which the input data begins.
/// </param>
/// <param name="length">The number of bytes to be processed.</param>
protected internal abstract void BlockUpdateInternal(byte[] input, int inOff, int length);
/// <summary>
/// Compute and output the final state, and reset the internal state of the MAC function.
/// Performs no checks on argument or state validity - use only when pre-validated!
/// </summary>
/// <param name="output">Array that the MAC is to be output to.</param>
/// <param name="outOff">
/// The offset into <paramref name="output" /> that the output is to start at.
/// </param>
/// <returns>Size of the output in bytes.</returns>
protected internal abstract int DoFinalInternal(byte[] output, int outOff);
}
}
| |
/*
* 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.Reflection;
using System.Timers;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
namespace OpenSim.Groups
{
public class GroupsService : GroupsServiceBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const GroupPowers DefaultEveryonePowers = GroupPowers.AllowSetHome |
GroupPowers.Accountable |
GroupPowers.JoinChat |
GroupPowers.AllowVoiceChat |
GroupPowers.ReceiveNotices |
GroupPowers.StartProposal |
GroupPowers.VoteOnProposal;
public const GroupPowers OwnerPowers = GroupPowers.Accountable |
GroupPowers.AllowEditLand |
GroupPowers.AllowFly |
GroupPowers.AllowLandmark |
GroupPowers.AllowRez |
GroupPowers.AllowSetHome |
GroupPowers.AllowVoiceChat |
GroupPowers.AssignMember |
GroupPowers.AssignMemberLimited |
GroupPowers.ChangeActions |
GroupPowers.ChangeIdentity |
GroupPowers.ChangeMedia |
GroupPowers.ChangeOptions |
GroupPowers.CreateRole |
GroupPowers.DeedObject |
GroupPowers.DeleteRole |
GroupPowers.Eject |
GroupPowers.FindPlaces |
GroupPowers.Invite |
GroupPowers.JoinChat |
GroupPowers.LandChangeIdentity |
GroupPowers.LandDeed |
GroupPowers.LandDivideJoin |
GroupPowers.LandEdit |
GroupPowers.LandEjectAndFreeze |
GroupPowers.LandGardening |
GroupPowers.LandManageAllowed |
GroupPowers.LandManageBanned |
GroupPowers.LandManagePasses |
GroupPowers.LandOptions |
GroupPowers.LandRelease |
GroupPowers.LandSetSale |
GroupPowers.ModerateChat |
GroupPowers.ObjectManipulate |
GroupPowers.ObjectSetForSale |
GroupPowers.ReceiveNotices |
GroupPowers.RemoveMember |
GroupPowers.ReturnGroupOwned |
GroupPowers.ReturnGroupSet |
GroupPowers.ReturnNonGroup |
GroupPowers.RoleProperties |
GroupPowers.SendNotices |
GroupPowers.SetLandingPoint |
GroupPowers.StartProposal |
GroupPowers.VoteOnProposal;
#region Daily Cleanup
private Timer m_CleanupTimer;
public GroupsService(IConfigSource config, string configName)
: base(config, configName)
{
}
public GroupsService(IConfigSource config)
: this(config, string.Empty)
{
// Once a day
m_CleanupTimer = new Timer(24 * 60 * 60 * 1000);
m_CleanupTimer.AutoReset = true;
m_CleanupTimer.Elapsed += new ElapsedEventHandler(m_CleanupTimer_Elapsed);
m_CleanupTimer.Enabled = true;
m_CleanupTimer.Start();
}
private void m_CleanupTimer_Elapsed(object sender, ElapsedEventArgs e)
{
m_Database.DeleteOldNotices();
m_Database.DeleteOldInvites();
}
#endregion
public UUID CreateGroup(string RequestingAgentID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment,
bool allowPublish, bool maturePublish, UUID founderID, out string reason)
{
reason = string.Empty;
// Check if the group already exists
if (m_Database.RetrieveGroup(name) != null)
{
reason = "A group with that name already exists";
return UUID.Zero;
}
// Create the group
GroupData data = new GroupData();
data.GroupID = UUID.Random();
data.Data = new Dictionary<string, string>();
data.Data["Name"] = name;
data.Data["Charter"] = charter;
data.Data["InsigniaID"] = insigniaID.ToString();
data.Data["FounderID"] = founderID.ToString();
data.Data["MembershipFee"] = membershipFee.ToString();
data.Data["OpenEnrollment"] = openEnrollment ? "1" : "0";
data.Data["ShowInList"] = showInList ? "1" : "0";
data.Data["AllowPublish"] = allowPublish ? "1" : "0";
data.Data["MaturePublish"] = maturePublish ? "1" : "0";
data.Data["OwnerRoleID"] = UUID.Random().ToString();
if (!m_Database.StoreGroup(data))
return UUID.Zero;
// Create Everyone role
_AddOrUpdateGroupRole(RequestingAgentID, data.GroupID, UUID.Zero, "Everyone", "Everyone in the group", "Member of " + name, (ulong)DefaultEveryonePowers, true);
// Create Owner role
UUID roleID = UUID.Random();
_AddOrUpdateGroupRole(RequestingAgentID, data.GroupID, roleID, "Owners", "Owners of the group", "Owner of " + name, (ulong)OwnerPowers, true);
// Add founder to group
_AddAgentToGroup(RequestingAgentID, founderID.ToString(), data.GroupID, roleID);
return data.GroupID;
}
public void UpdateGroup(string RequestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish)
{
GroupData data = m_Database.RetrieveGroup(groupID);
if (data == null)
return;
// Check perms
if (!HasPower(RequestingAgentID, groupID, GroupPowers.ChangeActions))
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at updating group {1} denied because of lack of permission", RequestingAgentID, groupID);
return;
}
data.GroupID = groupID;
data.Data["Charter"] = charter;
data.Data["ShowInList"] = showInList ? "1" : "0";
data.Data["InsigniaID"] = insigniaID.ToString();
data.Data["MembershipFee"] = membershipFee.ToString();
data.Data["OpenEnrollment"] = openEnrollment ? "1" : "0";
data.Data["AllowPublish"] = allowPublish ? "1" : "0";
data.Data["MaturePublish"] = maturePublish ? "1" : "0";
m_Database.StoreGroup(data);
}
public ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, UUID GroupID)
{
GroupData data = m_Database.RetrieveGroup(GroupID);
return _GroupDataToRecord(data);
}
public ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, string GroupName)
{
GroupData data = m_Database.RetrieveGroup(GroupName);
return _GroupDataToRecord(data);
}
public List<DirGroupsReplyData> FindGroups(string RequestingAgentID, string search)
{
List<DirGroupsReplyData> groups = new List<DirGroupsReplyData>();
GroupData[] data = m_Database.RetrieveGroups(search);
if (data != null && data.Length > 0)
{
foreach (GroupData d in data)
{
// Don't list group proxies
if (d.Data.ContainsKey("Location") && d.Data["Location"] != string.Empty)
continue;
DirGroupsReplyData g = new DirGroupsReplyData();
g.groupID = d.GroupID;
if (d.Data.ContainsKey("Name"))
g.groupName = d.Data["Name"];
else
m_log.DebugFormat("[Groups]: Key Name not found");
g.members = m_Database.MemberCount(d.GroupID);
groups.Add(g);
}
}
return groups;
}
public List<ExtendedGroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID)
{
List<ExtendedGroupMembersData> members = new List<ExtendedGroupMembersData>();
GroupData group = m_Database.RetrieveGroup(GroupID);
if (group == null)
return members;
UUID ownerRoleID = new UUID(group.Data["OwnerRoleID"]);
RoleData[] roles = m_Database.RetrieveRoles(GroupID);
if (roles == null)
// something wrong with this group
return members;
List<RoleData> rolesList = new List<RoleData>(roles);
// Check visibility?
// When we don't want to check visibility, we pass it "all" as the requestingAgentID
bool checkVisibility = !RequestingAgentID.Equals(UUID.Zero.ToString());
if (checkVisibility)
{
// Is the requester a member of the group?
bool isInGroup = false;
if (m_Database.RetrieveMember(GroupID, RequestingAgentID) != null)
isInGroup = true;
if (!isInGroup) // reduce the roles to the visible ones
rolesList = rolesList.FindAll(r => (UInt64.Parse(r.Data["Powers"]) & (ulong)GroupPowers.MemberVisible) != 0);
}
MembershipData[] datas = m_Database.RetrieveMembers(GroupID);
if (datas == null || (datas != null && datas.Length == 0))
return members;
// OK, we have everything we need
foreach (MembershipData d in datas)
{
RoleMembershipData[] rolememberships = m_Database.RetrieveMemberRoles(GroupID, d.PrincipalID);
List<RoleMembershipData> rolemembershipsList = new List<RoleMembershipData>(rolememberships);
ExtendedGroupMembersData m = new ExtendedGroupMembersData();
// What's this person's current role in the group?
UUID selectedRole = new UUID(d.Data["SelectedRoleID"]);
RoleData selected = rolesList.Find(r => r.RoleID == selectedRole);
if (selected != null)
{
m.Title = selected.Data["Title"];
m.AgentPowers = UInt64.Parse(selected.Data["Powers"]);
m.AgentID = d.PrincipalID;
m.AcceptNotices = d.Data["AcceptNotices"] == "1" ? true : false;
m.Contribution = Int32.Parse(d.Data["Contribution"]);
m.ListInProfile = d.Data["ListInProfile"] == "1" ? true : false;
// Is this person an owner of the group?
m.IsOwner = (rolemembershipsList.Find(r => r.RoleID == ownerRoleID) != null) ? true : false;
members.Add(m);
}
}
return members;
}
public bool AddGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, out string reason)
{
reason = string.Empty;
// check that the requesting agent has permissions to add role
if (!HasPower(RequestingAgentID, groupID, GroupPowers.CreateRole))
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at creating role in group {1} denied because of lack of permission", RequestingAgentID, groupID);
reason = "Insufficient permission to create role";
return false;
}
return _AddOrUpdateGroupRole(RequestingAgentID, groupID, roleID, name, description, title, powers, true);
}
public bool UpdateGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers)
{
// check perms
if (!HasPower(RequestingAgentID, groupID, GroupPowers.ChangeActions))
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at changing role in group {1} denied because of lack of permission", RequestingAgentID, groupID);
return false;
}
return _AddOrUpdateGroupRole(RequestingAgentID, groupID, roleID, name, description, title, powers, false);
}
public void RemoveGroupRole(string RequestingAgentID, UUID groupID, UUID roleID)
{
// check perms
if (!HasPower(RequestingAgentID, groupID, GroupPowers.DeleteRole))
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at deleting role from group {1} denied because of lack of permission", RequestingAgentID, groupID);
return;
}
// Can't delete Everyone and Owners roles
if (roleID == UUID.Zero)
{
m_log.DebugFormat("[Groups]: Attempt at deleting Everyone role from group {0} denied", groupID);
return;
}
GroupData group = m_Database.RetrieveGroup(groupID);
if (group == null)
{
m_log.DebugFormat("[Groups]: Attempt at deleting role from non-existing group {0}", groupID);
return;
}
if (roleID == new UUID(group.Data["OwnerRoleID"]))
{
m_log.DebugFormat("[Groups]: Attempt at deleting Owners role from group {0} denied", groupID);
return;
}
_RemoveGroupRole(groupID, roleID);
}
public List<GroupRolesData> GetGroupRoles(string RequestingAgentID, UUID GroupID)
{
// TODO: check perms
return _GetGroupRoles(GroupID);
}
public List<ExtendedGroupRoleMembersData> GetGroupRoleMembers(string RequestingAgentID, UUID GroupID)
{
// TODO: check perms
// Is the requester a member of the group?
bool isInGroup = false;
if (m_Database.RetrieveMember(GroupID, RequestingAgentID) != null)
isInGroup = true;
return _GetGroupRoleMembers(GroupID, isInGroup);
}
public bool AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID, string token, out string reason)
{
reason = string.Empty;
_AddAgentToGroup(RequestingAgentID, AgentID, GroupID, RoleID, token);
return true;
}
public void RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID)
{
// check perms
if (RequestingAgentID != AgentID && !HasPower(RequestingAgentID, GroupID, GroupPowers.Eject))
return;
_RemoveAgentFromGroup(RequestingAgentID, AgentID, GroupID);
}
public bool AddAgentToGroupInvite(string RequestingAgentID, UUID inviteID, UUID groupID, UUID roleID, string agentID)
{
// Check whether the invitee is already a member of the group
MembershipData m = m_Database.RetrieveMember(groupID, agentID);
if (m != null)
return false;
// Check permission to invite
if (!HasPower(RequestingAgentID, groupID, GroupPowers.Invite))
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at inviting to group {1} denied because of lack of permission", RequestingAgentID, groupID);
return false;
}
// Check whether there are pending invitations and delete them
InvitationData invite = m_Database.RetrieveInvitation(groupID, agentID);
if (invite != null)
m_Database.DeleteInvite(invite.InviteID);
invite = new InvitationData();
invite.InviteID = inviteID;
invite.PrincipalID = agentID;
invite.GroupID = groupID;
invite.RoleID = roleID;
invite.Data = new Dictionary<string, string>();
return m_Database.StoreInvitation(invite);
}
public GroupInviteInfo GetAgentToGroupInvite(string RequestingAgentID, UUID inviteID)
{
InvitationData data = m_Database.RetrieveInvitation(inviteID);
if (data == null)
return null;
GroupInviteInfo inviteInfo = new GroupInviteInfo();
inviteInfo.AgentID = data.PrincipalID;
inviteInfo.GroupID = data.GroupID;
inviteInfo.InviteID = data.InviteID;
inviteInfo.RoleID = data.RoleID;
return inviteInfo;
}
public void RemoveAgentToGroupInvite(string RequestingAgentID, UUID inviteID)
{
m_Database.DeleteInvite(inviteID);
}
public bool AddAgentToGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
//if (!m_Database.CheckOwnerRole(RequestingAgentID, GroupID, RoleID))
// return;
// check permissions
bool limited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMemberLimited);
bool unlimited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMember) | IsOwner(RequestingAgentID, GroupID);
if (!limited || !unlimited)
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at assigning {1} to role {2} denied because of lack of permission", RequestingAgentID, AgentID, RoleID);
return false;
}
// AssignMemberLimited means that the person can assign another person to the same roles that she has in the group
if (!unlimited && limited)
{
// check whether person's has this role
RoleMembershipData rolemembership = m_Database.RetrieveRoleMember(GroupID, RoleID, AgentID);
if (rolemembership == null)
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at assigning {1} to role {2} denied because of limited permission", RequestingAgentID, AgentID, RoleID);
return false;
}
}
_AddAgentToGroupRole(RequestingAgentID, AgentID, GroupID, RoleID);
return true;
}
public bool RemoveAgentFromGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
// Don't remove from Everyone role!
if (RoleID == UUID.Zero)
return false;
// check permissions
bool unlimited = HasPower(RequestingAgentID, GroupID, GroupPowers.AssignMember) || IsOwner(RequestingAgentID, GroupID);
if (!unlimited)
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at removing {1} from role {2} denied because of lack of permission", RequestingAgentID, AgentID, RoleID);
return false;
}
RoleMembershipData rolemember = m_Database.RetrieveRoleMember(GroupID, RoleID, AgentID);
if (rolemember == null)
return false;
m_Database.DeleteRoleMember(rolemember);
// Find another role for this person
UUID newRoleID = UUID.Zero; // Everyone
RoleMembershipData[] rdata = m_Database.RetrieveMemberRoles(GroupID, AgentID);
if (rdata != null)
foreach (RoleMembershipData r in rdata)
{
if (r.RoleID != UUID.Zero)
{
newRoleID = r.RoleID;
break;
}
}
MembershipData member = m_Database.RetrieveMember(GroupID, AgentID);
if (member != null)
{
member.Data["SelectedRoleID"] = newRoleID.ToString();
m_Database.StoreMember(member);
}
return true;
}
public List<GroupRolesData> GetAgentGroupRoles(string RequestingAgentID, string AgentID, UUID GroupID)
{
List<GroupRolesData> roles = new List<GroupRolesData>();
// TODO: check permissions
RoleMembershipData[] data = m_Database.RetrieveMemberRoles(GroupID, AgentID);
if (data == null || (data != null && data.Length ==0))
return roles;
foreach (RoleMembershipData d in data)
{
RoleData rdata = m_Database.RetrieveRole(GroupID, d.RoleID);
if (rdata == null) // hippos
continue;
GroupRolesData r = new GroupRolesData();
r.Name = rdata.Data["Name"];
r.Powers = UInt64.Parse(rdata.Data["Powers"]);
r.RoleID = rdata.RoleID;
r.Title = rdata.Data["Title"];
roles.Add(r);
}
return roles;
}
public ExtendedGroupMembershipData SetAgentActiveGroup(string RequestingAgentID, string AgentID, UUID GroupID)
{
// TODO: check perms
PrincipalData principal = new PrincipalData();
principal.PrincipalID = AgentID;
principal.ActiveGroupID = GroupID;
m_Database.StorePrincipal(principal);
return GetAgentGroupMembership(RequestingAgentID, AgentID, GroupID);
}
public ExtendedGroupMembershipData GetAgentActiveMembership(string RequestingAgentID, string AgentID)
{
// 1. get the principal data for the active group
PrincipalData principal = m_Database.RetrievePrincipal(AgentID);
if (principal == null)
return null;
return GetAgentGroupMembership(RequestingAgentID, AgentID, principal.ActiveGroupID);
}
public ExtendedGroupMembershipData GetAgentGroupMembership(string RequestingAgentID, string AgentID, UUID GroupID)
{
return GetAgentGroupMembership(RequestingAgentID, AgentID, GroupID, null);
}
private ExtendedGroupMembershipData GetAgentGroupMembership(string RequestingAgentID, string AgentID, UUID GroupID, MembershipData membership)
{
// 2. get the active group
GroupData group = m_Database.RetrieveGroup(GroupID);
if (group == null)
return null;
// 3. get the membership info if we don't have it already
if (membership == null)
{
membership = m_Database.RetrieveMember(group.GroupID, AgentID);
if (membership == null)
return null;
}
// 4. get the active role
UUID activeRoleID = new UUID(membership.Data["SelectedRoleID"]);
RoleData role = m_Database.RetrieveRole(group.GroupID, activeRoleID);
ExtendedGroupMembershipData data = new ExtendedGroupMembershipData();
data.AcceptNotices = membership.Data["AcceptNotices"] == "1" ? true : false;
data.AccessToken = membership.Data["AccessToken"];
data.Active = true;
data.ActiveRole = activeRoleID;
data.AllowPublish = group.Data["AllowPublish"] == "1" ? true : false;
data.Charter = group.Data["Charter"];
data.Contribution = Int32.Parse(membership.Data["Contribution"]);
data.FounderID = new UUID(group.Data["FounderID"]);
data.GroupID = new UUID(group.GroupID);
data.GroupName = group.Data["Name"];
data.GroupPicture = new UUID(group.Data["InsigniaID"]);
if (role != null)
{
data.GroupPowers = UInt64.Parse(role.Data["Powers"]);
data.GroupTitle = role.Data["Title"];
}
data.ListInProfile = membership.Data["ListInProfile"] == "1" ? true : false;
data.MaturePublish = group.Data["MaturePublish"] == "1" ? true : false;
data.MembershipFee = Int32.Parse(group.Data["MembershipFee"]);
data.OpenEnrollment = group.Data["OpenEnrollment"] == "1" ? true : false;
data.ShowInList = group.Data["ShowInList"] == "1" ? true : false;
return data;
}
public List<GroupMembershipData> GetAgentGroupMemberships(string RequestingAgentID, string AgentID)
{
List<GroupMembershipData> memberships = new List<GroupMembershipData>();
// 1. Get all the groups that this person is a member of
MembershipData[] mdata = m_Database.RetrieveMemberships(AgentID);
if (mdata == null || (mdata != null && mdata.Length == 0))
return memberships;
foreach (MembershipData d in mdata)
{
GroupMembershipData gmember = GetAgentGroupMembership(RequestingAgentID, AgentID, d.GroupID, d);
if (gmember != null)
{
memberships.Add(gmember);
//m_log.DebugFormat("[XXX]: Member of {0} as {1}", gmember.GroupName, gmember.GroupTitle);
//Util.PrintCallStack();
}
}
return memberships;
}
public void SetAgentActiveGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
MembershipData data = m_Database.RetrieveMember(GroupID, AgentID);
if (data == null)
return;
data.Data["SelectedRoleID"] = RoleID.ToString();
m_Database.StoreMember(data);
}
public void UpdateMembership(string RequestingAgentID, string AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile)
{
// TODO: check perms
MembershipData membership = m_Database.RetrieveMember(GroupID, AgentID);
if (membership == null)
return;
membership.Data["AcceptNotices"] = AcceptNotices ? "1" : "0";
membership.Data["ListInProfile"] = ListInProfile ? "1" : "0";
m_Database.StoreMember(membership);
}
public bool AddGroupNotice(string RequestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message,
bool hasAttachment, byte attType, string attName, UUID attItemID, string attOwnerID)
{
// Check perms
if (!HasPower(RequestingAgentID, groupID, GroupPowers.SendNotices))
{
m_log.DebugFormat("[Groups]: ({0}) Attempt at sending notice to group {1} denied because of lack of permission", RequestingAgentID, groupID);
return false;
}
return _AddNotice(groupID, noticeID, fromName, subject, message, hasAttachment, attType, attName, attItemID, attOwnerID);
}
public GroupNoticeInfo GetGroupNotice(string RequestingAgentID, UUID noticeID)
{
NoticeData data = m_Database.RetrieveNotice(noticeID);
if (data == null)
return null;
return _NoticeDataToInfo(data);
}
public List<ExtendedGroupNoticeData> GetGroupNotices(string RequestingAgentID, UUID groupID)
{
NoticeData[] data = m_Database.RetrieveNotices(groupID);
List<ExtendedGroupNoticeData> infos = new List<ExtendedGroupNoticeData>();
if (data == null || (data != null && data.Length == 0))
return infos;
foreach (NoticeData d in data)
{
ExtendedGroupNoticeData info = _NoticeDataToData(d);
infos.Add(info);
}
return infos;
}
public void ResetAgentGroupChatSessions(string agentID)
{
}
public bool hasAgentBeenInvitedToGroupChatSession(string agentID, UUID groupID)
{
return false;
}
public bool hasAgentDroppedGroupChatSession(string agentID, UUID groupID)
{
return false;
}
public void AgentDroppedFromGroupChatSession(string agentID, UUID groupID)
{
}
public void AgentInvitedToGroupChatSession(string agentID, UUID groupID)
{
}
#region Actions without permission checks
protected void _AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
_AddAgentToGroup(RequestingAgentID, AgentID, GroupID, RoleID, string.Empty);
}
protected void _RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID)
{
// 1. Delete membership
m_Database.DeleteMember(GroupID, AgentID);
// 2. Remove from rolememberships
m_Database.DeleteMemberAllRoles(GroupID, AgentID);
// 3. if it was active group, inactivate it
PrincipalData principal = m_Database.RetrievePrincipal(AgentID);
if (principal != null && principal.ActiveGroupID == GroupID)
{
principal.ActiveGroupID = UUID.Zero;
m_Database.StorePrincipal(principal);
}
}
protected void _AddAgentToGroup(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID, string accessToken)
{
// Check if it's already there
MembershipData data = m_Database.RetrieveMember(GroupID, AgentID);
if (data != null)
return;
// Add the membership
data = new MembershipData();
data.PrincipalID = AgentID;
data.GroupID = GroupID;
data.Data = new Dictionary<string, string>();
data.Data["SelectedRoleID"] = RoleID.ToString();
data.Data["Contribution"] = "0";
data.Data["ListInProfile"] = "1";
data.Data["AcceptNotices"] = "1";
data.Data["AccessToken"] = accessToken;
m_Database.StoreMember(data);
// Add principal to everyone role
_AddAgentToGroupRole(RequestingAgentID, AgentID, GroupID, UUID.Zero);
// Add principal to role, if different from everyone role
if (RoleID != UUID.Zero)
_AddAgentToGroupRole(RequestingAgentID, AgentID, GroupID, RoleID);
// Make thit this active group
PrincipalData pdata = new PrincipalData();
pdata.PrincipalID = AgentID;
pdata.ActiveGroupID = GroupID;
m_Database.StorePrincipal(pdata);
}
protected bool _AddOrUpdateGroupRole(string RequestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, bool add)
{
RoleData data = m_Database.RetrieveRole(groupID, roleID);
if (add && data != null) // it already exists, can't create
{
m_log.DebugFormat("[Groups]: Group {0} already exists. Can't create it again", groupID);
return false;
}
if (!add && data == null) // it deosn't exist, can't update
{
m_log.DebugFormat("[Groups]: Group {0} doesn't exist. Can't update it", groupID);
return false;
}
if (add)
data = new RoleData();
data.GroupID = groupID;
data.RoleID = roleID;
data.Data = new Dictionary<string, string>();
data.Data["Name"] = name;
data.Data["Description"] = description;
data.Data["Title"] = title;
data.Data["Powers"] = powers.ToString();
return m_Database.StoreRole(data);
}
protected void _RemoveGroupRole(UUID groupID, UUID roleID)
{
m_Database.DeleteRole(groupID, roleID);
}
protected void _AddAgentToGroupRole(string RequestingAgentID, string AgentID, UUID GroupID, UUID RoleID)
{
RoleMembershipData data = m_Database.RetrieveRoleMember(GroupID, RoleID, AgentID);
if (data != null)
return;
data = new RoleMembershipData();
data.GroupID = GroupID;
data.PrincipalID = AgentID;
data.RoleID = RoleID;
m_Database.StoreRoleMember(data);
// Make it the SelectedRoleID
MembershipData membership = m_Database.RetrieveMember(GroupID, AgentID);
if (membership == null)
{
m_log.DebugFormat("[Groups]: ({0}) No such member {0} in group {1}", AgentID, GroupID);
return;
}
membership.Data["SelectedRoleID"] = RoleID.ToString();
m_Database.StoreMember(membership);
}
protected List<GroupRolesData> _GetGroupRoles(UUID groupID)
{
List<GroupRolesData> roles = new List<GroupRolesData>();
RoleData[] data = m_Database.RetrieveRoles(groupID);
if (data == null || (data != null && data.Length == 0))
return roles;
foreach (RoleData d in data)
{
GroupRolesData r = new GroupRolesData();
r.Description = d.Data["Description"];
r.Members = m_Database.RoleMemberCount(groupID, d.RoleID);
r.Name = d.Data["Name"];
r.Powers = UInt64.Parse(d.Data["Powers"]);
r.RoleID = d.RoleID;
r.Title = d.Data["Title"];
roles.Add(r);
}
return roles;
}
protected List<ExtendedGroupRoleMembersData> _GetGroupRoleMembers(UUID GroupID, bool isInGroup)
{
List<ExtendedGroupRoleMembersData> rmembers = new List<ExtendedGroupRoleMembersData>();
RoleData[] rdata = new RoleData[0];
if (!isInGroup)
{
rdata = m_Database.RetrieveRoles(GroupID);
if (rdata == null || (rdata != null && rdata.Length == 0))
return rmembers;
}
List<RoleData> rlist = new List<RoleData>(rdata);
if (!isInGroup)
rlist = rlist.FindAll(r => (UInt64.Parse(r.Data["Powers"]) & (ulong)GroupPowers.MemberVisible) != 0);
RoleMembershipData[] data = m_Database.RetrieveRolesMembers(GroupID);
if (data == null || (data != null && data.Length == 0))
return rmembers;
foreach (RoleMembershipData d in data)
{
if (!isInGroup)
{
RoleData rd = rlist.Find(_r => _r.RoleID == d.RoleID); // visible role
if (rd == null)
continue;
}
ExtendedGroupRoleMembersData r = new ExtendedGroupRoleMembersData();
r.MemberID = d.PrincipalID;
r.RoleID = d.RoleID;
rmembers.Add(r);
}
return rmembers;
}
protected bool _AddNotice(UUID groupID, UUID noticeID, string fromName, string subject, string message,
bool hasAttachment, byte attType, string attName, UUID attItemID, string attOwnerID)
{
NoticeData data = new NoticeData();
data.GroupID = groupID;
data.NoticeID = noticeID;
data.Data = new Dictionary<string, string>();
data.Data["FromName"] = fromName;
data.Data["Subject"] = subject;
data.Data["Message"] = message;
data.Data["HasAttachment"] = hasAttachment ? "1" : "0";
if (hasAttachment)
{
data.Data["AttachmentType"] = attType.ToString();
data.Data["AttachmentName"] = attName;
data.Data["AttachmentItemID"] = attItemID.ToString();
data.Data["AttachmentOwnerID"] = attOwnerID;
}
data.Data["TMStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString();
return m_Database.StoreNotice(data);
}
#endregion
#region structure translations
ExtendedGroupRecord _GroupDataToRecord(GroupData data)
{
if (data == null)
return null;
ExtendedGroupRecord rec = new ExtendedGroupRecord();
rec.AllowPublish = data.Data["AllowPublish"] == "1" ? true : false;
rec.Charter = data.Data["Charter"];
rec.FounderID = new UUID(data.Data["FounderID"]);
rec.GroupID = data.GroupID;
rec.GroupName = data.Data["Name"];
rec.GroupPicture = new UUID(data.Data["InsigniaID"]);
rec.MaturePublish = data.Data["MaturePublish"] == "1" ? true : false;
rec.MembershipFee = Int32.Parse(data.Data["MembershipFee"]);
rec.OpenEnrollment = data.Data["OpenEnrollment"] == "1" ? true : false;
rec.OwnerRoleID = new UUID(data.Data["OwnerRoleID"]);
rec.ShowInList = data.Data["ShowInList"] == "1" ? true : false;
rec.ServiceLocation = data.Data["Location"];
rec.MemberCount = m_Database.MemberCount(data.GroupID);
rec.RoleCount = m_Database.RoleCount(data.GroupID);
return rec;
}
GroupNoticeInfo _NoticeDataToInfo(NoticeData data)
{
GroupNoticeInfo notice = new GroupNoticeInfo();
notice.GroupID = data.GroupID;
notice.Message = data.Data["Message"];
notice.noticeData = _NoticeDataToData(data);
return notice;
}
ExtendedGroupNoticeData _NoticeDataToData(NoticeData data)
{
ExtendedGroupNoticeData notice = new ExtendedGroupNoticeData();
notice.FromName = data.Data["FromName"];
notice.NoticeID = data.NoticeID;
notice.Subject = data.Data["Subject"];
notice.Timestamp = uint.Parse((string)data.Data["TMStamp"]);
notice.HasAttachment = data.Data["HasAttachment"] == "1" ? true : false;
if (notice.HasAttachment)
{
notice.AttachmentName = data.Data["AttachmentName"];
notice.AttachmentItemID = new UUID(data.Data["AttachmentItemID"].ToString());
notice.AttachmentType = byte.Parse(data.Data["AttachmentType"].ToString());
notice.AttachmentOwnerID = data.Data["AttachmentOwnerID"].ToString();
}
return notice;
}
#endregion
#region permissions
private bool HasPower(string agentID, UUID groupID, GroupPowers power)
{
RoleMembershipData[] rmembership = m_Database.RetrieveMemberRoles(groupID, agentID);
if (rmembership == null || (rmembership != null && rmembership.Length == 0))
return false;
foreach (RoleMembershipData rdata in rmembership)
{
RoleData role = m_Database.RetrieveRole(groupID, rdata.RoleID);
if ( (UInt64.Parse(role.Data["Powers"]) & (ulong)power) != 0 )
return true;
}
return false;
}
private bool IsOwner(string agentID, UUID groupID)
{
GroupData group = m_Database.RetrieveGroup(groupID);
if (group == null)
return false;
RoleMembershipData rmembership = m_Database.RetrieveRoleMember(groupID, new UUID(group.Data["OwnerRoleID"]), agentID);
if (rmembership == null)
return false;
return true;
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft Corporation. 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.
//
namespace NuGet.OneGet {
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using IRequestObject = System.Object;
using global::OneGet.ProviderSDK;
public abstract class CommonProvider<T> where T : BaseRequest {
protected static readonly string[] _empty = new string[0];
protected static Dictionary<string, string[]> _features;
internal static IEnumerable<string> SupportedSchemes {
get {
return _features[Constants.Features.SupportedSchemes];
}
}
internal abstract string ProviderName {get;}
/// <summary>
/// Returns the name of the Provider.
/// </summary>
/// <returns>The name of this proivder (uses the constant declared at the top of the class)</returns>
public string GetPackageProviderName() {
return ProviderName;
}
/// <summary>
/// NOT IMPLEMENTED YET
/// </summary>
/// <param name="fastPackageReference"></param>
/// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
/// <returns></returns>
public void GetPackageDetails(string fastPackageReference, IRequestObject requestObject) {
try {
// create a strongly-typed request object.
using (var request = requestObject.As<T>()) {
// Nice-to-have put a debug message in that tells what's going on.
request.Debug("Calling '{0}::GetPackageDetails' '{1}'", ProviderName, fastPackageReference);
// Check to see if we're ok to proceed.
if (!request.IsReady(true)) {
return;
}
}
}
catch (Exception e) {
// We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
// Really this is just here as a precautionary to behave correctly.
// At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::GetPackageDetails' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
}
}
/// <summary>
/// Returns a collection of strings to the client advertizing features this provider supports.
/// </summary>
/// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
public void GetFeatures(IRequestObject requestObject) {
try {
// create a strongly-typed request object.
using (var request = requestObject.As<T>()) {
// Nice-to-have put a debug message in that tells what's going on.
request.Debug("Calling '{0}::GetFeatures' ", ProviderName);
// Check to see if we're ok to proceed.
if (!request.IsReady(false)) {
return;
}
foreach (var feature in _features) {
request.Yield(feature);
}
}
}
catch (Exception e) {
// We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
// Really this is just here as a precautionary to behave correctly.
// At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::GetFeatures' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
}
}
/// <summary>
/// Returns dynamic option definitions to the HOST
/// </summary>
/// <param name="category">The category of dynamic options that the HOST is interested in</param>
/// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
public abstract void GetDynamicOptions(string category, IRequestObject requestObject);
/// <summary>
/// This is called when the user is adding (or updating) a package source
///
/// If this PROVIDER doesn't support user-defined package sources, remove this method.
/// </summary>
/// <param name="name">The name of the package source. If this parameter is null or empty the PROVIDER should use the location as the name (if the PROVIDER actually stores names of package sources)</param>
/// <param name="location">The location (ie, directory, URL, etc) of the package source. If this is null or empty, the PROVIDER should use the name as the location (if valid)</param>
/// <param name="trusted">A boolean indicating that the user trusts this package source. Packages returned from this source should be marked as 'trusted'</param>
/// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
public void AddPackageSource(string name, string location, bool trusted, IRequestObject requestObject) {
try {
// create a strongly-typed request object.
using (var request = requestObject.As<T>()) {
// Nice-to-have put a debug message in that tells what's going on.
request.Debug("Calling '{0}::AddPackageSource' '{1}','{2}','{3}'", ProviderName, name, location, trusted);
// Check to see if we're ok to proceed.
if (!request.IsReady(false)) {
return;
}
// if they didn't pass in a name, use the location as a name. (if you support that kind of thing)
name = string.IsNullOrEmpty(name) ? location : name;
// let's make sure that they've given us everything we need.
if (string.IsNullOrEmpty(name)) {
request.Error(ErrorCategory.InvalidArgument, Constants.Parameters.Name, Constants.Messages.MissingRequiredParameter, Constants.Parameters.Name);
// we're done here.
return;
}
if (string.IsNullOrEmpty(location)) {
request.Error(ErrorCategory.InvalidArgument, Constants.Parameters.Location, Constants.Messages.MissingRequiredParameter, Constants.Parameters.Location);
// we're done here.
return;
}
// if this is supposed to be an update, there will be a dynamic parameter set for IsUpdatePackageSource
var isUpdate = request.GetOptionValue(Constants.Parameters.IsUpdate).IsTrue();
// if your source supports credentials you get get them too:
// string username =request.Username;
// SecureString password = request.Password;
// feel free to send back an error here if your provider requires credentials for package sources.
// check first that we're not clobbering an existing source, unless this is an update
var src = request.FindRegisteredSource(name);
if (src != null && !isUpdate) {
// tell the user that there's one here already
request.Error(ErrorCategory.InvalidArgument, name ?? location, Constants.Messages.PackageProviderExists, name ?? location);
// we're done here.
return;
}
// conversely, if it didn't find one, and it is an update, that's bad too:
if (src == null && isUpdate) {
// you can't find that package source? Tell that to the user
request.Error(ErrorCategory.ObjectNotFound, name ?? location, Constants.Messages.UnableToResolveSource, name ?? location);
// we're done here.
return;
}
// ok, we know that we're ok to save this source
// next we check if the location is valid (if we support that kind of thing)
var validated = false;
if (!request.SkipValidate) {
// the user has not opted to skip validating the package source location, so check that it's valid (talk to the url, or check if it's a valid directory, etc)
// todo: insert code to check if the source is valid
validated = request.ValidateSourceLocation(location);
if (!validated) {
request.Error(ErrorCategory.InvalidData, name ?? location, Constants.Messages.SourceLocationNotValid, location);
// we're done here.
return;
}
// we passed validation!
}
// it's good to check just before you actaully write something to see if the user has cancelled the operation
if (request.IsCanceled) {
return;
}
// looking good -- store the package source
// todo: create the package source (and store it whereever you store it)
request.Verbose("Storing package source {0}", name);
// actually yielded by the implementation.
request.AddPackageSource(name, location, trusted, validated);
// and, before you go, Yield the package source back to the caller.
if (!request.YieldPackageSource(name, location, trusted, true /*since we just registered it*/, validated)) {
// always check the return value of a yield, since if it returns false, you don't keep returning data
// this can happen if they have cancelled the operation.
return;
}
// all done!
}
}
catch (Exception e) {
// We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
// Really this is just here as a precautionary to behave correctly.
// At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
Debug.WriteLine(string.Format("Unexpected Exception thrown in {0} PackageProvider -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
}
}
/// <summary>
/// Removes/Unregisters a package source
/// </summary>
/// <param name="name">The name or location of a package source to remove.</param>
/// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
public void RemovePackageSource(string name, IRequestObject requestObject) {
try {
// create a strongly-typed request object.
using (var request = requestObject.As<T>()) {
// Nice-to-have put a debug message in that tells what's going on.
request.Debug("Calling '{0}::RemovePackageSource' '{1}'", ProviderName, name);
var src = request.FindRegisteredSource(name);
if (src == null) {
request.Warning(Constants.Messages.UnableToResolveSource, name);
return;
}
request.RemovePackageSource(src.Name);
request.YieldPackageSource(src.Name, src.Location, src.Trusted, false, src.IsValidated);
}
}
catch (Exception e) {
// We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
// Really this is just here as a precautionary to behave correctly.
// At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::RemovePackageSource' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
}
}
/// <summary>
///
/// </summary>
/// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
public void ResolvePackageSources(IRequestObject requestObject) {
try {
// create a strongly-typed request object.
using (var request = requestObject.As<T>()) {
// Nice-to-have put a debug message in that tells what's going on.
request.Debug("Calling '{0}::ResolvePackageSources'", ProviderName);
// Check to see if we're ok to proceed.
if (!request.IsReady(false)) {
return;
}
foreach (var source in request.SelectedSources) {
request.YieldPackageSource(source.Name, source.Location, source.Trusted, source.IsRegistered, source.IsValidated);
}
}
}
catch (Exception e) {
// We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
// Really this is just here as a precautionary to behave correctly.
// At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::ResolvePackageSources' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
}
}
// --- Finds packages ---------------------------------------------------------------------------------------------------
/// <summary>
/// </summary>
/// <param name="name"></param>
/// <param name="requiredVersion"></param>
/// <param name="minimumVersion"></param>
/// <param name="maximumVersion"></param>
/// <param name="id"></param>
/// <param name="requestObject"></param>
/// <returns></returns>
public void FindPackage(string name, string requiredVersion, string minimumVersion, string maximumVersion, int id, IRequestObject requestObject) {
try {
// create a strongly-typed request object.
using (var request = requestObject.As<T>()) {
// Nice-to-have put a debug message in that tells what's going on.
request.Debug("Calling '{0}::FindPackage' '{1}','{2}','{3}','{4}'", ProviderName, requiredVersion, minimumVersion, maximumVersion, id);
// Check to see if we're ok to proceed.
if (!request.IsReady(true)) {
return;
}
// get the package by ID first.
// if there are any packages, yield and return
if (request.YieldPackages(request.GetPackageById(name, requiredVersion, minimumVersion, maximumVersion), name)) {
return;
}
// have we been cancelled?
if (request.IsCanceled) {
return;
}
// Try searching for matches and returning those.
request.YieldPackages(request.SearchForPackages(name, requiredVersion, minimumVersion, maximumVersion), name);
request.Debug("Finished '{0}::FindPackage' '{1}','{2}','{3}','{4}'", ProviderName, requiredVersion, minimumVersion, maximumVersion, id);
}
} catch (Exception e) {
// We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
// Really this is just here as a precautionary to behave correctly.
// At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::FindPackage' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
}
}
/// <summary>
///
/// </summary>
/// <param name="fastPackageReference"></param>
/// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
public void InstallPackage(string fastPackageReference, IRequestObject requestObject) {
try {
// create a strongly-typed request object.
using (var request = requestObject.As<T>()) {
// Nice-to-have put a debug message in that tells what's going on.
request.Debug("Calling '{0}::InstallPackage' '{1}'", ProviderName, fastPackageReference);
// Check to see if we're ok to proceed.
if (!request.IsReady(true)) {
return;
}
var pkgRef = request.GetPackageByFastpath(fastPackageReference);
if (pkgRef == null) {
request.Error(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage);
return;
}
var dependencies = request.GetUninstalledPackageDependencies(pkgRef).Reverse().ToArray();
int progressId = 0;
if (dependencies.Length > 0) {
progressId = request.StartProgress(0, "Installing package '{0}'", pkgRef.GetCanonicalId(request));
}
var n = 0;
foreach (var d in dependencies) {
request.Progress(progressId, (n*100/(dependencies.Length+1)) + 1, "Installing dependent package '{0}'", d.GetCanonicalId(request));
if (!request.InstallSinglePackage(d)) {
request.Error(ErrorCategory.InvalidResult, pkgRef.GetCanonicalId(request), Constants.Messages.DependentPackageFailedInstall, d.GetCanonicalId(request));
return;
}
n++;
request.Progress(progressId, (n * 100 / (dependencies.Length + 1)) , "Installed dependent package '{0}'", d.GetCanonicalId(request));
}
// got this far, let's install the package we came here for.
if (!request.InstallSinglePackage(pkgRef)) {
// package itself didn't install.
// roll that back out everything we did install.
// and get out of here.
request.Error(ErrorCategory.InvalidResult, pkgRef.GetCanonicalId(request), Constants.Messages.PackageFailedInstall, pkgRef.GetCanonicalId(request));
request.CompleteProgress(progressId, false);
}
request.CompleteProgress(progressId, true);
}
}
catch (Exception e) {
// We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
// Really this is just here as a precautionary to behave correctly.
// At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::InstallPackage' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
}
}
/// <summary>
/// Uninstalls a package
/// </summary>
/// <param name="fastPackageReference"></param>
/// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
public void UninstallPackage(string fastPackageReference, IRequestObject requestObject) {
try {
// create a strongly-typed request object.
using (var request = requestObject.As<T>()) {
// Nice-to-have put a debug message in that tells what's going on.
request.Debug("Calling '{0}::UninstallPackage' '{1}'", ProviderName, fastPackageReference);
// Check to see if we're ok to proceed.
if (!request.IsReady(true)) {
return;
}
var pkg = request.GetPackageByFastpath(fastPackageReference);
request.UninstallPackage(pkg);
}
}
catch (Exception e) {
// We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
// Really this is just here as a precautionary to behave correctly.
// At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::UninstallPackage' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
}
}
/// <summary>
/// Downloads a remote package file to a local location.
/// </summary>
/// <param name="fastPackageReference"></param>
/// <param name="location"></param>
/// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
/// <returns></returns>
public void DownloadPackage(string fastPackageReference, string location, IRequestObject requestObject) {
try {
// create a strongly-typed request object.
using (var request = requestObject.As<T>()) {
// Nice-to-have put a debug message in that tells what's going on.
request.Debug("Calling '{0}::DownloadPackage' '{1}','{2}'", ProviderName, fastPackageReference, location);
// Check to see if we're ok to proceed.
if (!request.IsReady(true)) {
return;
}
var pkgRef = request.GetPackageByFastpath(fastPackageReference);
if (pkgRef == null) {
request.Error(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage);
return;
}
// cheap and easy copy to location.
using (var input = pkgRef.Package.GetStream()) {
using (var output = new FileStream(location, FileMode.Create, FileAccess.Write, FileShare.Read)) {
input.CopyTo(output);
}
}
}
}
catch (Exception e) {
// We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
// Really this is just here as a precautionary to behave correctly.
// At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::DownloadPackage' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
}
}
/// <summary>
/// Returns package references for all the dependent packages
/// </summary>
/// <param name="fastPackageReference"></param>
/// <param name="requestObject">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param>
/// <returns></returns>
public void GetPackageDependencies(string fastPackageReference, IRequestObject requestObject) {
try {
// create a strongly-typed request object.
using (var request = requestObject.As<T>()) {
// Nice-to-have put a debug message in that tells what's going on.
request.Debug("Calling '{0}::GetPackageDependencies' '{1}'", ProviderName, fastPackageReference);
// Check to see if we're ok to proceed.
if (!request.IsReady(true)) {
return;
}
var pkgRef = request.GetPackageByFastpath(fastPackageReference);
if (pkgRef == null) {
request.Error(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage);
return;
}
foreach (var depSet in pkgRef.Package.DependencySets) {
foreach (var dep in depSet.Dependencies) {
var depRefs = dep.VersionSpec == null ? request.GetPackageById(dep.Id).ToArray() : request.GetPackageByIdAndVersionSpec(dep.Id, dep.VersionSpec, true).ToArray();
if (depRefs.Length == 0) {
request.Error(ErrorCategory.InvalidResult, pkgRef.GetCanonicalId(request), Constants.Messages.DependencyResolutionError, request.GetCanonicalPackageId(ProviderName, dep.Id, ((object)dep.VersionSpec ?? "").ToString()));
}
foreach (var dependencyReference in depRefs) {
request.YieldPackage(dependencyReference, pkgRef.Id);
}
}
}
}
}
catch (Exception e) {
// We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
// Really this is just here as a precautionary to behave correctly.
// At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::GetPackageDependencies' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
}
}
/// <summary>
/// Finds a package given a local filename
/// </summary>
/// <param name="file"></param>
/// <param name="id"></param>
/// <param name="requestObject"></param>
public void FindPackageByFile(string file, int id, IRequestObject requestObject) {
try {
// create a strongly-typed request object.
using (var request = requestObject.As<T>()) {
// Nice-to-have put a debug message in that tells what's going on.
request.Debug("Calling '{0}::FindPackageByFile' '{1}','{2}'", ProviderName, file, id);
// Check to see if we're ok to proceed.
if (!request.IsReady(true)) {
return;
}
var pkgItem = request.GetPackageByFilePath(Path.GetFullPath(file));
if (pkgItem != null) {
request.YieldPackage(pkgItem, file);
}
}
}
catch (Exception e) {
// We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
// Really this is just here as a precautionary to behave correctly.
// At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::FindPackageByFile' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
}
}
/// <summary>
/// Gets the installed packages
/// </summary>
/// <param name="name"></param>
/// <param name="requestObject"></param>
public void GetInstalledPackages(string name, IRequestObject requestObject) {
try {
// create a strongly-typed request object.
using (var request = requestObject.As<T>()) {
// Nice-to-have put a debug message in that tells what's going on.
request.Debug("Calling '{0}::GetInstalledPackages' '{1}'", ProviderName, name);
// Check to see if we're ok to proceed.
if (!request.IsReady(true)) {
return;
}
// look in the destination directory for directories that contain nupkg files.
var subdirs = Directory.EnumerateDirectories(request.Destination);
foreach (var subdir in subdirs) {
var nupkgs = Directory.EnumerateFileSystemEntries(subdir, "*.nupkg", SearchOption.TopDirectoryOnly);
foreach (var pkgFile in nupkgs) {
var pkgItem = request.GetPackageByFilePath(pkgFile);
if (pkgItem != null && pkgItem.IsInstalled) {
if (pkgItem.Id.Equals(name, StringComparison.CurrentCultureIgnoreCase)) {
request.YieldPackage(pkgItem, name);
break;
}
if (string.IsNullOrEmpty(name) || pkgItem.Id.IndexOf(name, StringComparison.CurrentCultureIgnoreCase) > -1) {
if (!request.YieldPackage(pkgItem, name)) {
return;
}
}
}
}
}
}
} catch (Exception e) {
// We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues.
// Really this is just here as a precautionary to behave correctly.
// At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it.
Debug.WriteLine(string.Format("Unexpected Exception thrown in '{0}::GetInstalledPackages' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace));
}
}
}
}
| |
#region License
// /*
// See license included in this library folder.
// */
#endregion
using System;
using System.ComponentModel;
using System.Threading;
using Sqloogle.Libs.NLog.Common;
using Sqloogle.Libs.NLog.Internal;
namespace Sqloogle.Libs.NLog.Targets.Wrappers
{
/// <summary>
/// Provides asynchronous, buffered execution of target writes.
/// </summary>
/// <seealso href="http://nlog-project.org/wiki/AsyncWrapper_target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// <p>
/// Asynchronous target wrapper allows the logger code to execute more quickly, by queueing
/// messages and processing them in a separate thread. You should wrap targets
/// that spend a non-trivial amount of time in their Write() method with asynchronous
/// target to speed up logging.
/// </p>
/// <p>
/// Because asynchronous logging is quite a common scenario, NLog supports a
/// shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to
/// the <targets/> element in the configuration file.
/// </p>
/// <code lang="XML">
/// <![CDATA[
/// <targets async="true">
/// ... your targets go here ...
/// </targets>
/// ]]></code>
/// </remarks>
/// <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/AsyncWrapper/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule. See below for
/// a programmatic configuration that's equivalent to the above config file:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/AsyncWrapper/Wrapping File/Example.cs" />
/// </example>
[Target("AsyncWrapper", IsWrapper = true)]
public class AsyncTargetWrapper : WrapperTargetBase
{
private readonly object lockObject = new object();
private AsyncContinuation flushAllContinuation;
private Timer lazyWriterTimer;
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
public AsyncTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public AsyncTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="queueLimit">Maximum number of requests in the queue.</param>
/// <param name="overflowAction">The action to be taken when the queue overflows.</param>
public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction)
{
RequestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard);
TimeToSleepBetweenBatches = 50;
BatchSize = 100;
WrappedTarget = wrappedTarget;
QueueLimit = queueLimit;
OverflowAction = overflowAction;
}
/// <summary>
/// Gets or sets the number of log events that should be processed in a batch
/// by the lazy writer thread.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(100)]
public int BatchSize { get; set; }
/// <summary>
/// Gets or sets the time in milliseconds to sleep between batches.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(50)]
public int TimeToSleepBetweenBatches { get; set; }
/// <summary>
/// Gets or sets the action to be taken when the lazy writer thread request queue count
/// exceeds the set limit.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue("Discard")]
public AsyncTargetWrapperOverflowAction OverflowAction
{
get { return RequestQueue.OnOverflow; }
set { RequestQueue.OnOverflow = value; }
}
/// <summary>
/// Gets or sets the limit on the number of requests in the lazy writer thread request queue.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(10000)]
public int QueueLimit
{
get { return RequestQueue.RequestLimit; }
set { RequestQueue.RequestLimit = value; }
}
/// <summary>
/// Gets the queue of lazy writer thread requests.
/// </summary>
internal AsyncRequestQueue RequestQueue { get; private set; }
/// <summary>
/// Waits for the lazy writer thread to finish writing messages.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
flushAllContinuation = asyncContinuation;
}
/// <summary>
/// Initializes the target by starting the lazy writer timer.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
RequestQueue.Clear();
lazyWriterTimer = new Timer(ProcessPendingEvents, null, Timeout.Infinite, Timeout.Infinite);
StartLazyWriterTimer();
}
/// <summary>
/// Shuts down the lazy writer timer.
/// </summary>
protected override void CloseTarget()
{
StopLazyWriterThread();
base.CloseTarget();
}
/// <summary>
/// Starts the lazy writer thread which periodically writes
/// queued log messages.
/// </summary>
protected virtual void StartLazyWriterTimer()
{
lock (lockObject)
{
if (lazyWriterTimer != null)
{
lazyWriterTimer.Change(TimeToSleepBetweenBatches, Timeout.Infinite);
}
}
}
/// <summary>
/// Starts the lazy writer thread.
/// </summary>
protected virtual void StopLazyWriterThread()
{
lock (lockObject)
{
if (lazyWriterTimer != null)
{
lazyWriterTimer.Change(Timeout.Infinite, Timeout.Infinite);
lazyWriterTimer = null;
}
}
}
/// <summary>
/// Adds the log event to asynchronous queue to be processed by
/// the lazy writer thread.
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <remarks>
/// The <see cref="Target.PrecalculateVolatileLayouts" /> is called
/// to ensure that the log event can be processed in another thread.
/// </remarks>
protected override void Write(AsyncLogEventInfo logEvent)
{
PrecalculateVolatileLayouts(logEvent.LogEvent);
RequestQueue.Enqueue(logEvent);
}
private void ProcessPendingEvents(object state)
{
try
{
var count = BatchSize;
var continuation = Interlocked.Exchange(ref flushAllContinuation, null);
if (continuation != null)
{
count = RequestQueue.RequestCount;
InternalLogger.Trace("Flushing {0} events.", count);
}
var logEventInfos = RequestQueue.DequeueBatch(count);
if (continuation != null)
{
// write all events, then flush, then call the continuation
WrappedTarget.WriteAsyncLogEvents(logEventInfos, ex => WrappedTarget.Flush(continuation));
}
else
{
// just write all events
WrappedTarget.WriteAsyncLogEvents(logEventInfos);
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error in lazy writer timer procedure: {0}", exception);
}
finally
{
StartLazyWriterTimer();
}
}
}
}
| |
namespace StudentManagementSystem.Authentication.MongoDb
{
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Identity;
using MongoDB.Bson.Serialization.Attributes;
public class IdentityUser : IdentityUser<string>
{
public IdentityUser() : base()
{
Id = Guid.NewGuid().ToString();
}
public IdentityUser(string userName) : this()
{
UserName = userName;
}
}
public class IdentityUser<TKey> : IdentityUser<IdentityRole<TKey>, TKey>
where TKey : IEquatable<TKey>
{
public IdentityUser() : base()
{
}
public IdentityUser(string userName) : base(userName)
{
}
}
public class IdentityUser<TRole, TKey> : IUser<TKey>
where TRole : IdentityRole<TKey>
where TKey : IEquatable<TKey>
{
public IdentityUser() { }
public IdentityUser(string userName) : this()
{
UserName = userName;
}
public virtual TKey Id { get; set; }
public virtual string UserName { get; set; }
/// /// <summary>
/// NOTE: should not be used except when extending SaanSoft.AspNet.Identity3.MongoDB.
/// Value will be overridden by RoleStore.
/// Used to store the username that is formatted in a case insensitive way so can do searches on it
/// </summary>
public virtual string NormalizedUserName { get; set; }
/// <summary>
/// Email
/// </summary>
public virtual string Email { get; set; }
/// /// <summary>
/// NOTE: should not be used except when extending SaanSoft.AspNet.Identity3.MongoDB.
/// Value will be overridden by RoleStore.
/// Used to store the email that is formatted in a case insensitive way so can do searches on it
/// </summary>
public virtual string NormalizedEmail { get; set; }
/// <summary>
/// True if the email is confirmed, default is false
/// </summary>
public virtual bool EmailConfirmed { get; set; }
/// <summary>
/// The salted/hashed form of the user password
/// </summary>
public virtual string PasswordHash { get; set; }
/// <summary>
/// A random value that should change whenever a user's credentials change (ie, password changed, login removed)
/// </summary>
public virtual string SecurityStamp { get; set; }
/// <summary>
/// PhoneNumber for the user
/// </summary>
public virtual string PhoneNumber { get; set; }
/// <summary>
/// True if the phone number is confirmed, default is false
/// </summary>
public virtual bool PhoneNumberConfirmed { get; set; }
/// <summary>
/// Is two factor enabled for the user
/// </summary>
public virtual bool TwoFactorEnabled { get; set; }
/// <summary>
/// DateTime in UTC when lockout ends, any time in the past is considered not locked out.
/// </summary>
public virtual DateTimeOffset? LockoutEnd { get; set; }
/// <summary>
/// Is lockout enabled for this user
/// </summary>
public virtual bool LockoutEnabled { get; set; }
/// <summary>
/// Used to record failures for the purposes of lockout
/// </summary>
public virtual int AccessFailedCount { get; set; }
/// <summary>
/// Navigation property for users in the role
/// </summary>
public virtual IList<TRole> Roles
{
get { return _roles; }
set { _roles = value ?? new List<TRole>(); }
}
private IList<TRole> _roles = new List<TRole>();
/// <summary>
/// Navigation property for users claims
/// </summary>
public virtual IList<IdentityClaim> Claims
{
get { return _claims; }
set { _claims = value ?? new List<IdentityClaim>(); }
}
private IList<IdentityClaim> _claims = new List<IdentityClaim>();
/// <summary>
/// Get a list of all user's claims combined with claims from role
/// </summary>
[BsonElement]
public virtual IList<IdentityClaim> AllClaims
{
get
{
// as Claims and Roles are virtual and could be overridden with an implementation that allows nulls
// - make sure they aren't null just in case
var clms = Claims ?? new List<IdentityClaim>();
var rls = Roles ?? new List<TRole>();
return clms.Concat(rls.Where(r => r.Claims != null).SelectMany(r => r.Claims)).Distinct().ToList();
}
}
/// <summary>
/// Navigation property for users logins
/// </summary>
public virtual IList<UserLoginInfo> Logins
{
get { return _logins; }
set { _logins = value ?? new List<UserLoginInfo>(); }
}
private IList<UserLoginInfo> _logins = new List<UserLoginInfo>();
/// <summary>
/// Returns a friendly name
/// </summary>
/// <returns></returns>
public override string ToString()
{
return UserName;
}
#region IEquatable<TKey> (Equals, GetHashCode(), ==, !=)
public override bool Equals(object obj)
{
if (!(obj is IdentityUser<TRole, TKey>)) return false;
var thisObj = (IdentityUser<TRole, TKey>)obj;
return this.Equals(thisObj);
}
public virtual bool Equals(IdentityUser<TRole, TKey> obj)
{
if (obj == null) return false;
return this.Id.Equals(obj.Id);
}
public static bool operator ==(IdentityUser<TRole, TKey> left, IdentityUser<TRole, TKey> right)
{
return Equals(left, right);
}
public static bool operator !=(IdentityUser<TRole, TKey> left, IdentityUser<TRole, TKey> right)
{
return !Equals(left, right);
}
public override int GetHashCode()
{
unchecked
{
return StringComparer.OrdinalIgnoreCase.GetHashCode(this.Id);
}
}
#endregion
}
}
| |
using Orleans.Serialization;
namespace Orleans.CodeGenerator
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans.Async;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils;
using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
/// <summary>
/// Implements a code generator using the Roslyn C# compiler.
/// </summary>
public class RoslynCodeGenerator : IRuntimeCodeGenerator, ISourceCodeGenerator, ICodeGeneratorCache
{
/// <summary>
/// The compiled assemblies.
/// </summary>
private readonly ConcurrentDictionary<string, CachedAssembly> CompiledAssemblies =
new ConcurrentDictionary<string, CachedAssembly>();
/// <summary>
/// The logger.
/// </summary>
private static readonly Logger Logger = LogManager.GetLogger("CodeGenerator");
/// <summary>
/// The serializer generation manager.
/// </summary>
private readonly SerializerGenerationManager serializerGenerationManager;
/// <summary>
/// Initializes a new instance of the <see cref="RoslynCodeGenerator"/> class.
/// </summary>
/// <param name="serializationManager">The serialization manager.</param>
public RoslynCodeGenerator(SerializationManager serializationManager)
{
this.serializerGenerationManager = new SerializerGenerationManager(serializationManager);
}
/// <summary>
/// Adds a pre-generated assembly.
/// </summary>
/// <param name="targetAssemblyName">
/// The name of the assembly the provided <paramref name="generatedAssembly"/> targets.
/// </param>
/// <param name="generatedAssembly">
/// The generated assembly.
/// </param>
public void AddGeneratedAssembly(string targetAssemblyName, GeneratedAssembly generatedAssembly)
{
CompiledAssemblies.TryAdd(targetAssemblyName, new CachedAssembly(generatedAssembly));
}
/// <summary>
/// Generates code for all loaded assemblies and loads the output.
/// </summary>
public IReadOnlyList<GeneratedAssembly> GenerateAndLoadForAllAssemblies()
{
return this.GenerateAndLoadForAssemblies(AppDomain.CurrentDomain.GetAssemblies());
}
/// <summary>
/// Generates and loads code for the specified inputs.
/// </summary>
/// <param name="inputs">The assemblies to generate code for.</param>
public IReadOnlyList<GeneratedAssembly> GenerateAndLoadForAssemblies(params Assembly[] inputs)
{
if (inputs == null)
{
throw new ArgumentNullException(nameof(inputs));
}
var results = new List<GeneratedAssembly>();
var timer = Stopwatch.StartNew();
var emitDebugSymbols = false;
foreach (var input in inputs)
{
if (!emitDebugSymbols)
{
emitDebugSymbols |= RuntimeVersion.IsAssemblyDebugBuild(input);
}
RegisterGeneratedCodeTargets(input);
var cached = TryLoadGeneratedAssemblyFromCache(input);
if (cached != null)
{
results.Add(cached);
}
}
var grainAssemblies = inputs.Where(ShouldGenerateCodeForAssembly).ToList();
if (grainAssemblies.Count == 0)
{
// Already up to date.
return results;
}
try
{
// Generate code for newly loaded assemblies.
var generatedSyntax = GenerateForAssemblies(grainAssemblies, true);
CachedAssembly generatedAssembly;
if (generatedSyntax.Syntax != null)
{
generatedAssembly = CompileAndLoad(generatedSyntax, emitDebugSymbols);
if (generatedAssembly != null)
{
results.Add(generatedAssembly);
}
}
else
{
generatedAssembly = new CachedAssembly { Loaded = true };
}
foreach (var assembly in generatedSyntax.SourceAssemblies)
{
CompiledAssemblies.AddOrUpdate(
assembly.GetName().FullName,
generatedAssembly,
(_, __) => generatedAssembly);
}
if (Logger.IsVerbose2)
{
Logger.Verbose2(
ErrorCode.CodeGenCompilationSucceeded,
"Generated code for {0} assemblies in {1}ms",
generatedSyntax.SourceAssemblies.Count,
timer.ElapsedMilliseconds);
}
return results;
}
catch (Exception exception)
{
var assemblyNames = string.Join("\n", grainAssemblies.Select(_ => _.GetName().FullName));
var message =
$"Exception generating code for input assemblies:\n{assemblyNames}\nException: {LogFormatter.PrintException(exception)}";
Logger.Warn(ErrorCode.CodeGenCompilationFailed, message, exception);
throw;
}
}
/// <summary>
/// Ensures that code generation has been run for the provided assembly.
/// </summary>
/// <param name="input">
/// The assembly to generate code for.
/// </param>
public GeneratedAssembly GenerateAndLoadForAssembly(Assembly input)
{
try
{
RegisterGeneratedCodeTargets(input);
if (!ShouldGenerateCodeForAssembly(input))
{
return TryLoadGeneratedAssemblyFromCache(input);
}
var timer = Stopwatch.StartNew();
var generated = GenerateForAssemblies(new List<Assembly> { input }, true);
CachedAssembly generatedAssembly;
if (generated.Syntax != null)
{
var emitDebugSymbols = RuntimeVersion.IsAssemblyDebugBuild(input);
generatedAssembly = CompileAndLoad(generated, emitDebugSymbols);
}
else
{
generatedAssembly = new CachedAssembly { Loaded = true };
}
foreach (var assembly in generated.SourceAssemblies)
{
CompiledAssemblies.AddOrUpdate(
assembly.GetName().FullName,
generatedAssembly,
(_, __) => generatedAssembly);
}
if (Logger.IsVerbose2)
{
Logger.Verbose2(
ErrorCode.CodeGenCompilationSucceeded,
"Generated code for 1 assembly in {0}ms",
timer.ElapsedMilliseconds);
}
return generatedAssembly;
}
catch (Exception exception)
{
var message =
$"Exception generating code for input assembly {input.GetName().FullName}\nException: {LogFormatter.PrintException(exception)}";
Logger.Warn(ErrorCode.CodeGenCompilationFailed, message, exception);
throw;
}
}
/// <summary>
/// Generates source code for the provided assembly.
/// </summary>
/// <param name="input">
/// The assembly to generate source for.
/// </param>
/// <returns>
/// The generated source.
/// </returns>
public string GenerateSourceForAssembly(Assembly input)
{
RegisterGeneratedCodeTargets(input);
if (!ShouldGenerateCodeForAssembly(input))
{
return string.Empty;
}
var generated = GenerateForAssemblies(new List<Assembly> { input }, false);
if (generated.Syntax == null)
{
return string.Empty;
}
return CodeGeneratorCommon.GenerateSourceCode(CodeGeneratorCommon.AddGeneratedCodeAttribute(generated));
}
/// <summary>
/// Returns the collection of generated assemblies as pairs of target assembly name to raw assembly bytes.
/// </summary>
/// <returns>The collection of generated assemblies.</returns>
public IDictionary<string, GeneratedAssembly> GetGeneratedAssemblies()
{
return CompiledAssemblies.ToDictionary(_ => _.Key, _ => (GeneratedAssembly)_.Value);
}
/// <summary>
/// Attempts to load a generated assembly from the cache.
/// </summary>
/// <param name="targetAssembly">
/// The target assembly which the cached counterpart is generated for.
/// </param>
private CachedAssembly TryLoadGeneratedAssemblyFromCache(Assembly targetAssembly)
{
CachedAssembly cached;
if (!CompiledAssemblies.TryGetValue(targetAssembly.GetName().FullName, out cached)
|| cached.RawBytes == null || cached.Loaded)
{
return cached;
}
// Load the assembly and mark it as being loaded.
cached.Assembly = LoadAssembly(cached);
cached.Loaded = true;
return cached;
}
/// <summary>
/// Compiles the provided syntax tree, and loads and returns the result.
/// </summary>
/// <param name="generatedSyntax">The syntax tree.</param>
/// <param name="emitDebugSymbols">
/// Whether or not to emit debug symbols for the generated assembly.
/// </param>
/// <returns>The compilation output.</returns>
private static CachedAssembly CompileAndLoad(GeneratedSyntax generatedSyntax, bool emitDebugSymbols)
{
var generated = CodeGeneratorCommon.CompileAssembly(generatedSyntax, "OrleansCodeGen", emitDebugSymbols: emitDebugSymbols);
var loadedAssembly = LoadAssembly(generated);
return new CachedAssembly(generated)
{
Loaded = true,
Assembly = loadedAssembly,
};
}
/// <summary>
/// Loads the specified assembly.
/// </summary>
/// <param name="asm">The assembly to load.</param>
private static Assembly LoadAssembly(GeneratedAssembly asm)
{
#if ORLEANS_BOOTSTRAP
throw new NotImplementedException();
#elif NETSTANDARD
Assembly result;
result = Orleans.PlatformServices.PlatformAssemblyLoader.LoadFromBytes(asm.RawBytes, asm.DebugSymbolRawBytes);
AppDomain.CurrentDomain.AddAssembly(result);
return result;
#else
if (asm.DebugSymbolRawBytes != null)
{
return Assembly.Load(
asm.RawBytes,
asm.DebugSymbolRawBytes);
}
else
{
return Assembly.Load(asm.RawBytes);
}
#endif
}
/// <summary>
/// Generates a syntax tree for the provided assemblies.
/// </summary>
/// <param name="assemblies">The assemblies to generate code for.</param>
/// <param name="runtime">Whether or not runtime code generation is being performed.</param>
/// <returns>The generated syntax tree.</returns>
private GeneratedSyntax GenerateForAssemblies(List<Assembly> assemblies, bool runtime)
{
if (Logger.IsVerbose)
{
Logger.Verbose(
"Generating code for assemblies: {0}",
string.Join(", ", assemblies.Select(_ => _.FullName)));
}
Assembly targetAssembly;
HashSet<Type> ignoredTypes;
if (runtime)
{
// Ignore types which have already been accounted for.
ignoredTypes = GetTypesWithGeneratedSupportClasses();
targetAssembly = null;
}
else
{
ignoredTypes = new HashSet<Type>();
targetAssembly = assemblies.FirstOrDefault();
}
var members = new List<MemberDeclarationSyntax>();
// Include assemblies which are marked as included.
var knownAssemblyAttributes = new Dictionary<Assembly, KnownAssemblyAttribute>();
var knownAssemblies = new HashSet<Assembly>();
foreach (var attribute in assemblies.SelectMany(asm => asm.GetCustomAttributes<KnownAssemblyAttribute>()))
{
knownAssemblyAttributes[attribute.Assembly] = attribute;
knownAssemblies.Add(attribute.Assembly);
}
if (knownAssemblies.Count > 0)
{
knownAssemblies.UnionWith(assemblies);
assemblies = knownAssemblies.ToList();
}
// Get types from assemblies which reference Orleans and are not generated assemblies.
var includedTypes = new HashSet<Type>();
for (var i = 0; i < assemblies.Count; i++)
{
var assembly = assemblies[i];
foreach (var attribute in assembly.GetCustomAttributes<ConsiderForCodeGenerationAttribute>())
{
ConsiderType(attribute.Type, runtime, targetAssembly, includedTypes, considerForSerialization: true);
if (attribute.ThrowOnFailure && !serializerGenerationManager.IsTypeRecorded(attribute.Type))
{
throw new CodeGenerationException(
$"Found {attribute.GetType().Name} for type {attribute.Type.GetParseableName()}, but code"
+ " could not be generated. Ensure that the type is accessible.");
}
}
KnownAssemblyAttribute knownAssemblyAttribute;
var considerAllTypesForSerialization = knownAssemblyAttributes.TryGetValue(assembly, out knownAssemblyAttribute)
&& knownAssemblyAttribute.TreatTypesAsSerializable;
foreach (var type in TypeUtils.GetDefinedTypes(assembly, Logger))
{
var considerForSerialization = considerAllTypesForSerialization || type.IsSerializable;
ConsiderType(type.AsType(), runtime, targetAssembly, includedTypes, considerForSerialization);
}
}
includedTypes.RemoveWhere(_ => ignoredTypes.Contains(_));
// Group the types by namespace and generate the required code in each namespace.
foreach (var group in includedTypes.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_)))
{
var namespaceMembers = new List<MemberDeclarationSyntax>();
foreach (var type in group)
{
// The module containing the serializer.
var module = runtime ? null : type.GetTypeInfo().Module;
// Every type which is encountered must be considered for serialization.
Action<Type> onEncounteredType = encounteredType =>
{
// If a type was encountered which can be accessed, process it for serialization.
serializerGenerationManager.RecordTypeToGenerate(encounteredType, module, targetAssembly);
};
if (Logger.IsVerbose2)
{
Logger.Verbose2("Generating code for: {0}", type.GetParseableName());
}
if (GrainInterfaceUtils.IsGrainInterface(type))
{
if (Logger.IsVerbose2)
{
Logger.Verbose2(
"Generating GrainReference and MethodInvoker for {0}",
type.GetParseableName());
}
GrainInterfaceUtils.ValidateInterfaceRules(type);
namespaceMembers.Add(GrainReferenceGenerator.GenerateClass(type, onEncounteredType));
namespaceMembers.Add(GrainMethodInvokerGenerator.GenerateClass(type));
}
// Generate serializers.
var first = true;
Type toGen;
while (serializerGenerationManager.GetNextTypeToProcess(out toGen))
{
if (!runtime)
{
if (first)
{
ConsoleText.WriteStatus("ClientGenerator - Generating serializer classes for types:");
first = false;
}
ConsoleText.WriteStatus(
"\ttype " + toGen.FullName + " in namespace " + toGen.Namespace
+ " defined in Assembly " + toGen.GetTypeInfo().Assembly.GetName());
}
if (Logger.IsVerbose2)
{
Logger.Verbose2(
"Generating & Registering Serializer for Type {0}",
toGen.GetParseableName());
}
namespaceMembers.Add(SerializerGenerator.GenerateClass(toGen, onEncounteredType));
}
}
if (namespaceMembers.Count == 0)
{
if (Logger.IsVerbose)
{
Logger.Verbose2("Skipping namespace: {0}", group.Key);
}
continue;
}
members.Add(
SF.NamespaceDeclaration(SF.ParseName(group.Key))
.AddUsings(
TypeUtils.GetNamespaces(typeof(TaskUtility), typeof(GrainExtensions), typeof(IntrospectionExtensions))
.Select(_ => SF.UsingDirective(SF.ParseName(_)))
.ToArray())
.AddMembers(namespaceMembers.ToArray()));
}
return new GeneratedSyntax
{
SourceAssemblies = assemblies,
Syntax = members.Count > 0 ? SF.CompilationUnit().AddMembers(members.ToArray()) : null
};
}
private void ConsiderType(
Type type,
bool runtime,
Assembly targetAssembly,
ISet<Type> includedTypes,
bool considerForSerialization = false)
{
// The module containing the serializer.
var typeInfo = type.GetTypeInfo();
var module = runtime || !Equals(typeInfo.Assembly, targetAssembly) ? null : typeInfo.Module;
// If a type was encountered which can be accessed and is marked as [Serializable], process it for serialization.
if (considerForSerialization)
{
RecordType(type, module, targetAssembly, includedTypes);
}
// Consider generic arguments to base types and implemented interfaces for code generation.
ConsiderGenericBaseTypeArguments(typeInfo, module, targetAssembly, includedTypes);
ConsiderGenericInterfacesArguments(typeInfo, module, targetAssembly, includedTypes);
// Include grain interface types.
if (GrainInterfaceUtils.IsGrainInterface(type))
{
// If code generation is being performed at runtime, the interface must be accessible to the generated code.
if (!runtime || TypeUtilities.IsAccessibleFromAssembly(type, targetAssembly))
{
if (Logger.IsVerbose2) Logger.Verbose2("Will generate code for: {0}", type.GetParseableName());
includedTypes.Add(type);
}
}
}
private void RecordType(Type type, Module module, Assembly targetAssembly, ISet<Type> includedTypes)
{
if (serializerGenerationManager.RecordTypeToGenerate(type, module, targetAssembly))
{
includedTypes.Add(type);
}
}
private void ConsiderGenericBaseTypeArguments(
TypeInfo typeInfo,
Module module,
Assembly targetAssembly,
ISet<Type> includedTypes)
{
if (typeInfo.BaseType == null) return;
if (!typeInfo.BaseType.IsConstructedGenericType) return;
foreach (var type in typeInfo.BaseType.GetGenericArguments())
{
RecordType(type, module, targetAssembly, includedTypes);
}
}
private void ConsiderGenericInterfacesArguments(
TypeInfo typeInfo,
Module module,
Assembly targetAssembly,
ISet<Type> includedTypes)
{
var interfaces = typeInfo.GetInterfaces().Where(x => x.IsConstructedGenericType);
foreach (var type in interfaces.SelectMany(v => v.GetTypeInfo().GetGenericArguments()))
{
RecordType(type, module, targetAssembly, includedTypes);
}
}
/// <summary>
/// Get types which have corresponding generated classes.
/// </summary>
/// <returns>Types which have corresponding generated classes marked.</returns>
private static HashSet<Type> GetTypesWithGeneratedSupportClasses()
{
// Get assemblies which contain generated code.
var all =
AppDomain.CurrentDomain.GetAssemblies()
.Where(assemblies => assemblies.GetCustomAttribute<GeneratedCodeAttribute>() != null)
.SelectMany(assembly => TypeUtils.GetDefinedTypes(assembly, Logger));
// Get all generated types in each assembly.
var attributes = all.SelectMany(_ => _.GetCustomAttributes<GeneratedAttribute>());
var results = new HashSet<Type>();
foreach (var attribute in attributes)
{
if (attribute.TargetType != null)
{
results.Add(attribute.TargetType);
}
}
return results;
}
/// <summary>
/// Returns a value indicating whether or not code should be generated for the provided assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>A value indicating whether or not code should be generated for the provided assembly.</returns>
private bool ShouldGenerateCodeForAssembly(Assembly assembly)
{
return !assembly.IsDynamic && !CompiledAssemblies.ContainsKey(assembly.GetName().FullName)
&& TypeUtils.IsOrleansOrReferencesOrleans(assembly)
&& assembly.GetCustomAttribute<GeneratedCodeAttribute>() == null
&& assembly.GetCustomAttribute<SkipCodeGenerationAttribute>() == null;
}
/// <summary>
/// Registers the input assembly with this class.
/// </summary>
/// <param name="input">The assembly to register.</param>
private void RegisterGeneratedCodeTargets(Assembly input)
{
var targets = input.GetCustomAttributes<OrleansCodeGenerationTargetAttribute>();
foreach (var target in targets)
{
CompiledAssemblies.TryAdd(target.AssemblyName, new CachedAssembly { Loaded = true });
}
}
[Serializable]
private class CachedAssembly : GeneratedAssembly
{
public CachedAssembly()
{
}
public CachedAssembly(GeneratedAssembly generated) : base(generated)
{
}
/// <summary>
/// Gets or sets a value indicating whether or not the assembly has been loaded.
/// </summary>
public bool Loaded { get; set; }
}
}
}
| |
using Signum.Engine.Translation;
using Signum.React.Filters;
using Signum.Utilities;
using Signum.Utilities.DataStructures;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using Signum.Engine.Basics;
using Signum.Entities.Translation;
using Signum.Entities;
using Signum.Engine.Maps;
using Signum.Utilities.Reflection;
using Signum.React.Files;
using System.IO;
using Signum.Engine.Mailing;
namespace Signum.React.Translation
{
[ValidateModelFilter]
public class TranslatedInstanceController : ControllerBase
{
[HttpGet("api/translatedInstance")]
public List<TranslatedTypeSummaryTS> Status()
{
return TranslatedInstanceLogic.TranslationInstancesStatus().Select(a => new TranslatedTypeSummaryTS(a)).ToList();
}
[HttpGet("api/translatedInstance/view/{type}")]
public TranslatedInstanceViewTypeTS View(string type, string? culture, string filter)
{
Type t = TypeLogic.GetType(type);
var c = culture == null ? null : CultureInfo.GetCultureInfo(culture);
var master = TranslatedInstanceLogic.FromEntities(t);
var support = TranslatedInstanceLogic.TranslationsForType(t, culture: c);
var all = string.IsNullOrEmpty(filter);
var cultures = TranslationLogic.CurrentCultureInfos(TranslatedInstanceLogic.DefaultCulture);
Func<LocalizedInstanceKey, bool> filtered = li =>
{
if (all)
return true;
if (li.RowId.ToString() == filter || li.Instance.Id.ToString() == filter || li.Instance.Key() == filter)
return true;
if (li.Route.PropertyString().Contains(filter, StringComparison.InvariantCultureIgnoreCase))
return true;
if (master.GetOrThrow(li)?.Contains(filter, StringComparison.InvariantCultureIgnoreCase) == true)
return true;
if (cultures.Any(ci => (support.TryGetC(ci)?.TryGetC(li)?.TranslatedText ?? "").Contains(filter, StringComparison.InvariantCultureIgnoreCase)))
return true;
return false;
};
var sd = new StringDistance();
var supportByInstance = (from kvpCult in support
from kvpLocIns in kvpCult.Value
where filtered(kvpLocIns.Key)
let newText = master.TryGet(kvpLocIns.Key, null)
group (lockIns: kvpLocIns.Key, translatedInstance: kvpLocIns.Value, culture: kvpCult.Key, newText: newText) by kvpLocIns.Key.Instance into gInstance
select KeyValuePair.Create(gInstance.Key,
gInstance.AgGroupToDictionary(a => a.lockIns.RouteAndRowId(),
gr => gr.ToDictionary(a => a.culture.Name, a => new TranslatedPairViewTS
{
OriginalText = a.translatedInstance.OriginalText,
Diff = a.translatedInstance.OriginalText.Equals(a.newText) ? null : sd.DiffText(a.translatedInstance.OriginalText, a.newText),
TranslatedText = a.translatedInstance.TranslatedText
})
))).ToDictionary();
return new TranslatedInstanceViewTypeTS
{
TypeName = type,
Routes = TranslatedInstanceLogic.TranslateableRoutes.GetOrThrow(t).ToDictionary(a => a.Key.PropertyString(), a => a.Value),
MasterCulture = TranslatedInstanceLogic.DefaultCulture.Name,
Instances = master.Where(kvp => filtered(kvp.Key)).GroupBy(a => a.Key.Instance).Select(gr => new TranslatedInstanceViewTS
{
Lite = gr.Key,
Master = gr.ToDictionary(
a => a.Key.RouteAndRowId(),
a => a.Value!
),
Translations = supportByInstance.TryGetC(gr.Key) ?? new Dictionary<string, Dictionary<string, TranslatedPairViewTS>>()
}).ToList()
};
}
[HttpGet("api/translatedInstance/sync/{type}")]
public TypeInstancesChangesTS Sync(string type, string culture)
{
Type t = TypeLogic.GetType(type);
var c = CultureInfo.GetCultureInfo(culture);
int totalInstances;
var changes = TranslatedInstanceSynchronizer.GetTypeInstanceChangesTranslated(TranslationServer.Translators, t, c, out totalInstances);
var sd = new StringDistance();
return new TypeInstancesChangesTS
{
MasterCulture = TranslatedInstanceLogic.DefaultCulture.Name,
Routes = TranslatedInstanceLogic.TranslateableRoutes.GetOrThrow(t).ToDictionary(a => a.Key.PropertyString(), a => a.Value),
TotalInstances = totalInstances,
TypeName = t.Name,
Instances = changes.Instances.Select(a => new InstanceChangesTS
{
Instance = a.Instance,
RouteConflicts = a.RouteConflicts.ToDictionaryEx(
ipr => ipr.Key.RouteRowId(),
ipr => new PropertyChangeTS
{
Support = ipr.Value.ToDictionaryEx(c => c.Key.Name, c => new PropertyRouteConflictTS
{
Original = c.Value.Original,
OldOriginal = c.Value.OldOriginal,
OldTranslation = c.Value.OldTranslation,
Diff = c.Value.OldOriginal == null || c.Value.Original == null || c.Value.OldOriginal.Equals(c.Value.Original) ? null : sd.DiffText(c.Value.OldOriginal, c.Value.Original),
AutomaticTranslations = c.Value.AutomaticTranslations.ToArray(),
})
}
)
}).ToList()
};
}
[HttpPost("api/translatedInstance/save/{type}")]
public void Save([Required, FromBody] List<TranslationRecordTS> body, string type, string? culture)
{
Type t = TypeLogic.GetType(type);
CultureInfo? c = culture == null ? null : CultureInfo.GetCultureInfo(culture);
var records = GetTranslationRecords(body, t);
TranslatedInstanceLogic.SaveRecords(records, t, c);
}
private List<TranslationRecord> GetTranslationRecords(List<TranslationRecordTS> records, Type type)
{
var propertyRoute = TranslatedInstanceLogic.TranslateableRoutes.GetOrThrow(type).Keys
.ToDictionaryEx(pr => pr.PropertyString(), pr =>
{
var mlistPr = pr.GetMListItemsRoute();
var mlistPkType = mlistPr == null ? null : ((FieldMList)Schema.Current.Field(mlistPr.Parent!)).TableMList.PrimaryKey.Type;
return (pr, mlistPkType);
});
var list = (from rec in records
let c = CultureInfo.GetCultureInfo(rec.Culture)
let prInfo = propertyRoute.GetOrThrow(rec.PropertyRoute)
select new TranslationRecord
{
Culture = c,
Key = new LocalizedInstanceKey(
prInfo.pr,
rec.Lite,
prInfo.mlistPkType == null ? (PrimaryKey?)null : new PrimaryKey((IComparable)ReflectionTools.Parse(rec.RowId!, prInfo.mlistPkType)!)
),
OriginalText = rec.OriginalText,
TranslatedText = rec.TranslatedText,
}).ToList();
return list;
}
[HttpGet("api/translatedInstance/viewFile/{type}")]
public FileStreamResult ViewFile(string type, string culture)
{
Type t = TypeLogic.GetType(type);
var c = CultureInfo.GetCultureInfo(culture);
var file = TranslatedInstanceLogic.ExportExcelFile(t, c);
return FilesController.GetFileStreamResult(file);
}
[HttpGet("api/translatedInstance/syncFile/{type}")]
public FileStreamResult SyncFile(string type, string culture)
{
Type t = TypeLogic.GetType(type);
var c = CultureInfo.GetCultureInfo(culture);
var file = TranslatedInstanceLogic.ExportExcelFileSync(t, c);
return FilesController.GetFileStreamResult(file);
}
[HttpPost("api/translatedInstance/uploadFile")]
public void UploadFile([Required, FromBody] FileUpload file)
{
TranslatedInstanceLogic.ImportExcelFile(new MemoryStream(file.content), file.fileName);
}
}
public class TranslationRecordTS
{
public string Culture;
public string PropertyRoute;
public string? RowId;
public Lite<Entity> Lite;
public string OriginalText;
public string TranslatedText;
}
public class TypeInstancesChangesTS
{
public string TypeName;
public string MasterCulture;
public int TotalInstances;
public List<InstanceChangesTS> Instances;
public Dictionary<string, TranslateableRouteType> Routes { get; internal set; }
}
public class InstanceChangesTS
{
public Lite<Entity> Instance;
public Dictionary<string, PropertyChangeTS> RouteConflicts;
}
public class PropertyChangeTS
{
public string? TranslatedText;
public Dictionary<string, PropertyRouteConflictTS> Support;
}
public class PropertyRouteConflictTS
{
public string? OldOriginal;
public string? OldTranslation;
public string Original;
public AutomaticTranslation[]? AutomaticTranslations;
public List<StringDistance.DiffPair<List<StringDistance.DiffPair<string>>>>? Diff { get; set; }
}
public class FileUpload
{
public string fileName;
public byte[] content;
}
public class TranslatedInstanceViewTypeTS
{
public string TypeName;
public string MasterCulture;
public Dictionary<string, TranslateableRouteType> Routes;
public List<TranslatedInstanceViewTS> Instances;
}
public class TranslatedInstanceViewTS
{
public Lite<Entity> Lite;
public Dictionary<string, string> Master;
public Dictionary<string, Dictionary<string, TranslatedPairViewTS>> Translations;
}
public class TranslatedPairViewTS
{
public string OriginalText { get; set; }
public string TranslatedText { get; set; }
public List<StringDistance.DiffPair<List<StringDistance.DiffPair<string>>>>? Diff { get; set; }
}
public class TranslatedTypeSummaryTS
{
public string Type { get; }
public bool IsDefaultCulture { get; }
public string Culture { get; }
public TranslatedSummaryState? State { get; }
public TranslatedTypeSummaryTS(TranslatedTypeSummary ts)
{
this.IsDefaultCulture = ts.CultureInfo.Name == TranslatedInstanceLogic.DefaultCulture.Name;
this.Type = TypeLogic.GetCleanName(ts.Type);
this.Culture = ts.CultureInfo.Name;
this.State = ts.State;
}
}
}
| |
//
// UsbDevice.cs
//
// Author:
// Alex Launi <[email protected]>
//
// Copyright (c) 2010 Alex Launi
//
// 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.
#if ENABLE_GIO_HARDWARE
using System;
using Banshee.Hardware;
using GUdev;
using System.Globalization;
namespace Banshee.Hardware.Gio
{
class UsbDevice : IUsbDevice, IRawDevice
{
const string UdevUsbBusNumber = "BUSNUM";
const string UdevUsbDeviceNumber = "DEVNUM";
const string UdevVendorId = "ID_VENDOR_ID";
const string UdevProductId = "ID_MODEL_ID";
internal static UsbDevice ResolveRootDevice (IDevice device)
{
// First check if the supplied device is an IUsbDevice itself
var result = Resolve (device);
if (result != null) {
return result;
}
// Now walk up the device tree to see if we can find one.
IRawDevice raw = device as IRawDevice;
if (raw != null) {
var parent = raw.Device.UdevMetadata.Parent;
while (parent != null) {
if (parent.PropertyExists (UdevUsbBusNumber) && parent.PropertyExists (UdevUsbDeviceNumber)) {
return new UsbDevice (new RawUsbDevice (raw.Device.Manager, raw.Device.GioMetadata, parent));
}
parent = parent.Parent;
}
}
return null;
}
public IUsbDevice ResolveRootUsbDevice ()
{
return this;
}
public IUsbPortInfo ResolveUsbPortInfo ()
{
return new UsbPortInfo (BusNumber, DeviceNumber);
}
public static int GetBusNumber (IUsbDevice device)
{
var raw = device as IRawDevice;
return raw == null ? 0 : int.Parse (raw.Device.UdevMetadata.GetPropertyString (UdevUsbBusNumber));
}
public static int GetDeviceNumber (IUsbDevice device)
{
var raw = device as IRawDevice;
return raw == null ? 0 : int.Parse (raw.Device.UdevMetadata.GetPropertyString (UdevUsbDeviceNumber));
}
public static int GetProductId (IUsbDevice device)
{
var raw = device as IRawDevice;
return raw == null ? 0 : int.Parse (raw.Device.UdevMetadata.GetPropertyString (UdevProductId), NumberStyles.HexNumber);
}
public static int GetSpeed (IUsbDevice device)
{
throw new NotImplementedException ();
}
public static int GetVendorId (IUsbDevice device)
{
var raw = device as IRawDevice;
return raw == null ? 0 : int.Parse (raw.Device.UdevMetadata.GetPropertyString (UdevVendorId), NumberStyles.HexNumber);
}
public static int GetVersion (IUsbDevice device)
{
throw new NotImplementedException ();
}
public static UsbDevice Resolve (IDevice device)
{
IRawDevice raw = device as IRawDevice;
if (raw != null) {
var metadata = raw.Device.UdevMetadata;
if (metadata.PropertyExists (UdevUsbBusNumber) && metadata.PropertyExists (UdevUsbDeviceNumber))
return new UsbDevice (raw.Device);
}
return null;
}
public RawDevice Device {
get; set;
}
public int BusNumber {
get { return GetBusNumber (this); }
}
public int DeviceNumber {
get { return GetDeviceNumber (this); }
}
public string Name {
get { return Device.Name; }
}
public IDeviceMediaCapabilities MediaCapabilities {
get { return Device.MediaCapabilities; }
}
public string Product {
get { return Device.Product;}
}
public int ProductId {
get { return GetProductId (this); }
}
public string Serial {
get { return Device.Serial; }
}
// What is this and why do we want it?
public double Speed {
get { return GetSpeed (this); }
}
public string Uuid {
get { return Device.Uuid; }
}
public string Vendor {
get { return Device.Vendor; }
}
public int VendorId {
get { return GetVendorId (this); }
}
// What is this and why do we want it?
public double Version {
get { return GetVersion (this); }
}
UsbDevice (RawDevice device)
{
Device = device;
}
bool IDevice.PropertyExists (string key)
{
return Device.PropertyExists (key);
}
string IDevice.GetPropertyString (string key)
{
return Device.GetPropertyString (key);
}
double IDevice.GetPropertyDouble (string key)
{
return Device.GetPropertyDouble (key);
}
bool IDevice.GetPropertyBoolean (string key)
{
return Device.GetPropertyBoolean (key);
}
int IDevice.GetPropertyInteger (string key)
{
return Device.GetPropertyInteger (key);
}
ulong IDevice.GetPropertyUInt64 (string key)
{
return Device.GetPropertyUInt64 (key);
}
public string[] GetPropertyStringList (string key)
{
return Device.GetPropertyStringList (key);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Utilities;
using Signum.Entities.DynamicQuery;
using System.Text.RegularExpressions;
using Signum.Utilities.Reflection;
using Signum.Utilities.DataStructures;
using Signum.Entities.UserAssets;
using Newtonsoft.Json;
namespace Signum.Entities.Omnibox
{
public class DynamicQueryOmniboxResultGenerator :OmniboxResultGenerator<DynamicQueryOmniboxResult>
{
private static List<FilterSyntax> SyntaxSequence(Match m)
{
return m.Groups["filter"].Captures().Select(filter => new FilterSyntax
{
Index = filter.Index,
TokenLength = m.Groups["token"].Captures().Single(filter.Contains).Length,
Length = filter.Length,
Completion = m.Groups["val"].Captures().Any(filter.Contains) ? FilterSyntaxCompletion.Complete :
m.Groups["op"].Captures().Any(filter.Contains) ? FilterSyntaxCompletion.Operation : FilterSyntaxCompletion.Token,
}).ToList();
}
Regex regex = new Regex(@"^I(?<filter>(?<token>I(\.I)*)(\.|((?<op>=)(?<val>[ENSIG])?))?)*$", RegexOptions.ExplicitCapture);
public override IEnumerable<DynamicQueryOmniboxResult> GetResults(string rawQuery, List<OmniboxToken> tokens, string tokenPattern)
{
Match m = regex.Match(tokenPattern);
if (!m.Success)
yield break;
string pattern = tokens[0].Value;
bool isPascalCase = OmniboxUtils.IsPascalCasePattern(pattern);
List<FilterSyntax>? syntaxSequence = null;
foreach (var match in OmniboxUtils.Matches(OmniboxParser.Manager.GetQueries(), OmniboxParser.Manager.AllowedQuery, pattern, isPascalCase).OrderBy(ma => ma.Distance))
{
var queryName = match.Value;
if (syntaxSequence == null)
syntaxSequence = SyntaxSequence(m);
if (syntaxSequence.Any())
{
QueryDescription description = OmniboxParser.Manager.GetDescription(match.Value);
IEnumerable<IEnumerable<OmniboxFilterResult>> bruteFilters = syntaxSequence.Select(a => GetFilterQueries(rawQuery, description, a, tokens));
foreach (var list in bruteFilters.CartesianProduct())
{
yield return new DynamicQueryOmniboxResult
{
QueryName = match.Value,
QueryNameMatch = match,
Distance = match.Distance + list.Average(a => a.Distance),
Filters = list.ToList(),
};
}
}
else
{
if (match.Text == pattern && tokens.Count == 1 && tokens[0].Next(rawQuery) == ' ')
{
QueryDescription description = OmniboxParser.Manager.GetDescription(match.Value);
foreach (var qt in QueryUtils.SubTokens(null, description, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement))
{
yield return new DynamicQueryOmniboxResult
{
QueryName = match.Value,
QueryNameMatch = match,
Distance = match.Distance,
Filters = new List<OmniboxFilterResult> { new OmniboxFilterResult(0, null, qt, null) },
};
}
}
else
{
yield return new DynamicQueryOmniboxResult
{
QueryName = match.Value,
QueryNameMatch = match,
Distance = match.Distance,
Filters = new List<OmniboxFilterResult>()
};
}
}
}
}
protected IEnumerable<OmniboxFilterResult> GetFilterQueries(string rawQuery, QueryDescription queryDescription, FilterSyntax syntax, List<OmniboxToken> tokens)
{
List<OmniboxFilterResult> result = new List<OmniboxFilterResult>();
int operatorIndex = syntax.Index + syntax.TokenLength;
List<(QueryToken token, ImmutableStack<OmniboxMatch> stack)> ambiguousTokens = GetAmbiguousTokens(null, ImmutableStack<OmniboxMatch>.Empty,
queryDescription, tokens, syntax.Index, operatorIndex).ToList();
foreach ((QueryToken token, ImmutableStack<OmniboxMatch> stack) pair in ambiguousTokens)
{
var distance = pair.stack.Sum(a => a.Distance);
var tokenMatches = pair.stack.Reverse().ToArray();
var token = pair.token;
if (syntax.Completion == FilterSyntaxCompletion.Token)
{
if (tokens[operatorIndex - 1].Next(rawQuery) == '.' && pair.stack.All(a => ((QueryToken)a.Value).ToString().ToOmniboxPascal() == a.Text))
{
foreach (var qt in QueryUtils.SubTokens(pair.token, queryDescription, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement))
{
result.Add(new OmniboxFilterResult(distance, syntax, qt, tokenMatches));
}
}
else
{
result.Add(new OmniboxFilterResult(distance, syntax, token, tokenMatches));
}
}
else
{
string? canFilter = QueryUtils.CanFilter(pair.token);
if (canFilter.HasText())
{
result.Add(new OmniboxFilterResult(distance, syntax, token, tokenMatches)
{
CanFilter = canFilter,
});
}
else
{
FilterOperation operation = FilterValueConverter.ParseOperation(tokens[operatorIndex].Value);
if (syntax.Completion == FilterSyntaxCompletion.Operation)
{
var suggested = SugestedValues(pair.token);
if (suggested == null)
{
result.Add(new OmniboxFilterResult(distance, syntax, token, tokenMatches)
{
Operation = operation,
});
}
else
{
foreach (var item in suggested)
{
result.Add(new OmniboxFilterResult(distance, syntax, token, tokenMatches)
{
Operation = operation,
Value = item.Value
});
}
}
}
else
{
var values = GetValues(pair.token, tokens[operatorIndex + 1]);
foreach (var value in values)
{
result.Add(new OmniboxFilterResult(distance, syntax, token, tokenMatches)
{
Operation = operation,
Value = value.Value,
ValueMatch = value.Match,
});
}
}
}
}
}
return result;
}
public static readonly string UnknownValue = "??UNKNOWN??";
public struct ValueTuple
{
public object? Value;
public OmniboxMatch? Match;
}
protected virtual ValueTuple[]? SugestedValues(QueryToken queryToken)
{
var ft = QueryUtils.GetFilterType(queryToken.Type);
switch (ft)
{
case FilterType.Integer:
case FilterType.Decimal: return new[] { new ValueTuple { Value = Activator.CreateInstance(queryToken.Type.UnNullify()), Match = null } };
case FilterType.String: return new[] { new ValueTuple { Value = "", Match = null } };
case FilterType.DateTime: return new[] { new ValueTuple { Value = DateTime.Today, Match = null } };
case FilterType.Lite:
case FilterType.Embedded: break;
case FilterType.Boolean: return new[] { new ValueTuple { Value = true, Match = null }, new ValueTuple { Value = false, Match = null } };
case FilterType.Enum: return EnumEntity.GetValues(queryToken.Type.UnNullify()).Select(e => new ValueTuple { Value = e, Match = null }).ToArray();
case FilterType.Guid: break;
}
return null;
}
public int AutoCompleteLimit = 5;
protected virtual ValueTuple[] GetValues(QueryToken queryToken, OmniboxToken omniboxToken)
{
if (omniboxToken.IsNull())
return new[] { new ValueTuple { Value = null, Match = null } };
var ft = QueryUtils.GetFilterType(queryToken.Type);
switch (ft)
{
case FilterType.Integer:
case FilterType.Decimal:
if (omniboxToken.Type == OmniboxTokenType.Number)
{
if (ReflectionTools.TryParse(omniboxToken.Value, queryToken.Type, out object? result))
return new[] { new ValueTuple { Value = result, Match = null } };
}
break;
case FilterType.String:
if (omniboxToken.Type == OmniboxTokenType.String)
return new[] { new ValueTuple { Value = OmniboxUtils.CleanCommas(omniboxToken.Value), Match = null } };
break;
case FilterType.DateTime:
if (omniboxToken.Type == OmniboxTokenType.String)
{
var str = OmniboxUtils.CleanCommas(omniboxToken.Value);
if (ReflectionTools.TryParse(str, queryToken.Type, out object? result))
return new[] { new ValueTuple { Value = result, Match = null } };
}
break;
case FilterType.Lite:
if (omniboxToken.Type == OmniboxTokenType.String)
{
var patten = OmniboxUtils.CleanCommas(omniboxToken.Value);
var result = OmniboxParser.Manager.Autocomplete(queryToken.GetImplementations()!.Value, patten, AutoCompleteLimit);
return result.Select(lite => new ValueTuple { Value = lite, Match = OmniboxUtils.Contains(lite, lite.ToString()!, patten) }).ToArray();
}
else if (omniboxToken.Type == OmniboxTokenType.Entity)
{
var error = Lite.TryParseLite(omniboxToken.Value, out Lite<Entity>? lite);
if (string.IsNullOrEmpty(error))
return new []{new ValueTuple { Value = lite }};
}
else if (omniboxToken.Type == OmniboxTokenType.Number)
{
var imp = queryToken.GetImplementations()!.Value;
if (!imp.IsByAll)
{
return imp.Types.Select(t => CreateLite(t, omniboxToken.Value))
.NotNull().Select(t => new ValueTuple { Value = t }).ToArray();
}
}break;
case FilterType.Embedded:
case FilterType.Boolean:
bool? boolean = ParseBool(omniboxToken.Value);
if (boolean.HasValue)
return new []{ new ValueTuple{ Value = boolean.Value} };
break;
case FilterType.Enum:
if (omniboxToken.Type == OmniboxTokenType.String ||
omniboxToken.Type == OmniboxTokenType.Identifier)
{
string value = omniboxToken.Type == OmniboxTokenType.Identifier ? omniboxToken.Value : OmniboxUtils.CleanCommas(omniboxToken.Value);
bool isPascalValue = OmniboxUtils.IsPascalCasePattern(value);
Type enumType = queryToken.Type.UnNullify();
var dic = EnumEntity.GetValues(enumType).ToOmniboxPascalDictionary(a => a.NiceToString(), a => (object)a);
var result = OmniboxUtils.Matches(dic, e => true, value, isPascalValue)
.Select(m => new ValueTuple { Value = m.Value, Match = m })
.ToArray();
return result;
}
break;
case FilterType.Guid:
if (omniboxToken.Type == OmniboxTokenType.Guid)
{
if (Guid.TryParse(omniboxToken.Value, out Guid result))
return new[] { new ValueTuple { Value = result, Match = null } };
}
else if (omniboxToken.Type == OmniboxTokenType.String)
{
var str = OmniboxUtils.CleanCommas(omniboxToken.Value);
if (Guid.TryParse(str, out Guid result))
return new[] { new ValueTuple { Value = result, Match = null } };
}
break;
default:
break;
}
return new[] { new ValueTuple { Value = UnknownValue, Match = null } };
}
Lite<Entity>? CreateLite(Type type, string value)
{
if (PrimaryKey.TryParse(value, type, out PrimaryKey id))
return Lite.Create(type, id, "{0} {1}".FormatWith(type.NiceName(), id));
return null;
}
bool? ParseBool(string val)
{
val = val.ToLower().RemoveDiacritics();
if (val == "true" || val == "t" || val == "yes" || val == "y" || val == OmniboxMessage.Yes.NiceToString())
return true;
if (val == "false" || val == "f" || val == "no" || val == "n" || val == OmniboxMessage.No.NiceToString())
return false;
return null;
}
protected virtual IEnumerable<(QueryToken token, ImmutableStack<OmniboxMatch> stack)> GetAmbiguousTokens(QueryToken? queryToken, ImmutableStack<OmniboxMatch> distancePack,
QueryDescription queryDescription, List<OmniboxToken> omniboxTokens, int index, int operatorIndex)
{
OmniboxToken omniboxToken = omniboxTokens[index];
bool isPascal = OmniboxUtils.IsPascalCasePattern(omniboxToken.Value);
var dic = QueryUtils.SubTokens(queryToken, queryDescription, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement).ToOmniboxPascalDictionary(qt => qt.ToString(), qt => qt);
var matches = OmniboxUtils.Matches(dic, qt => qt.IsAllowed() == null, omniboxToken.Value, isPascal);
if (index == operatorIndex - 1)
{
foreach (var m in matches)
{
var token = (QueryToken)m.Value;
yield return (token: token, stack: distancePack.Push(m));
}
}
else
{
foreach (var m in matches)
foreach (var newPair in GetAmbiguousTokens((QueryToken)m.Value, distancePack.Push(m), queryDescription, omniboxTokens, index + 2, operatorIndex))
yield return newPair;
}
}
public static string ToStringValue(object? p)
{
if (p == null)
return "null";
switch (QueryUtils.GetFilterType(p.GetType()))
{
case FilterType.Integer:
case FilterType.Decimal: return p.ToString()!;
case FilterType.String: return "\"" + p.ToString() + "\"";
case FilterType.DateTime: return "'" + p.ToString() + "'";
case FilterType.Lite: return ((Lite<Entity>)p).Key();
case FilterType.Embedded: throw new InvalidOperationException("Impossible to translate not null Embedded entity to string");
case FilterType.Boolean: return p.ToString()!;
case FilterType.Enum: return ((Enum)p).NiceToString().SpacePascal();
case FilterType.Guid: return "\"" + p.ToString() + "\"";
}
throw new InvalidOperationException("Unexpected value type {0}".FormatWith(p.GetType()));
}
public override List<HelpOmniboxResult> GetHelp()
{
var resultType = typeof(DynamicQueryOmniboxResult);
var queryName = OmniboxMessage.Omnibox_Query.NiceToString();
var field = OmniboxMessage.Omnibox_Field.NiceToString();
var value = OmniboxMessage.Omnibox_Value.NiceToString();
return new List<HelpOmniboxResult>
{
new HelpOmniboxResult { Text = "{0}".FormatWith(queryName), ReferencedType = resultType },
new HelpOmniboxResult { Text = "{0} {1}='{2}'".FormatWith(queryName, field, value), ReferencedType = resultType },
new HelpOmniboxResult { Text = "{0} {1}1='{2}1' {1}2='{2}2'".FormatWith(queryName, field, value), ReferencedType = resultType },
};
}
}
public class DynamicQueryOmniboxResult : OmniboxResult
{
[JsonConverter(typeof(QueryNameJsonConverter))]
public object QueryName { get; set; }
public OmniboxMatch QueryNameMatch { get; set; }
public List<OmniboxFilterResult> Filters { get; set; }
public override string ToString()
{
string queryName = QueryUtils.GetNiceName(QueryName).ToOmniboxPascal();
string filters = Filters.ToString(" ");
if (string.IsNullOrEmpty(filters))
return queryName;
else
return queryName + " " + filters;
}
}
public class OmniboxFilterResult
{
public OmniboxFilterResult(float distance, FilterSyntax? syntax, DynamicQuery.QueryToken queryToken, OmniboxMatch[]? omniboxMatch)
{
this.Distance = distance;
this.Syntax = syntax;
this.QueryToken = queryToken;
this.QueryTokenMatches = omniboxMatch;
}
public float Distance { get; set; }
public FilterSyntax? Syntax {get; set;}
[JsonConverter(typeof(QueryTokenJsonConverter))]
public QueryToken QueryToken { get; set; }
public string? QueryTokenOmniboxPascal => QueryToken?.Follow(a => a.Parent).Reverse().ToString(a => a.ToString().ToOmniboxPascal(), ".");
public OmniboxMatch[]? QueryTokenMatches { get; set; }
public FilterOperation? Operation { get; set; }
public string? OperationToString => this.Operation == null ? null : FilterValueConverter.ToStringOperation(this.Operation.Value);
public string? ValueToString => this.Value == null ? null : DynamicQueryOmniboxResultGenerator.ToStringValue(this.Value);
public object? Value { get; set; }
public OmniboxMatch? ValueMatch { get; set; }
public string CanFilter { get; set; }
public override string ToString()
{
string token = QueryToken.Follow(q => q.Parent).Reverse().Select(a => a.ToString().ToOmniboxPascal()).ToString(".");
if (Syntax == null || Syntax.Completion == FilterSyntaxCompletion.Token || CanFilter.HasText())
return token;
string oper = FilterValueConverter.ToStringOperation(Operation!.Value);
if ((Syntax.Completion == FilterSyntaxCompletion.Operation && Value == null) ||
(Value as string == DynamicQueryOmniboxResultGenerator.UnknownValue))
return token + oper;
return token + oper + DynamicQueryOmniboxResultGenerator.ToStringValue(Value);
}
}
public class FilterSyntax
{
public int Index;
public int TokenLength;
public int Length;
public FilterSyntaxCompletion Completion;
}
public enum FilterSyntaxCompletion
{
Token,
Operation,
Complete,
}
//User 2
//ped cus.per.add.cit=="London" fj>'2012'
//FVL N="hola"
public class QueryNameJsonConverter : JsonConverter
{
public static Func<object, string> GetQueryKey;
public override bool CanConvert(Type objectType)
{
return true;
}
public override bool CanWrite => true;
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
writer.WriteValue(GetQueryKey(value!));
}
public override bool CanRead => false;
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class QueryTokenJsonConverter : JsonConverter
{
public static Func<QueryToken, object> GetQueryTokenTS;
public override bool CanConvert(Type objectType)
{
return true;
}
public override bool CanWrite => true;
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
serializer.Serialize(writer, GetQueryTokenTS((QueryToken)value!));
}
public override bool CanRead => false;
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.