context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using Signum.Entities.Basics;
using Signum.Entities.Workflow;
namespace Signum.Engine.Workflow;
public static class CaseFlowLogic
{
public static CaseFlow GetCaseFlow(CaseEntity @case)
{
var averages = new Dictionary<Lite<IWorkflowNodeEntity>, double?>();
averages.AddRange(@case.Workflow.WorkflowActivities().Select(a => KeyValuePair.Create((Lite<IWorkflowNodeEntity>)a.ToLite(), a.AverageDuration())));
averages.AddRange(@case.Workflow.WorkflowEvents().Where(e => e.Type == WorkflowEventType.IntermediateTimer).Select(e => KeyValuePair.Create((Lite<IWorkflowNodeEntity>)e.ToLite(), e.AverageDuration())));
var caseActivities = @case.CaseActivities().Select(ca => new CaseActivityStats
{
CaseActivity = ca.ToLite(),
PreviousActivity = ca.Previous,
WorkflowActivity = ca.WorkflowActivity.ToLite(),
WorkflowActivityType = (WorkflowActivityType?)(ca.WorkflowActivity as WorkflowActivityEntity)!.Type,
WorkflowEventType = (WorkflowEventType?)(ca.WorkflowActivity as WorkflowEventEntity)!.Type,
SubWorkflow = (ca.WorkflowActivity as WorkflowActivityEntity).Try(wa => wa.SubWorkflow).Try(sw => sw.Workflow.ToLite()),
BpmnElementId = ca.WorkflowActivity.BpmnElementId,
Notifications = ca.Notifications().Count(),
StartDate = ca.StartDate,
DoneDate = ca.DoneDate,
DoneType = ca.DoneType,
DoneDecision = ca.DoneDecision,
DoneBy = ca.DoneBy,
Duration = ca.Duration,
AverageDuration = averages.TryGetS(ca.WorkflowActivity.ToLite()),
EstimatedDuration = ca.WorkflowActivity is WorkflowActivityEntity ?
((WorkflowActivityEntity)ca.WorkflowActivity).EstimatedDuration :
((WorkflowEventEntity)ca.WorkflowActivity).Timer!.Duration == null ? (double?)null :
((WorkflowEventEntity)ca.WorkflowActivity).Timer!.Duration!.ToTimeSpan().TotalMinutes,
}).ToDictionary(a => a.CaseActivity);
var gr = WorkflowLogic.GetWorkflowNodeGraph(@case.Workflow.ToLite());
IEnumerable<CaseConnectionStats>? GetSyncPaths(CaseActivityStats prev, IWorkflowNodeEntity from, IWorkflowNodeEntity to)
{
if (prev.DoneType == DoneType.Timeout)
{
if (from is WorkflowActivityEntity wa)
{
var conns = wa.BoundaryTimers.Where(a => a.Type == WorkflowEventType.BoundaryInterruptingTimer)
.SelectMany(e => gr.GetAllConnections(e, to, path => path.All(a => a.Type == ConnectionType.Normal)));
if (conns.Any())
return conns.Select(c => new CaseConnectionStats().WithConnection(c).WithDone(prev));
}
else if (from is WorkflowEventEntity we)
{
var conns = gr.GetAllConnections(we, to, path => path.All(a => a.Type == ConnectionType.Normal)); ;
if (conns.Any())
return conns.Select(c => new CaseConnectionStats().WithConnection(c).WithDone(prev));
}
}
else
{
var conns = gr.GetAllConnections(from, to, path => IsValidPath(prev.DoneType!.Value, prev.DoneDecision, path));
if (conns.Any())
return conns.Select(c => new CaseConnectionStats().WithConnection(c).WithDone(prev));
}
return null;
}
var connections = caseActivities.Values
.Where(cs => cs.PreviousActivity != null && caseActivities.ContainsKey(cs.PreviousActivity))
.SelectMany(cs =>
{
var prev = caseActivities.GetOrThrow(cs.PreviousActivity!);
var from = gr.GetNode(prev.WorkflowActivity);
var to = gr.GetNode(cs.WorkflowActivity);
if (prev.DoneType.HasValue)
{
var res = GetSyncPaths(prev, from, to);
if (res != null)
return res;
}
if (from is WorkflowActivityEntity waFork)
{
var conns = waFork.BoundaryTimers.Where(a => a.Type == WorkflowEventType.BoundaryForkTimer).SelectMany(e => gr.GetAllConnections(e, to, path => path.All(a => a.Type == ConnectionType.Normal)));
if (conns.Any())
return conns.Select(c => new CaseConnectionStats().WithConnection(c).WithDone(prev));
}
return new[]
{
new CaseConnectionStats
{
FromBpmnElementId = from.BpmnElementId,
ToBpmnElementId = to.BpmnElementId,
}.WithDone(prev)
};
}).ToList();
var isInPrevious = caseActivities.Values.Select(a => a.PreviousActivity).ToHashSet();
connections.AddRange(caseActivities.Values
.Where(cs => cs.DoneDate.HasValue && !isInPrevious.Contains(cs.CaseActivity))
.Select(cs =>
{
var from = gr.GetNode(cs.WorkflowActivity);
var candidates = cs.DoneType == DoneType.Timeout && from is WorkflowActivityEntity wa ?
wa.BoundaryTimers.SelectMany(e => gr.NextConnections(e)) :
gr.NextConnections(from);
var nextConnection = candidates
.SingleOrDefaultEx(c => IsCompatible(c.Type, cs.DoneType!.Value) && (c.DoneDecision() == null || c.DoneDecision() == cs.DoneDecision) && gr.IsParallelGateway(c.To, WorkflowGatewayDirection.Join));
if (nextConnection != null)
return new CaseConnectionStats().WithConnection(nextConnection).WithDone(cs);
return null;
}).NotNull());
var firsts = caseActivities.Values.Where(a => (a.PreviousActivity == null || !caseActivities.ContainsKey(a.PreviousActivity)));
foreach (var f in firsts)
{
WorkflowEventEntity? start = GetStartEvent(@case, f.CaseActivity, gr);
if (start != null)
connections.AddRange(gr.GetAllConnections(start, gr.GetNode(f.WorkflowActivity), path => path.All(a => a.Type == ConnectionType.Normal))
.Select(c => new CaseConnectionStats().WithConnection(c).WithDone(f)));
}
if(@case.FinishDate != null)
{
var lasts = caseActivities.Values.Where(last => !caseActivities.Values.Any(a => a.PreviousActivity.Is(last.CaseActivity))).ToList();
var ends = gr.Events.Values.Where(a => a.Type == WorkflowEventType.Finish);
foreach (var last in lasts)
{
var from = gr.GetNode(last.WorkflowActivity);
var compatibleEnds = ends.Select(end => GetSyncPaths(last, from, end)).NotNull().ToList();
if (compatibleEnds.Count != 0)
{
foreach (var path in compatibleEnds)
{
connections.AddRange(path);
}
}
else //Cancel Case
{
var firstEnd = ends.FirstOrDefault();
if(firstEnd != null)
{
connections.Add(new CaseConnectionStats
{
FromBpmnElementId = from.BpmnElementId,
ToBpmnElementId = firstEnd.BpmnElementId,
}.WithDone(last));
}
}
}
}
return new CaseFlow
{
Activities = caseActivities.Values.GroupToDictionary(a => a.BpmnElementId),
Connections = connections.Where(a => a.BpmnElementId != null).GroupToDictionary(a => a.BpmnElementId!),
Jumps = connections.Where(a => a.BpmnElementId == null).ToList(),
AllNodes = connections.Select(a => a.FromBpmnElementId!)
.Union(connections.Select(a => a.ToBpmnElementId!)).ToList()
};
}
private static bool IsCompatible(ConnectionType type, DoneType doneType)
{
switch (doneType)
{
case DoneType.Next:return type == ConnectionType.Normal;
case DoneType.Jump: return type == ConnectionType.Jump;
case DoneType.Timeout: return type == ConnectionType.Normal;
case DoneType.ScriptSuccess: return type == ConnectionType.Normal;
case DoneType.ScriptFailure: return type == ConnectionType.ScriptException;
case DoneType.Recompose: return type == ConnectionType.Normal;
default: throw new UnexpectedValueException(doneType);
}
}
private static bool IsValidPath(DoneType doneType, string? doneDecision, Stack<WorkflowConnectionEntity> path)
{
switch (doneType)
{
case DoneType.Next:
case DoneType.ScriptSuccess:
case DoneType.Recompose:
return path.All(a => a.Type == ConnectionType.Normal || doneDecision != null && (a.DoneDecision() == doneDecision));
case DoneType.Jump: return path.All(a => a.Is(path.FirstEx()) ? a.Type == ConnectionType.Jump : a.Type == ConnectionType.Normal);
case DoneType.ScriptFailure: return path.All(a => a.Is(path.FirstEx()) ? a.Type == ConnectionType.ScriptException : a.Type == ConnectionType.Normal);
case DoneType.Timeout:
default:
throw new InvalidOperationException();
}
}
private static WorkflowEventEntity? GetStartEvent(CaseEntity @case, Lite<CaseActivityEntity> firstActivity, WorkflowNodeGraph gr)
{
var wet = Database.Query<OperationLogEntity>()
.Where(l => l.Operation.Is(CaseActivityOperation.CreateCaseFromWorkflowEventTask.Symbol) && l.Target.Is(@case))
.Select(l => new { l.Origin, l.User })
.SingleOrDefaultEx();
if (wet != null)
{
var lite = ((Lite<WorkflowEventTaskEntity>)wet.Origin!).InDB(a => a.Event);
return lite == null ? null : gr.Events.GetOrThrow(lite);
}
bool register = Database.Query<OperationLogEntity>()
.Where(l => l.Operation.Is(CaseActivityOperation.Register.Symbol) && l.Target.Is(firstActivity) && l.Exception == null)
.Any();
if (register)
return gr.Events.Values.SingleEx(a => a.Type == WorkflowEventType.Start);
return gr.Events.Values.Where(a => a.Type.IsStart()).Only();
}
}
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
public class CaseActivityStats
{
public Lite<CaseActivityEntity> CaseActivity;
public Lite<CaseActivityEntity>? PreviousActivity;
public Lite<IWorkflowNodeEntity> WorkflowActivity;
public WorkflowActivityType? WorkflowActivityType;
public WorkflowEventType? WorkflowEventType;
public Lite<WorkflowEntity>? SubWorkflow;
public int Notifications;
public DateTime StartDate;
public DateTime? DoneDate;
public DoneType? DoneType;
public string? DoneDecision;
public Lite<IUserEntity>? DoneBy;
public double? Duration;
public double? AverageDuration;
public double? EstimatedDuration;
public string BpmnElementId { get; internal set; }
}
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
public class CaseConnectionStats
{
public CaseConnectionStats WithConnection(WorkflowConnectionEntity c)
{
this.BpmnElementId = c.BpmnElementId;
this.Connection = c.ToLite();
this.FromBpmnElementId = c.From.BpmnElementId;
this.ToBpmnElementId = c.To.BpmnElementId;
return this;
}
public CaseConnectionStats WithDone(CaseActivityStats activity)
{
this.DoneBy = activity.DoneBy;
this.DoneDate = activity.DoneDate;
this.DoneType = activity.DoneType;
this.DoneDecision = activity.DoneDecision;
return this;
}
public Lite<WorkflowConnectionEntity>? Connection;
public DateTime? DoneDate;
public Lite<IUserEntity>? DoneBy;
public DoneType? DoneType;
public string? DoneDecision { get; private set; }
public string? BpmnElementId { get; internal set; }
public string? FromBpmnElementId { get; internal set; }
public string? ToBpmnElementId { get; internal set; }
public override string ToString() => $"{FromBpmnElementId} =({DoneType})=> {ToBpmnElementId}";
}
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
public class CaseFlow
{
public Dictionary<string, List<CaseActivityStats>> Activities;
public Dictionary<string, List<CaseConnectionStats>> Connections;
public List<CaseConnectionStats> Jumps;
public List<string> AllNodes;
}
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
| |
// 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.
/*============================================================
**
**
**
** Purpose: A representation of an IEEE double precision
** floating point number.
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Internal.Runtime.CompilerServices;
namespace System
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct Double : IComparable, IConvertible, IFormattable, IComparable<Double>, IEquatable<Double>, ISpanFormattable
{
private double m_value; // Do not rename (binary serialization)
//
// Public Constants
//
public const double MinValue = -1.7976931348623157E+308;
public const double MaxValue = 1.7976931348623157E+308;
// Note Epsilon should be a double whose hex representation is 0x1
// on little endian machines.
public const double Epsilon = 4.9406564584124654E-324;
public const double NegativeInfinity = (double)-1.0 / (double)(0.0);
public const double PositiveInfinity = (double)1.0 / (double)(0.0);
public const double NaN = (double)0.0 / (double)0.0;
// We use this explicit definition to avoid the confusion between 0.0 and -0.0.
internal const double NegativeZero = -0.0;
/// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsFinite(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
return (bits & 0x7FFFFFFFFFFFFFFF) < 0x7FF0000000000000;
}
/// <summary>Determines whether the specified value is infinite.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsInfinity(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
return (bits & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000;
}
/// <summary>Determines whether the specified value is NaN.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNaN(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
return (bits & 0x7FFFFFFFFFFFFFFF) > 0x7FF0000000000000;
}
/// <summary>Determines whether the specified value is negative.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNegative(double d)
{
var bits = unchecked((ulong)BitConverter.DoubleToInt64Bits(d));
return (bits & 0x8000000000000000) == 0x8000000000000000;
}
/// <summary>Determines whether the specified value is negative infinity.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsNegativeInfinity(double d)
{
return (d == double.NegativeInfinity);
}
/// <summary>Determines whether the specified value is normal.</summary>
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsNormal(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
bits &= 0x7FFFFFFFFFFFFFFF;
return (bits < 0x7FF0000000000000) && (bits != 0) && ((bits & 0x7FF0000000000000) != 0);
}
/// <summary>Determines whether the specified value is positive infinity.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsPositiveInfinity(double d)
{
return (d == double.PositiveInfinity);
}
/// <summary>Determines whether the specified value is subnormal.</summary>
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsSubnormal(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
bits &= 0x7FFFFFFFFFFFFFFF;
return (bits < 0x7FF0000000000000) && (bits != 0) && ((bits & 0x7FF0000000000000) == 0);
}
// Compares this object to another object, returning an instance of System.Relation.
// Null is considered less than any instance.
//
// If object is not of type Double, this method throws an ArgumentException.
//
// Returns a value less than zero if this object
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is Double)
{
double d = (double)value;
if (m_value < d) return -1;
if (m_value > d) return 1;
if (m_value == d) return 0;
// At least one of the values is NaN.
if (IsNaN(m_value))
return (IsNaN(d) ? 0 : -1);
else
return 1;
}
throw new ArgumentException(SR.Arg_MustBeDouble);
}
public int CompareTo(Double value)
{
if (m_value < value) return -1;
if (m_value > value) return 1;
if (m_value == value) return 0;
// At least one of the values is NaN.
if (IsNaN(m_value))
return (IsNaN(value) ? 0 : -1);
else
return 1;
}
// True if obj is another Double with the same value as the current instance. This is
// a method of object equality, that only returns true if obj is also a double.
public override bool Equals(Object obj)
{
if (!(obj is Double))
{
return false;
}
double temp = ((Double)obj).m_value;
// This code below is written this way for performance reasons i.e the != and == check is intentional.
if (temp == m_value)
{
return true;
}
return IsNaN(temp) && IsNaN(m_value);
}
[NonVersionable]
public static bool operator ==(Double left, Double right)
{
return left == right;
}
[NonVersionable]
public static bool operator !=(Double left, Double right)
{
return left != right;
}
[NonVersionable]
public static bool operator <(Double left, Double right)
{
return left < right;
}
[NonVersionable]
public static bool operator >(Double left, Double right)
{
return left > right;
}
[NonVersionable]
public static bool operator <=(Double left, Double right)
{
return left <= right;
}
[NonVersionable]
public static bool operator >=(Double left, Double right)
{
return left >= right;
}
public bool Equals(Double obj)
{
if (obj == m_value)
{
return true;
}
return IsNaN(obj) && IsNaN(m_value);
}
//The hashcode for a double is the absolute value of the integer representation
//of that double.
//
[MethodImpl(MethodImplOptions.AggressiveInlining)] // 64-bit constants make the IL unusually large that makes the inliner to reject the method
public override int GetHashCode()
{
var bits = Unsafe.As<double, long>(ref m_value);
// Optimized check for IsNan() || IsZero()
if (((bits - 1) & 0x7FFFFFFFFFFFFFFF) >= 0x7FF0000000000000)
{
// Ensure that all NaNs and both zeros have the same hash code
bits &= 0x7FF0000000000000;
}
return unchecked((int)bits) ^ ((int)(bits >> 32));
}
public override String ToString()
{
return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format)
{
return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format, IFormatProvider provider)
{
return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider));
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)
{
return Number.TryFormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten);
}
public static double Parse(String s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDouble(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
public static double Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDouble(s, style, NumberFormatInfo.CurrentInfo);
}
public static double Parse(String s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDouble(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}
public static double Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDouble(s, style, NumberFormatInfo.GetInstance(provider));
}
// Parses a double from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
// This method will not throw an OverflowException, but will return
// PositiveInfinity or NegativeInfinity for a number that is too
// large or too small.
public static double Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.ParseDouble(s, style, NumberFormatInfo.GetInstance(provider));
}
public static bool TryParse(String s, out double result)
{
if (s == null)
{
result = 0;
return false;
}
return TryParse((ReadOnlySpan<char>)s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(ReadOnlySpan<char> s, out double result)
{
return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null)
{
result = 0;
return false;
}
return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result);
}
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out double result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out double result)
{
bool success = Number.TryParseDouble(s, style, info, out result);
if (!success)
{
ReadOnlySpan<char> sTrim = s.Trim();
if (sTrim.EqualsOrdinal(info.PositiveInfinitySymbol))
{
result = PositiveInfinity;
}
else if (sTrim.EqualsOrdinal(info.NegativeInfinitySymbol))
{
result = NegativeInfinity;
}
else if (sTrim.EqualsOrdinal(info.NaNSymbol))
{
result = NaN;
}
else
{
return false; // We really failed
}
}
return true;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Double;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return m_value;
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.VFX;
namespace UnityEditor.VFX.Block
{
class SetAttributeVariantReadWritable : VariantProvider
{
protected override sealed Dictionary<string, object[]> variants
{
get
{
return new Dictionary<string, object[]>
{
{ "attribute", VFXAttribute.AllIncludingVariadicReadWritable.Cast<object>().ToArray() },
{ "Source", new object[] { SetAttribute.ValueSource.Slot, SetAttribute.ValueSource.Source } },
{ "Composition", new object[] { AttributeCompositionMode.Overwrite, AttributeCompositionMode.Add, AttributeCompositionMode.Multiply, AttributeCompositionMode.Blend } }
};
}
}
}
[VFXInfo(category = "Attribute/Set", variantProvider = typeof(SetAttributeVariantReadWritable))]
class SetAttribute : VFXBlock
{
public enum ValueSource
{
Slot,
Source
}
[VFXSetting(VFXSettingAttribute.VisibleFlags.InInspector), StringProvider(typeof(ReadWritableAttributeProvider))]
public string attribute = VFXAttribute.AllIncludingVariadic.First();
[VFXSetting(VFXSettingAttribute.VisibleFlags.InInspector)]
public AttributeCompositionMode Composition = AttributeCompositionMode.Overwrite;
[VFXSetting(VFXSettingAttribute.VisibleFlags.InInspector)]
public ValueSource Source = ValueSource.Slot;
[VFXSetting(VFXSettingAttribute.VisibleFlags.InInspector)]
public RandomMode Random = RandomMode.Off;
[VFXSetting]
public VariadicChannelOptions channels = VariadicChannelOptions.XYZ;
private static readonly char[] channelNames = new char[] { 'x', 'y', 'z' };
public override string libraryName
{
get
{
return ComposeName("");
}
}
public override string name
{
get
{
string variadicName = (currentAttribute.variadic == VFXVariadic.True) ? "." + channels.ToString() : "";
return ComposeName(variadicName);
}
}
private string ComposeName(string variadicName)
{
string attributeName = ObjectNames.NicifyVariableName(attribute) + variadicName;
switch (Source)
{
case ValueSource.Slot: return VFXBlockUtility.GetNameString(Composition) + " " + attributeName + " " + VFXBlockUtility.GetNameString(Random);
case ValueSource.Source: return "Inherit Source " + attributeName + " (" + VFXBlockUtility.GetNameString(Composition) + ")";
default: return "NOT IMPLEMENTED : " + Source;
}
}
public override VFXContextType compatibleContexts { get { return VFXContextType.kInitAndUpdateAndOutput; } }
public override VFXDataType compatibleData { get { return VFXDataType.kParticle; } }
public override void Sanitize(int version)
{
if (VFXBlockUtility.SanitizeAttribute(ref attribute, ref channels, version))
Invalidate(InvalidationCause.kSettingChanged);
base.Sanitize(version);
}
protected override IEnumerable<string> filteredOutSettings
{
get
{
if (Source != ValueSource.Slot)
yield return "Random";
if (currentAttribute.variadic == VFXVariadic.False)
yield return "channels";
foreach (var setting in base.filteredOutSettings)
yield return setting;
}
}
public override IEnumerable<VFXAttributeInfo> attributes
{
get
{
var attrib = currentAttribute;
VFXAttributeMode attributeMode = (Composition == AttributeCompositionMode.Overwrite) ? VFXAttributeMode.Write : VFXAttributeMode.ReadWrite;
if (attrib.variadic == VFXVariadic.True)
{
string channelsString = channels.ToString();
for (int i = 0; i < channelsString.Length; i++)
yield return new VFXAttributeInfo(VFXAttribute.Find(attrib.name + channelsString[i]), attributeMode);
}
else
{
yield return new VFXAttributeInfo(attrib, attributeMode);
}
if (Random != RandomMode.Off)
yield return new VFXAttributeInfo(VFXAttribute.Seed, VFXAttributeMode.ReadWrite);
}
}
static private string GenerateLocalAttributeName(string name)
{
return name[0].ToString().ToUpper() + name.Substring(1);
}
public override string source
{
get
{
var attrib = currentAttribute;
string source = "";
int attributeSize = VFXExpression.TypeToSize(attrib.type);
int loopCount = 1;
if (attrib.variadic == VFXVariadic.True)
{
attributeSize = 1;
loopCount = channels.ToString().Length;
}
for (int i = 0; i < loopCount; i++)
{
string paramPostfix = (attrib.variadic == VFXVariadic.True) ? "." + channelNames[i] : "";
string attributePostfix = (attrib.variadic == VFXVariadic.True) ? char.ToUpper(channels.ToString()[i]).ToString() : "";
string channelSource = "";
if (Source == ValueSource.Slot)
{
if (Random == RandomMode.Off)
channelSource = VFXBlockUtility.GetRandomMacroString(Random, attributeSize, paramPostfix, GenerateLocalAttributeName(attrib.name));
else
channelSource = VFXBlockUtility.GetRandomMacroString(Random, attributeSize, paramPostfix, "Min", "Max");
}
else
{
channelSource = VFXBlockUtility.GetRandomMacroString(RandomMode.Off, attributeSize, paramPostfix, "Value");
}
if (Composition == AttributeCompositionMode.Blend)
channelSource = VFXBlockUtility.GetComposeString(Composition, attrib.name + attributePostfix, channelSource, "Blend");
else
channelSource = VFXBlockUtility.GetComposeString(Composition, attrib.name + attributePostfix, channelSource);
if (i < loopCount - 1)
channelSource += "\n";
source += channelSource;
}
return source;
}
}
public override IEnumerable<VFXNamedExpression> parameters
{
get
{
foreach (var param in base.parameters)
{
if ((param.name == "Value" || param.name == "Min" || param.name == "Max") && Source == ValueSource.Source)
continue;
yield return param;
}
if (Source == ValueSource.Source)
{
VFXExpression sourceExpression = null;
var attrib = currentAttribute;
if (attrib.variadic == VFXVariadic.True)
{
var currentChannels = channels.ToString().Select(c => char.ToUpper(c));
var currentChannelsExpression = currentChannels.Select(o =>
{
var subAttrib = VFXAttribute.Find(attribute + o);
return new VFXAttributeExpression(subAttrib, VFXAttributeLocation.Source);
}).ToArray();
if (currentChannelsExpression.Length == 1)
sourceExpression = currentChannelsExpression[0];
else
sourceExpression = new VFXExpressionCombine(currentChannelsExpression);
}
else
{
sourceExpression = new VFXAttributeExpression(attrib, VFXAttributeLocation.Source);
}
yield return new VFXNamedExpression(sourceExpression, "Value");
}
}
}
private int ChannelToIndex(char channel)
{
switch (channel)
{
default:
case 'X': return 0;
case 'Y': return 1;
case 'Z': return 2;
case 'W': return 3;
}
}
protected override IEnumerable<VFXPropertyWithValue> inputProperties
{
get
{
if (Source != ValueSource.Source)
{
var attrib = currentAttribute;
VFXPropertyAttribute[] attr = null;
if (attrib.Equals(VFXAttribute.Color))
attr = VFXPropertyAttribute.Create(new ShowAsColorAttribute());
Type slotType = VFXExpression.TypeToType(attrib.type);
object content = attrib.value.GetContent();
if (attrib.variadic == VFXVariadic.True)
{
string channelsString = channels.ToString();
int length = channelsString.Length;
switch (length)
{
case 1:
slotType = typeof(float);
content = ((Vector3)content)[ChannelToIndex(channelsString[0])];
break;
case 2:
slotType = typeof(Vector2);
Vector2 v = (Vector2)(Vector3)content;
for (int i = 0; i < 2; i++)
v[i] = ((Vector3)content)[ChannelToIndex(channelsString[i])];
content = v;
break;
case 3:
slotType = typeof(Vector3);
break;
default:
break;
}
}
if (Random == RandomMode.Off)
{
yield return new VFXPropertyWithValue(new VFXProperty(slotType, GenerateLocalAttributeName(attrib.name)) { attributes = attr }, content);
}
else
{
yield return new VFXPropertyWithValue(new VFXProperty(slotType, "Min") { attributes = attr }, content);
yield return new VFXPropertyWithValue(new VFXProperty(slotType, "Max") { attributes = attr }, content);
}
}
if (Composition == AttributeCompositionMode.Blend)
yield return new VFXPropertyWithValue(new VFXProperty(typeof(float), "Blend", VFXPropertyAttribute.Create(new RangeAttribute(0.0f, 1.0f))));
}
}
private VFXAttribute currentAttribute
{
get
{
return VFXAttribute.Find(attribute);
}
}
}
}
| |
// 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 XorByte()
{
var test = new SimpleBinaryOpTest__XorByte();
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();
// 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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorByte
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Byte);
private const int Op2ElementCount = VectorSize / sizeof(Byte);
private const int RetElementCount = VectorSize / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector256<Byte> _clsVar1;
private static Vector256<Byte> _clsVar2;
private Vector256<Byte> _fld1;
private Vector256<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable;
static SimpleBinaryOpTest__XorByte()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__XorByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.Xor(
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.Xor(
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.Xor(
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr);
var result = Avx2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorByte();
var result = Avx2.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Byte> left, Vector256<Byte> right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
if ((byte)(left[0] ^ right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((byte)(left[i] ^ right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Xor)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using InAudioSystem;
using InAudioSystem.ExtensionMethods;
using InAudioSystem.Internal;
using UnityEditor;
using UnityEngine;
namespace InAudioSystem.InAudioEditor
{
[CanEditMultipleObjects]
[CustomEditor(typeof(InSplineNode))]
public class InSplineNodeDrawer : Editor
{
InSplineNode SplineNode
{
get { return target as InSplineNode; }
}
private static float range = 0.0f;
private static float maxRange = 100.0f;
private bool expandedConnections = true;
void OnDisable()
{
if (InAudioInstanceFinder.IsValid)
{
InAudioInstanceFinder.InAudioGuiUserPrefs.SelectedSplineController = null;
}
}
void OnEnable()
{
if (InAudioInstanceFinder.IsValid)
{
InAudioInstanceFinder.InAudioGuiUserPrefs.SelectedSplineController = SplineNode.SplineController;
}
}
public override void OnInspectorGUI()
{
if (!InAudioInstanceFinder.IsValid)
{
EditorGUILayout.HelpBox("Please add the InAudio Manager to the scene", MessageType.Info);
if (GUILayout.Button("Add manager to scene"))
{
ErrorDrawer.AddManagerToScene();
}
}
serializedObject.Update();
EditorGUI.BeginChangeCheck();
if (serializedObject.FindProperty("SplineController").hasMultipleDifferentValues)
{
EditorGUILayout.HelpBox("Different spline controllers", MessageType.Warning);
return;
}
if(SplineNode.SplineController == null)
EditorGUILayout.HelpBox("Missing spline controller, please assign one", MessageType.Warning);
if (InAudioInstanceFinder.IsValid)
{
InAudioInstanceFinder.InAudioGuiUserPrefs.SelectedSplineController = SplineNode.SplineController;
}
bool add = GUILayout.Button("Add Node");
bool selectNew = false;
if (GUILayout.Button("Add and Select"))
{
add = true;
selectNew = true;
}
EditorGUILayout.Separator();
var objectField = EditorGUILayout.ObjectField("Controlling Spline", serializedObject.FindProperty("SplineController").objectReferenceValue, typeof(InSpline), true);
if (serializedObject.FindProperty("SplineController").objectReferenceValue == null)
{
serializedObject.FindProperty("SplineController").objectReferenceValue = objectField;
}
if (Selection.objects.Length == 1)
{
GUILayout.Button("Drag node here to connect");
OnDragging.DraggingObject<Object>(GUILayoutUtility.GetLastRect(), o =>
{
GameObject go = o as GameObject;
if (go != null)
{
var node = go.GetComponent<InSplineNode>();
if (node != SplineNode && !SplineNode.SplineController.ContainsConnection(SplineNode, node))
return true;
}
return false;
}, o =>
{
InUndoHelper.RecordObject(SplineNode.SplineController, "Connect nodes");
(o as GameObject).GetComponent<InSplineNode>().ConnectTo(SplineNode);
});
//var a = new SerializedObject(SplineNode.SplineController)
if (SplineNode.SplineController != null)
{
expandedConnections = EditorGUILayout.Foldout(expandedConnections, "Connected to");
for (int i = 0; i < SplineNode.SplineController.Connections.Count; i++)
{
EditorGUILayout.BeginHorizontal();
GUI.enabled = false;
var conc = SplineNode.SplineController.Connections[i];
if (conc.NodeA == SplineNode)
{
EditorGUILayout.ObjectField(conc.NodeB, typeof (InSplineNode), true);
GUI.enabled = true;
if (GUILayout.Button("X", GUILayout.Width(20)))
{
InUndoHelper.RecordObject(SplineNode.SplineController, "Remove spline connection");
SplineNode.SplineController.RemoveConnections(conc);
}
EditorUtility.SetDirty(SplineNode.SplineController);
}
else if (conc.NodeB == SplineNode)
{
EditorGUILayout.ObjectField(conc.NodeA, typeof (InSplineNode), true);
GUI.enabled = true;
if (GUILayout.Button("X", GUILayout.Width(20)))
{
InUndoHelper.RecordObject(SplineNode.SplineController, "Remove spline connection");
SplineNode.SplineController.RemoveConnections(conc);
}
EditorUtility.SetDirty(SplineNode.SplineController);
}
EditorGUILayout.EndHorizontal();
}
}
}
EditorGUILayout.Separator();
bool delete = true;
if (GUILayout.Button("Delete"))
{
InUndoHelper.DoInGroup(() =>
{
#if UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo("Combine nodes");
#else
UndoAll("Delete node");
#endif
foreach (var gameObject in Selection.gameObjects)
{
InUndoHelper.Destroy(gameObject);
}
delete = true;
});
}
if (add)
{
InUndoHelper.DoInGroup(() =>
{
#if UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo("Delete element in spline");
#else
UndoAll("Add new spline node");
#endif
GameObject go = InUndoHelper.CreateGO(SplineNode.SplineController.gameObject.name + " Node");
go.transform.parent = SplineNode.SplineController.transform;
go.transform.position = SplineNode.transform.position + SplineNode.transform.forward;
go.transform.position = SplineNode.transform.position;
var newNode = go.AddComponent<InSplineNode>();
newNode.SplineController = SplineNode.SplineController;
newNode.ConnectTo(SplineNode);
SplineNode.SplineController.Nodes.Add(newNode);
if (selectNew)
Selection.activeGameObject = go;
});
}
if (EditorGUI.EndChangeCheck() && delete == false)
{
serializedObject.ApplyModifiedProperties();
}
}
void OnSceneGUI()
{
int inSplineNodeSelectionCount = Selection.gameObjects.CountIf(go => go.GetComponent<InSplineNode>() != null);
if (inSplineNodeSelectionCount == 1)
{
if (Selection.objects.Length == 1)
{
Handles.BeginGUI();
range = EditorGUI.Slider(new Rect(15, 10, 300, 18), "Range", range, 0.0f, maxRange);
if (SplineNode.SplineController == null)
GUI.enabled = false;
if (GUI.Button(new Rect(15, 30, 200, 20), "Combine nodes in Range"))
{
CombineInRange(SplineNode, range);
Repaint();
}
if (GUI.Button(new Rect(15, 50, 200, 20), "Connect all nodes in Range"))
{
string message = "Connect nodes in range";
UndoAll(message);
ConnectInRange(SplineNode, range);
Repaint();
}
GUI.enabled = true;
Handles.EndGUI();
if (SplineNode.SplineController != null && Selection.activeGameObject != null)
{
Handles.color = Color.red;
Handles.CubeCap(0, Selection.activeGameObject.transform.position, Quaternion.identity, 1.2f * 0.3f);
for (int i = 0; i < SplineNode.SplineController.Nodes.Count; i++)
{
var node = SplineNode.SplineController.Nodes[i];
if (node == SplineNode || node == null)
continue;
if (SplineNode == null)
break;
if (Vector3.Distance(node.transform.position, SplineNode.transform.position) < range)
{
Handles.CubeCap(0, node.gameObject.transform.position, Quaternion.identity, 1.2f * 0.3f);
}
}
Handles.color = Color.white;
}
var color = Color.gray;
Handles.color = color;
if (SplineNode != null)
{
//range = Handles.RadiusHandle(Quaternion.identity, SplineNode.transform.position, range);
}
}
}
else if(inSplineNodeSelectionCount == Selection.objects.Length)
{
if (Selection.activeGameObject != SplineNode.gameObject)
{
Handles.color = Color.red;
if(Selection.activeGameObject != null)
Handles.CubeCap(0, Selection.activeGameObject.transform.position, Quaternion.identity, 0.2f);
Selection.gameObjects.ForEach(go =>
{
var node = go.GetComponent<InSplineNode>();
if(node != null)
Handles.CubeCap(0, node.gameObject.transform.position, Quaternion.identity, 0.2f);
});
Handles.color = Color.white;
GUI.enabled = true;
Handles.BeginGUI();
if (GUI.Button(new Rect(15, 10, 200, 20), "Combine selected nodes"))
{
CombineSelectedNodes();
}
Handles.EndGUI();
}
}
Handles.color = Color.white;
if (SplineNode != null)
{
/*if (Selection.activeGameObject != SplineNode.gameObject)
{
return;
}*/
//if (!Selection.Contains(SplineNode.gameObject))
// return;
InSplineDrawer.OnSceneDraw(SplineNode.SplineController);
}
/* if (Event.current.type == EventType.Layout)
{
HandleUtility.AddDefaultControl(controlID);
}*/
if (GUI.changed && target != null)
EditorUtility.SetDirty(target);
}
private void UndoAll(string message)
{
InUndoHelper.RecordObject(
SplineNode.SplineController.Nodes.Cast<Object>().ToArray().Add(SplineNode.SplineController), message);
}
private void CombineSelectedNodes()
{
InSplineNode splineNode = Selection.activeGameObject.GetComponent<InSplineNode>();
GameObject[] selectedGO = Selection.gameObjects.FindAllNoNulls(go =>
{
var node = go.GetComponent<InSplineNode>();
if (node == null || splineNode == node)
return false;
return true;
});
InSplineNode[] selected = selectedGO.Convert(go => go.GetComponent<InSplineNode>());
CombineNodes(splineNode, selected);
}
private void CombineNodes(InSplineNode splineNode, InSplineNode[] conditioned)
{
InUndoHelper.DoInGroup(() => {
#if UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo("Combine nodes");
#else
UndoAll("Combine nodes");
#endif
HashSet<InSplineNode> periphery = new HashSet<InSplineNode>();
foreach (var node in conditioned)
{
var connected = node.SplineController.FindConnectedNodes(node);
for (int i = 0; i < connected.Length; i++)
{
var connectedTo = connected[i];
periphery.Add(connectedTo);
}
node.UnconnectAll();
}
foreach (var node in conditioned)
{
if(node != null)
InUndoHelper.Destroy(node.gameObject);
}
foreach (var node in periphery)
{
splineNode.ConnectTo(node);
}
var connections = splineNode.SplineController.Connections;
for (int i = 0; i < connections.Count; i++)
{
if (!connections[i].IsValid())
{
connections.SafeRemoveAt(ref i);
}
}
});
//Selection.activeGameObject = null;
Repaint();
}
private void CombineInRange(InSplineNode splineNode, float range)
{
InSplineNode[] inRange = splineNode.SplineController.Nodes.FindAllNoNulls(
n => Vector3.Distance(n.transform.position, splineNode.transform.position) < range && n != splineNode);
CombineNodes(splineNode, inRange);
}
private void ConnectInRange(InSplineNode splineNode, float range)
{
InSplineNode[] inRange = splineNode.SplineController.Nodes.FindAllNoNulls(
n => Vector3.Distance(n.transform.position, splineNode.transform.position) < range);
for (int i = 0; i < inRange.Length; i++)
{
for (int j = i; j < inRange.Length; j++)
{
inRange[i].ConnectTo(inRange[j]);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace EgoLngEditor
{
public partial class FindAndReplaceForm : Form
{
private DataGridView m_DataGridView;
private int m_SearchStartRow;
private int m_SearchStartColumn;
private int m_SearchSelectionIndex;
private List<DataGridViewCell> m_SelectedCells;
public FindAndReplaceForm( DataGridView datagridview )
{
m_SelectedCells = new List<DataGridViewCell>();
InitializeComponent();
InitializeForm(datagridview);
}
public void InitializeForm( DataGridView datagridview )
{
if ( m_DataGridView != datagridview )
{
if (m_DataGridView != null)
{
m_DataGridView.MouseClick -= DataGridView_MouseClick;
}
m_DataGridView = datagridview;
m_DataGridView.MouseClick += new MouseEventHandler(DataGridView_MouseClick);
m_DataGridView.SelectionChanged += new EventHandler(DataGridView_SelectionChanged);
}
if (m_DataGridView.SelectedCells.Count > 1)
{
this.LookInComboBox1.SelectedIndex = 1;
}
else
{
this.LookInComboBox1.SelectedIndex = 0;
}
if (m_DataGridView.CurrentCell != null)
{
m_SearchStartRow = m_DataGridView.CurrentCell.RowIndex;
m_SearchStartColumn = m_DataGridView.CurrentCell.ColumnIndex;
if (m_DataGridView.CurrentCell.Value != null)
{
this.FindWhatTextBox1.Text = m_DataGridView.CurrentCell.Value.ToString();
}
}
SelectionCellsChanged();
}
void DataGridView_SelectionChanged(object sender, EventArgs e)
{
SelectionCellsChanged();
}
void SelectionCellsChanged()
{
m_SearchSelectionIndex = 0;
m_SelectedCells.Clear();
foreach (DataGridViewCell cell in m_DataGridView.SelectedCells)
{
m_SelectedCells.Add(cell);
}
}
void DataGridView_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
DataGridView.HitTestInfo hitTest = m_DataGridView.HitTest(e.X, e.Y);
if (hitTest.Type == DataGridViewHitTestType.Cell)
{
m_SearchStartRow = hitTest.RowIndex;
m_SearchStartColumn = hitTest.ColumnIndex;
}
}
}
void FindWhatTextBox1_TextChanged(object sender, System.EventArgs e)
{
this.FindWhatTextBox2.Text = this.FindWhatTextBox1.Text;
}
void FindWhatTextBox2_TextChanged(object sender, System.EventArgs e)
{
this.FindWhatTextBox1.Text = this.FindWhatTextBox2.Text;
}
void LookInComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.LookInComboBox2.SelectedIndex = this.LookInComboBox1.SelectedIndex;
}
void LookInComboBox2_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.LookInComboBox1.SelectedIndex = this.LookInComboBox2.SelectedIndex;
}
void MatchCaseCheckBox1_CheckedChanged(object sender, System.EventArgs e)
{
this.MatchCaseCheckBox2.Checked = this.MatchCaseCheckBox1.Checked;
}
void MatchCaseCheckBox2_CheckedChanged(object sender, System.EventArgs e)
{
this.MatchCaseCheckBox1.Checked = this.MatchCaseCheckBox2.Checked;
}
void MatchCellCheckBox1_CheckedChanged(object sender, System.EventArgs e)
{
this.MatchCellCheckBox2.Checked = this.MatchCellCheckBox1.Checked;
}
void MatchCellCheckBox2_CheckedChanged(object sender, System.EventArgs e)
{
this.MatchCellCheckBox1.Checked = this.MatchCellCheckBox2.Checked;
}
void SearchUpCheckBox1_CheckedChanged(object sender, System.EventArgs e)
{
this.SearchUpCheckBox2.Checked = this.SearchUpCheckBox1.Checked;
}
void SearchUpCheckBox2_CheckedChanged(object sender, System.EventArgs e)
{
this.SearchUpCheckBox1.Checked = this.SearchUpCheckBox2.Checked;
}
void UseCheckBox1_CheckedChanged(object sender, System.EventArgs e)
{
this.UseCheckBox2.Checked = this.UseCheckBox1.Checked;
if (this.UseCheckBox1.Checked)
{
this.UseComboBox1.Enabled = true;
}
else
{
this.UseComboBox1.Enabled = false;
this.UseComboBox1.SelectedItem = null;
}
}
void UseCheckBox2_CheckedChanged(object sender, System.EventArgs e)
{
this.UseCheckBox1.Checked = this.UseCheckBox2.Checked;
if (this.UseCheckBox2.Checked)
{
this.UseComboBox2.Enabled = true;
}
else
{
this.UseComboBox2.Enabled = false;
this.UseComboBox2.SelectedItem = null;
}
}
void UseComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.UseComboBox2.SelectedIndex = this.UseComboBox1.SelectedIndex;
}
void UseComboBox2_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.UseComboBox1.SelectedIndex = this.UseComboBox2.SelectedIndex;
}
void FindButton2_Click(object sender, System.EventArgs e)
{
FindButton1_Click(sender, e);
}
void ReplaceAllButton_Click(object sender, System.EventArgs e)
{
DataGridViewCell FindCell = null;
if (this.LookInComboBox1.SelectedIndex == 0)
{
FindCell = FindAndReplaceInTable(true, false, this.ReplaceWithTextBox.Text);
}
else if (this.LookInComboBox1.SelectedIndex == 1)
{
FindCell = FindAndReplaceInSelection(true, false, this.ReplaceWithTextBox.Text);
} else if (this.LookInComboBox1.SelectedIndex == 2) {
FindCell = FindAndReplaceInColumn(true, false, this.ReplaceWithTextBox.Text);
}
if (FindCell != null)
{
DataGridViewCell[] cells = m_SelectedCells.ToArray(); ;
int iSearchIndex = m_SearchSelectionIndex;
m_DataGridView.CurrentCell = FindCell;
// restore cached selection variables that was changed by setting CurrentCell
m_SearchSelectionIndex = iSearchIndex;
m_SelectedCells.Clear();
m_SelectedCells.AddRange(cells);
}
}
void ReplaceButton_Click(object sender, System.EventArgs e)
{
DataGridViewCell FindCell = null;
if (this.LookInComboBox1.SelectedIndex == 0)
{
FindCell = FindAndReplaceInTable(true, true, this.ReplaceWithTextBox.Text);
}
else if (this.LookInComboBox1.SelectedIndex == 1)
{
FindCell = FindAndReplaceInSelection(true, true, this.ReplaceWithTextBox.Text);
} else if (this.LookInComboBox1.SelectedIndex == 2) {
FindCell = FindAndReplaceInColumn(true, true, this.ReplaceWithTextBox.Text);
}
if (FindCell != null)
{
DataGridViewCell[] cells = m_SelectedCells.ToArray(); ;
int iSearchIndex = m_SearchSelectionIndex;
m_DataGridView.CurrentCell = FindCell;
// restore cached selection variables that was changed by setting CurrentCell
m_SearchSelectionIndex = iSearchIndex;
m_SelectedCells.Clear();
m_SelectedCells.AddRange(cells);
}
}
void FindButton1_Click(object sender, System.EventArgs e)
{
Find(this.SearchUpCheckBox1.Checked);
}
public void Find(bool searchUp)
{
this.SearchUpCheckBox1.Checked = searchUp;
DataGridViewCell FindCell = null;
if (this.LookInComboBox1.SelectedIndex == 0)
{
FindCell = FindAndReplaceInTable(false, true, null);
}
else if (this.LookInComboBox1.SelectedIndex == 1)
{
FindCell = FindAndReplaceInSelection(false, true, null);
}
else if (this.LookInComboBox1.SelectedIndex == 2)
{
FindCell = FindAndReplaceInColumn(false, true, null);
}
if (FindCell != null)
{
DataGridViewCell[] cells = m_SelectedCells.ToArray(); ;
int iSearchIndex = m_SearchSelectionIndex;
m_DataGridView.CurrentCell = FindCell;
// restore cached selection variables that was changed by setting CurrentCell
m_SearchSelectionIndex = iSearchIndex;
m_SelectedCells.Clear();
m_SelectedCells.AddRange(cells);
}
}
DataGridViewCell FindAndReplaceInSelection(bool bReplace, bool bStopOnFind, String replaceString)
{
// Search criterions
String sFindWhat = this.FindWhatTextBox1.Text;
bool bMatchCase = this.MatchCaseCheckBox1.Checked;
bool bMatchCell = this.MatchCellCheckBox1.Checked;
bool bSearchUp = this.SearchUpCheckBox1.Checked;
int iSearchMethod = -1; // No regular repression or wildcard
if (this.UseCheckBox1.Checked)
{
iSearchMethod = this.UseComboBox1.SelectedIndex;
}
// Start of search
int iSearchIndex = m_SearchSelectionIndex;
if (bSearchUp)
{
iSearchIndex = m_SelectedCells.Count - m_SearchSelectionIndex - 1;
}
while (m_SearchSelectionIndex < m_SelectedCells.Count)
{
m_SearchSelectionIndex++;
// Search end of search
DataGridViewCell FindCell = null;
if (FindAndReplaceString(bReplace, m_SelectedCells[iSearchIndex], sFindWhat, replaceString, bMatchCase, bMatchCell, iSearchMethod))
{
FindCell = m_SelectedCells[iSearchIndex];
}
if (bStopOnFind && FindCell != null)
{
if (m_SearchSelectionIndex >= m_SelectedCells.Count)
{
m_SearchSelectionIndex = 0;
}
return FindCell;
}
if (bSearchUp)
{
iSearchIndex = m_SelectedCells.Count - m_SearchSelectionIndex - 1;
}
else
{
iSearchIndex = m_SearchSelectionIndex;
}
}
if (m_SearchSelectionIndex >= m_SelectedCells.Count)
{
m_SearchSelectionIndex = 0;
}
return null;
}
DataGridViewCell FindAndReplaceInTable(bool bReplace, bool bStopOnFind, String replaceString)
{
if (m_DataGridView.CurrentCell == null)
{
return null;
}
// Search criterions
String sFindWhat = this.FindWhatTextBox1.Text;
bool bMatchCase = this.MatchCaseCheckBox1.Checked;
bool bMatchCell = this.MatchCellCheckBox1.Checked;
bool bSearchUp = this.SearchUpCheckBox1.Checked;
int iSearchMethod = -1; // No regular repression or wildcard
if (this.UseCheckBox1.Checked)
{
iSearchMethod = this.UseComboBox1.SelectedIndex;
}
// Start of search
int iSearchStartRow = m_DataGridView.CurrentCell.RowIndex;
int iSearchStartColumn = m_DataGridView.CurrentCell.ColumnIndex;
int iRowIndex = m_DataGridView.CurrentCell.RowIndex;
int iColIndex = m_DataGridView.CurrentCell.ColumnIndex;
if (bSearchUp)
{
iColIndex = iColIndex - 1;
if (iColIndex < 0)
{
iColIndex = m_DataGridView.ColumnCount - 1;
iRowIndex--;
}
}
else
{
iColIndex = iColIndex + 1;
if (iColIndex >= m_DataGridView.ColumnCount)
{
iColIndex = 0;
iRowIndex++;
}
}
if (iRowIndex >= m_DataGridView.RowCount)
{
iRowIndex = 0;
}
else if (iRowIndex < 0)
{
iRowIndex = m_DataGridView.RowCount - 1;
}
while (!(iRowIndex == iSearchStartRow && iColIndex == iSearchStartColumn))
{
// Search end of search
DataGridViewCell FindCell = null;
if (FindAndReplaceString(bReplace, m_DataGridView[iColIndex, iRowIndex], sFindWhat, replaceString, bMatchCase, bMatchCell, iSearchMethod))
{
FindCell = m_DataGridView[iColIndex, iRowIndex];
}
if (bStopOnFind && FindCell != null)
{
return FindCell;
}
if (bSearchUp)
{
iColIndex--;
}
else
{
iColIndex++;
}
if (iColIndex >= m_DataGridView.ColumnCount)
{
iColIndex = 0;
iRowIndex++;
}
else if (iColIndex < 0)
{
iColIndex = m_DataGridView.ColumnCount - 1;
iRowIndex--;
}
if (iRowIndex >= m_DataGridView.RowCount)
{
iRowIndex = 0;
}
else if (iRowIndex < 0)
{
iRowIndex = m_DataGridView.RowCount - 1;
}
}
if (FindAndReplaceString(bReplace, m_DataGridView[iColIndex, iRowIndex], sFindWhat, replaceString, bMatchCase, bMatchCell, iSearchMethod))
{
return m_DataGridView[iColIndex, iRowIndex];
}
return null;
}
DataGridViewCell FindAndReplaceInColumn(bool bReplace, bool bStopOnFind, String replaceString) {
if (m_DataGridView.CurrentCell == null) {
return null;
}
// Search criterions
String sFindWhat = this.FindWhatTextBox1.Text;
bool bMatchCase = this.MatchCaseCheckBox1.Checked;
bool bMatchCell = this.MatchCellCheckBox1.Checked;
bool bSearchUp = this.SearchUpCheckBox1.Checked;
int iSearchMethod = -1; // No regular repression or wildcard
if (this.UseCheckBox1.Checked) {
iSearchMethod = this.UseComboBox1.SelectedIndex;
}
// Start of search
int iSearchStartRow = m_DataGridView.CurrentCell.RowIndex;
int iSearchStartColumn = m_DataGridView.CurrentCell.ColumnIndex;
int iRowIndex = m_DataGridView.CurrentCell.RowIndex;
iRowIndex++;
if (iRowIndex >= m_DataGridView.RowCount) {
iRowIndex = 0;
} else if (iRowIndex < 0) {
iRowIndex = m_DataGridView.RowCount - 1;
}
while (!(iRowIndex == iSearchStartRow)) {
// Search end of search
DataGridViewCell FindCell = null;
if (FindAndReplaceString(bReplace, m_DataGridView[iSearchStartColumn, iRowIndex], sFindWhat, replaceString, bMatchCase, bMatchCell, iSearchMethod)) {
FindCell = m_DataGridView[iSearchStartColumn, iRowIndex];
}
if (bStopOnFind && FindCell != null) {
return FindCell;
}
if (bSearchUp) {
iRowIndex--;
} else {
iRowIndex++;
}
if (iRowIndex >= m_DataGridView.RowCount) {
iRowIndex = 0;
} else if (iRowIndex < 0) {
iRowIndex = m_DataGridView.RowCount - 1;
}
}
if (FindAndReplaceString(bReplace, m_DataGridView[iSearchStartColumn, iRowIndex], sFindWhat, replaceString, bMatchCase, bMatchCell, iSearchMethod)) {
return m_DataGridView[iSearchStartColumn, iRowIndex];
}
return null;
}
DataGridViewCell FindAndReplaceInColumnHeader()
{
// Search parameters
String sFindWhat = this.FindWhatTextBox1.Text;
bool bMatchCase = this.MatchCaseCheckBox1.Checked;
bool bMatchCell = this.MatchCellCheckBox1.Checked;
bool bSearchUp = this.SearchUpCheckBox1.Checked;
int iSearchMethod = -1; // No regular repression or wildcard
if (this.UseCheckBox1.Checked)
{
iSearchMethod = this.UseComboBox1.SelectedIndex;
}
// Start of search
int iSearchStartColumn = m_DataGridView.CurrentCell.ColumnIndex;
int iColIndex = m_DataGridView.CurrentCell.ColumnIndex;
// search one cell back
if (bSearchUp)
{
iColIndex = iColIndex - 1;
if (iColIndex < 0)
{
iColIndex = m_DataGridView.ColumnCount - 1;
}
}
else
{
iColIndex = iColIndex + 1;
if (iColIndex >= m_DataGridView.ColumnCount)
{
iColIndex = 0;
}
}
while (!(iColIndex == iSearchStartColumn))
{
// Search end of search
DataGridViewCell FindCell = null;
if (FindString(m_DataGridView.Columns[iColIndex].Name, sFindWhat, bMatchCase, bMatchCell, iSearchMethod))
{
FindCell = m_DataGridView[iColIndex, 0];
return FindCell;
}
if (bSearchUp)
{
iColIndex--;
}
else
{
iColIndex++;
}
// Search down
if (iColIndex >= m_DataGridView.ColumnCount)
{
iColIndex = 0;
}
// Search up
else if (iColIndex < 0)
{
iColIndex = m_DataGridView.ColumnCount - 1;
}
}
return null;
}
bool FindString(String SearchString, String FindString, bool bMatchCase, bool bMatchCell, int iSearchMethod)
{
// Regular string search
if (iSearchMethod == -1)
{
// Match Cell
if (bMatchCell)
{
if (!bMatchCase)
{
if (SearchString.ToLowerInvariant() == FindString.ToLowerInvariant())
{
return true;
}
}
else
{
if (SearchString == FindString)
{
return true;
}
}
}
// No Match Cell
else
{
bool bFound = false;
StringComparison strCompare = StringComparison.InvariantCulture;
if (!bMatchCase)
{
strCompare = StringComparison.InvariantCultureIgnoreCase;
}
bFound = SearchString.IndexOf(FindString, 0, strCompare) != -1;
return bFound;
}
}
else
{
// Regular Expression
String RegexPattern = FindString;
// Wildcards
if (iSearchMethod == 1)
{
// Convert wildcard to regex:
RegexPattern = "^" + System.Text.RegularExpressions.Regex.Escape(FindString).Replace("\\*", ".*").Replace("\\?", ".") + "$";
}
System.Text.RegularExpressions.RegexOptions strCompare = System.Text.RegularExpressions.RegexOptions.None;
if (!bMatchCase)
{
strCompare = System.Text.RegularExpressions.RegexOptions.IgnoreCase;
}
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(RegexPattern, strCompare);
if (regex.IsMatch(SearchString))
{
return true;
}
return false;
}
return false;
}
bool FindAndReplaceString(bool bReplace, DataGridViewCell SearchCell, String FindString, String ReplaceString, bool bMatchCase, bool bMatchCell, int iSearchMethod )
{
String SearchString = SearchCell.FormattedValue.ToString();
// Regular string search
if (iSearchMethod == -1)
{
// Match Cell
if ( bMatchCell )
{
if ( !bMatchCase )
{
if ( SearchString.ToLowerInvariant() == FindString.ToLowerInvariant() )
{
if ( bReplace )
{
SearchCell.Value = Convert.ChangeType(ReplaceString, SearchCell.ValueType);
}
return true;
}
}
else
{
if ( SearchString == FindString )
{
if ( bReplace )
{
SearchCell.Value = Convert.ChangeType(ReplaceString, SearchCell.ValueType);
}
return true;
}
}
}
// No Match Cell
else
{
bool bFound = false;
StringComparison strCompare = StringComparison.InvariantCulture;
if (!bMatchCase)
{
strCompare = StringComparison.InvariantCultureIgnoreCase;
}
if (bReplace)
{
String NewString = null;
int strIndex = 0;
while (strIndex != -1)
{
int nextStrIndex = SearchString.IndexOf(FindString, strIndex, strCompare);
if (nextStrIndex != -1)
{
bFound = true;
NewString += SearchString.Substring(strIndex, nextStrIndex - strIndex);
NewString += ReplaceString;
nextStrIndex = nextStrIndex + FindString.Length;
}
else
{
NewString += SearchString.Substring(strIndex);
}
strIndex = nextStrIndex;
}
if ( bFound )
{
SearchCell.Value = Convert.ChangeType(NewString, SearchCell.ValueType);
}
}
else
{
bFound = SearchString.IndexOf(FindString, 0, strCompare) != -1;
}
return bFound;
}
}
else
{
// Regular Expression
String RegexPattern = FindString;
// Wildcards
if (iSearchMethod == 1)
{
// Convert wildcard to regex:
RegexPattern = "^" + System.Text.RegularExpressions.Regex.Escape(FindString).Replace("\\*", ".*").Replace("\\?", ".") + "$";
}
System.Text.RegularExpressions.RegexOptions strCompare = System.Text.RegularExpressions.RegexOptions.None;
if (!bMatchCase)
{
strCompare = System.Text.RegularExpressions.RegexOptions.IgnoreCase;
}
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(RegexPattern, strCompare);
if ( regex.IsMatch( SearchString ) )
{
if ( bReplace )
{
String NewString = regex.Replace(SearchString, ReplaceString );
SearchCell.Value = Convert.ChangeType(NewString, SearchCell.ValueType);
}
return true;
}
return false;
}
return false;
}
private void FindAndReplaceForm_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
e.Cancel = true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Runtime;
using System.ServiceModel.Channels;
using System.Text;
using System.Xml;
namespace System.ServiceModel
{
public abstract class HttpBindingBase : Binding, IBindingRuntimePreferences
{
// private BindingElements
private HttpTransportBindingElement _httpTransport;
private HttpsTransportBindingElement _httpsTransport;
internal HttpBindingBase()
{
_httpTransport = new HttpTransportBindingElement();
_httpsTransport = new HttpsTransportBindingElement();
TextMessageEncodingBindingElement = new TextMessageEncodingBindingElement();
TextMessageEncodingBindingElement.MessageVersion = MessageVersion.Soap11;
MtomMessageEncodingBindingElement = new MtomMessageEncodingBindingElement();
MtomMessageEncodingBindingElement.MessageVersion = MessageVersion.Soap11;
_httpsTransport.WebSocketSettings = _httpTransport.WebSocketSettings;
}
[DefaultValue(HttpTransportDefaults.AllowCookies)]
public bool AllowCookies
{
get
{
return _httpTransport.AllowCookies;
}
set
{
_httpTransport.AllowCookies = value;
_httpsTransport.AllowCookies = value;
}
}
[DefaultValue(HttpTransportDefaults.BypassProxyOnLocal)]
public bool BypassProxyOnLocal
{
get
{
return _httpTransport.BypassProxyOnLocal;
}
set
{
_httpTransport.BypassProxyOnLocal = value;
_httpsTransport.BypassProxyOnLocal = value;
}
}
[DefaultValue(HttpTransportDefaults.HostNameComparisonMode)]
public HostNameComparisonMode HostNameComparisonMode
{
get
{
return _httpTransport.HostNameComparisonMode;
}
set
{
_httpTransport.HostNameComparisonMode = value;
_httpsTransport.HostNameComparisonMode = value;
}
}
[DefaultValue(TransportDefaults.MaxBufferSize)]
public int MaxBufferSize
{
get
{
return _httpTransport.MaxBufferSize;
}
set
{
_httpTransport.MaxBufferSize = value;
_httpsTransport.MaxBufferSize = value;
MtomMessageEncodingBindingElement.MaxBufferSize = value;
}
}
[DefaultValue(TransportDefaults.MaxBufferPoolSize)]
public long MaxBufferPoolSize
{
get
{
return _httpTransport.MaxBufferPoolSize;
}
set
{
_httpTransport.MaxBufferPoolSize = value;
_httpsTransport.MaxBufferPoolSize = value;
}
}
[DefaultValue(TransportDefaults.MaxReceivedMessageSize)]
public long MaxReceivedMessageSize
{
get
{
return _httpTransport.MaxReceivedMessageSize;
}
set
{
_httpTransport.MaxReceivedMessageSize = value;
_httpsTransport.MaxReceivedMessageSize = value;
}
}
[DefaultValue(HttpTransportDefaults.ProxyAddress)]
[TypeConverter(typeof(UriTypeConverter))]
public Uri ProxyAddress
{
get
{
return _httpTransport.ProxyAddress;
}
set
{
_httpTransport.ProxyAddress = value;
_httpsTransport.ProxyAddress = value;
}
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
return TextMessageEncodingBindingElement.ReaderQuotas;
}
set
{
if (value == null)
{
throw FxTrace.Exception.ArgumentNull("value");
}
value.CopyTo(TextMessageEncodingBindingElement.ReaderQuotas);
value.CopyTo(MtomMessageEncodingBindingElement.ReaderQuotas);
SetReaderQuotas(value);
}
}
public override string Scheme
{
get
{
return GetTransport().Scheme;
}
}
public EnvelopeVersion EnvelopeVersion
{
get { return GetEnvelopeVersion(); }
}
public Encoding TextEncoding
{
get
{
return TextMessageEncodingBindingElement.WriteEncoding;
}
set
{
TextMessageEncodingBindingElement.WriteEncoding = value;
MtomMessageEncodingBindingElement.WriteEncoding = value;
}
}
[DefaultValue(HttpTransportDefaults.TransferMode)]
public TransferMode TransferMode
{
get
{
return _httpTransport.TransferMode;
}
set
{
_httpTransport.TransferMode = value;
_httpsTransport.TransferMode = value;
}
}
[DefaultValue(HttpTransportDefaults.UseDefaultWebProxy)]
public bool UseDefaultWebProxy
{
get
{
return _httpTransport.UseDefaultWebProxy;
}
set
{
_httpTransport.UseDefaultWebProxy = value;
_httpsTransport.UseDefaultWebProxy = value;
}
}
bool IBindingRuntimePreferences.ReceiveSynchronously
{
get { return false; }
}
internal TextMessageEncodingBindingElement TextMessageEncodingBindingElement { get; }
internal MtomMessageEncodingBindingElement MtomMessageEncodingBindingElement { get; }
internal abstract BasicHttpSecurity BasicHttpSecurity
{
get;
}
internal WebSocketTransportSettings InternalWebSocketSettings
{
get
{
return _httpTransport.WebSocketSettings;
}
}
internal static bool GetSecurityModeFromTransport(HttpTransportBindingElement http, HttpTransportSecurity transportSecurity, out UnifiedSecurityMode mode)
{
mode = UnifiedSecurityMode.None;
if (http == null)
{
return false;
}
Fx.Assert(http.AuthenticationScheme.IsSingleton(), "authenticationScheme used in an Http(s)ChannelFactory must be a singleton value.");
if (http is HttpsTransportBindingElement)
{
mode = UnifiedSecurityMode.Transport | UnifiedSecurityMode.TransportWithMessageCredential;
BasicHttpSecurity.EnableTransportSecurity((HttpsTransportBindingElement)http, transportSecurity);
}
else if (HttpTransportSecurity.IsDisabledTransportAuthentication(http))
{
mode = UnifiedSecurityMode.Message | UnifiedSecurityMode.None;
}
else if (!BasicHttpSecurity.IsEnabledTransportAuthentication(http, transportSecurity))
{
return false;
}
else
{
mode = UnifiedSecurityMode.TransportCredentialOnly;
}
return true;
}
internal TransportBindingElement GetTransport()
{
Fx.Assert(BasicHttpSecurity != null, "this.BasicHttpSecurity should not return null from a derived class.");
BasicHttpSecurity basicHttpSecurity = BasicHttpSecurity;
if (basicHttpSecurity.Mode == BasicHttpSecurityMode.Transport || basicHttpSecurity.Mode == BasicHttpSecurityMode.TransportWithMessageCredential)
{
basicHttpSecurity.EnableTransportSecurity(_httpsTransport);
return _httpsTransport;
}
else if (basicHttpSecurity.Mode == BasicHttpSecurityMode.TransportCredentialOnly)
{
basicHttpSecurity.EnableTransportAuthentication(_httpTransport);
return _httpTransport;
}
else
{
// ensure that there is no transport security
basicHttpSecurity.DisableTransportAuthentication(_httpTransport);
return _httpTransport;
}
}
internal abstract EnvelopeVersion GetEnvelopeVersion();
internal virtual void SetReaderQuotas(XmlDictionaryReaderQuotas readerQuotas)
{
}
// In the Win8 profile, some settings for the binding security are not supported.
internal virtual void CheckSettings()
{
BasicHttpSecurity security = BasicHttpSecurity;
if (security == null)
{
return;
}
BasicHttpSecurityMode mode = security.Mode;
if (mode == BasicHttpSecurityMode.None)
{
return;
}
else if (mode == BasicHttpSecurityMode.Message)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, nameof(security.Mode), mode)));
}
// Transport.ClientCredentialType = InheritedFromHost are not supported.
Fx.Assert(
(mode == BasicHttpSecurityMode.Transport) || (mode == BasicHttpSecurityMode.TransportCredentialOnly) || (mode == BasicHttpSecurityMode.TransportWithMessageCredential),
"Unexpected BasicHttpSecurityMode value: " + mode);
HttpTransportSecurity transport = security.Transport;
if (transport != null && transport.ClientCredentialType == HttpClientCredentialType.InheritedFromHost)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Transport.ClientCredentialType", transport.ClientCredentialType)));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Signum.Utilities.Reflection;
using System.Globalization;
using System.Reflection;
using System.Collections;
namespace Signum.Utilities
{
public static class Tsv
{
// Default changed since Excel exports not to UTF8 and https://stackoverflow.com/questions/49215791/vs-code-c-sharp-system-notsupportedexception-no-data-is-available-for-encodin
public static Encoding DefaultEncoding = Encoding.UTF8;
public static CultureInfo DefaultCulture = CultureInfo.InvariantCulture;
public static string ToTsvFile<T>(T[,] collection, string fileName, Encoding? encoding = null, bool autoFlush = false, bool append = false,
Func<TsvColumnInfo<T>, Func<object, string>>? toStringFactory = null)
{
encoding = encoding ?? DefaultEncoding;
using (FileStream fs = append ? new FileStream(fileName, FileMode.Append, FileAccess.Write) : File.Create(fileName))
{
using (StreamWriter sw = new StreamWriter(fs, encoding) { AutoFlush = autoFlush })
{
for (int i = 0; i < collection.GetLength(0); i++)
{
for (int j = 0; j < collection.GetLength(1); j++)
{
sw.Write(collection[i, j]);
sw.Write(tab);
}
if (i < collection.GetLength(0))
sw.WriteLine();
}
}
}
return fileName;
}
public static string ToTsvFile<T>(this IEnumerable<T> collection, string fileName, Encoding? encoding = null, CultureInfo? culture = null, bool writeHeaders = true, bool autoFlush = false, bool append = false,
Func<TsvColumnInfo<T>, Func<object?, string?>>? toStringFactory = null)
{
using (FileStream fs = append ? new FileStream(fileName, FileMode.Append, FileAccess.Write) : File.Create(fileName))
ToTsv<T>(collection, fs, encoding, culture, writeHeaders, autoFlush, toStringFactory);
return fileName;
}
public static byte[] ToTsvBytes<T>(this IEnumerable<T> collection, Encoding? encoding = null, CultureInfo? culture = null, bool writeHeaders = true, bool autoFlush = false,
Func<TsvColumnInfo<T>, Func<object?, string?>>? toStringFactory = null)
{
using (MemoryStream ms = new MemoryStream())
{
collection.ToTsv(ms, encoding, culture, writeHeaders, autoFlush, toStringFactory);
return ms.ToArray();
}
}
private const string tab = "\t";
public static void ToTsv<T>(this IEnumerable<T> collection, Stream stream, Encoding? encoding = null, CultureInfo? culture = null, bool writeHeaders = true, bool autoFlush = false,
Func<TsvColumnInfo<T>, Func<object?, string?>>? toStringFactory = null)
{
encoding = encoding ?? DefaultEncoding;
var defCulture = culture ?? DefaultCulture;
if (typeof(IList).IsAssignableFrom(typeof(T)))
{
using (StreamWriter sw = new StreamWriter(stream, encoding) { AutoFlush = autoFlush })
{
foreach (IList? row in collection)
{
for (int i = 0; i < row!.Count; i++)
{
var obj = row![i];
var str = ConvertToString(obj, defCulture);
sw.Write(str);
if (i < row!.Count - 1)
sw.Write(tab);
else
sw.WriteLine();
}
}
}
}
else
{
var columns = ColumnInfoCache<T>.Columns;
var members = columns.Select(c => c.MemberEntry).ToList();
var toString = columns.Select(c => GetToString(c, defCulture, toStringFactory)).ToList();
using (StreamWriter sw = new StreamWriter(stream, encoding) { AutoFlush = autoFlush })
{
if (writeHeaders)
sw.WriteLine(members.ToString(m => HandleSpaces(m.Name), tab));
foreach (var item in collection)
{
for (int i = 0; i < members.Count; i++)
{
var obj = members[i].Getter!(item);
var str = toString[i](obj);
sw.Write(str);
if (i < members.Count - 1)
sw.Write(tab);
else
sw.WriteLine();
}
}
}
}
}
private static Func<object?, string?> GetToString<T>(TsvColumnInfo<T> column, CultureInfo culture, Func<TsvColumnInfo<T>, Func<object?, string?>>? toStringFactory)
{
if (toStringFactory != null)
{
var result = toStringFactory(column);
if (result != null)
return result;
}
return obj => ConvertToString(obj, culture);
}
static string ConvertToString(object? obj, CultureInfo culture)
{
if (obj == null)
return "";
if (obj is IFormattable f)
return f.ToString(null, culture);
else
{
var p = obj!.ToString();
if (p != null && p.Contains(tab))
throw new InvalidDataException("TSV fields can't contain the tab character, found one in value: " + p);
return p!;
}
}
static string HandleSpaces(string p)
{
return p.Replace("__", "^").Replace("_", " ").Replace("^", "_");
}
public static List<T> ReadFile<T>(string fileName, Encoding? encoding = null, int skipLines = 1, CultureInfo? culture = null, TsvReadOptions<T>? options = null) where T : class, new()
{
encoding = encoding ?? DefaultEncoding;
using (FileStream fs = File.OpenRead(fileName))
return ReadStream<T>(fs, encoding, skipLines, culture, options).ToList();
}
public static List<T> ReadBytes<T>(byte[] data, Encoding? encoding = null, int skipLines = 1, CultureInfo? culture = null, TsvReadOptions<T>? options = null) where T : class, new()
{
using (MemoryStream ms = new MemoryStream(data))
return ReadStream<T>(ms, encoding, skipLines, culture, options).ToList();
}
public static IEnumerable<T> ReadStream<T>(Stream stream, Encoding? encoding = null, int skipLines = 1, CultureInfo? culture = null, TsvReadOptions<T>? options = null) where T : class, new()
{
encoding = encoding ?? DefaultEncoding;
var defOptions = options ?? new TsvReadOptions<T>();
var defCulture = culture ?? DefaultCulture;
var columns = ColumnInfoCache<T>.Columns;
var members = columns.Select(c => c.MemberEntry).ToList();
var parsers = columns.Select(c => GetParser(c, defCulture, defOptions.ParserFactory)).ToList();
using (StreamReader sr = new StreamReader(stream, encoding))
{
for (int i = 0; i < skipLines; i++)
sr.ReadLine();
var line = skipLines;
while (true)
{
string? tsvLine = sr.ReadLine();
if (tsvLine == null)
yield break;
T? t = null;
try
{
t = ReadObject<T>(tsvLine, members, parsers);
}
catch (Exception e)
{
e.Data["row"] = line;
if (defOptions.SkipError?.Invoke(e, tsvLine) != true)
throw new ParseCsvException(e);
}
if (t != null)
yield return t;
}
}
}
public static T ReadLine<T>(string tsvLine, CultureInfo? culture = null, TsvReadOptions<T>? options = null)
where T : class, new()
{
var defOptions = options ?? new TsvReadOptions<T>();
var defCulture = culture ?? DefaultCulture;
var columns = ColumnInfoCache<T>.Columns;
return ReadObject<T>(tsvLine,
columns.Select(c => c.MemberEntry).ToList(),
columns.Select(c => GetParser(c, defCulture, defOptions.ParserFactory)).ToList());
}
private static Func<string, object?> GetParser<T>(TsvColumnInfo<T> column, CultureInfo culture, Func<TsvColumnInfo<T>, Func<string, object?>>? parserFactory)
{
if (parserFactory != null)
{
var result = parserFactory(column);
if (result != null)
return result;
}
return str => ConvertTo(str, column.MemberInfo.ReturningType(), column.Format, culture);
}
static T ReadObject<T>(string line, List<MemberEntry<T>> members, List<Func<string, object?>> parsers) where T : new()
{
var vals = line.Split(new[] { tab }, StringSplitOptions.None).ToList();
if (vals.Count < members.Count)
throw new FormatException("Only {0} columns found (instead of {1}) in line: {2}".FormatWith(vals.Count, members.Count, line));
T t = new T();
for (int i = 0; i < members.Count; i++)
{
string? str = null;
try
{
str = vals[i];
object? val = parsers[i](str);
members[i].Setter!(t, val);
}
catch (Exception e)
{
e.Data["value"] = str;
e.Data["member"] = members[i].MemberInfo.Name;
throw;
}
}
return t;
}
static class ColumnInfoCache<T>
{
public static List<TsvColumnInfo<T>> Columns = MemberEntryFactory.GenerateList<T>(MemberOptions.Fields | MemberOptions.Properties | MemberOptions.Typed | MemberOptions.Setters | MemberOptions.Getter)
.Select((me, i) => new TsvColumnInfo<T>(i, me, me.MemberInfo.GetCustomAttribute<FormatAttribute>()?.Format)).ToList();
}
static object? ConvertTo(string s, Type type, string? format, CultureInfo culture)
{
Type? baseType = Nullable.GetUnderlyingType(type);
if (baseType != null)
{
if (!s.HasText())
return null;
type = baseType;
}
if (type.IsEnum)
return Enum.Parse(type, s);
if (type == typeof(DateTime))
if (format == null)
return DateTime.Parse(s, culture);
else
return DateTime.ParseExact(s, format, culture);
return Convert.ChangeType(s, type, culture);
}
}
public class TsvReadOptions<T> where T : class
{
public Func<TsvColumnInfo<T>, Func<string, object>>? ParserFactory;
public Func<Exception, string, bool>? SkipError;
}
public class TsvColumnInfo<T>
{
public readonly int Index;
public readonly MemberEntry<T> MemberEntry;
public readonly string? Format;
public MemberInfo MemberInfo
{
get { return this.MemberEntry.MemberInfo; }
}
internal TsvColumnInfo(int index, MemberEntry<T> memberEntry, string? format)
{
this.Index = index;
this.MemberEntry = memberEntry;
this.Format = format;
}
}
[Serializable]
public class ParseTsvException : Exception
{
public int? Row { get; set; }
public string? Member { get; set; }
public string? Value { get; set; }
public ParseTsvException() { }
public ParseTsvException(Exception inner) : base(inner.Message, inner)
{
this.Row = (int?)inner.Data["row"];
this.Value = (string)inner.Data["value"]!;
this.Member = (string)inner.Data["member"]!;
}
protected ParseTsvException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context)
{ }
public override string Message
{
get
{
return $"(Row: {this.Row}, Member: {this.Member}, Value: '{this.Value}') {base.Message})";
}
}
}
}
| |
// 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 Microsoft.Xml;
using Microsoft.Xml.Schema;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Security;
namespace System.Runtime.Serialization
{
#if USE_REFEMIT || NET_NATIVE
public delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract);
public delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract);
#else
internal delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract);
internal delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract);
internal sealed class XmlFormatWriterGenerator
{
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that was produced within an assert
/// </SecurityNote>
private CriticalHelper _helper;
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// </SecurityNote>
[SecurityCritical]
public XmlFormatWriterGenerator()
{
_helper = new CriticalHelper();
}
/// <SecurityNote>
/// Critical - accesses SecurityCritical helper class 'CriticalHelper'
/// </SecurityNote>
[SecurityCritical]
internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract)
{
return _helper.GenerateClassWriter(classContract);
}
/// <SecurityNote>
/// Critical - accesses SecurityCritical helper class 'CriticalHelper'
/// </SecurityNote>
[SecurityCritical]
internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract)
{
return _helper.GenerateCollectionWriter(collectionContract);
}
/// <SecurityNote>
/// Review - handles all aspects of IL generation including initializing the DynamicMethod.
/// changes to how IL generated could affect how data is serialized and what gets access to data,
/// therefore we mark it for review so that changes to generation logic are reviewed.
/// </SecurityNote>
private class CriticalHelper
{
private CodeGenerator _ilg;
private ArgBuilder _xmlWriterArg;
private ArgBuilder _contextArg;
private ArgBuilder _dataContractArg;
private LocalBuilder _objectLocal;
// Used for classes
private LocalBuilder _contractNamespacesLocal;
private LocalBuilder _memberNamesLocal;
private LocalBuilder _childElementNamespacesLocal;
private int _typeIndex = 1;
private int _childElementIndex = 0;
internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null);
try
{
_ilg.BeginMethod("Write" + classContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatClassWriterDelegate, memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
classContract.RequiresMemberAccessForWrite(securityException);
}
else
{
throw;
}
}
InitArgs(classContract.UnderlyingType);
WriteClass(classContract);
return (XmlFormatClassWriterDelegate)_ilg.EndMethod();
}
internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = collectionContract.RequiresMemberAccessForWrite(null);
try
{
_ilg.BeginMethod("Write" + collectionContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatCollectionWriterDelegate, memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
collectionContract.RequiresMemberAccessForWrite(securityException);
}
else
{
throw;
}
}
InitArgs(collectionContract.UnderlyingType);
WriteCollection(collectionContract);
return (XmlFormatCollectionWriterDelegate)_ilg.EndMethod();
}
private void InitArgs(Type objType)
{
_xmlWriterArg = _ilg.GetArg(0);
_contextArg = _ilg.GetArg(2);
_dataContractArg = _ilg.GetArg(3);
_objectLocal = _ilg.DeclareLocal(objType, "objSerialized");
ArgBuilder objectArg = _ilg.GetArg(1);
_ilg.Load(objectArg);
// Copy the data from the DataTimeOffset object passed in to the DateTimeOffsetAdapter.
// DateTimeOffsetAdapter is used here for serialization purposes to bypass the ISerializable implementation
// on DateTimeOffset; which does not work in partial trust.
if (objType == Globals.TypeOfDateTimeOffsetAdapter)
{
_ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfDateTimeOffset);
_ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetAdapterMethod);
}
//Copy the KeyValuePair<K,T> to a KeyValuePairAdapter<K,T>.
else if (objType.GetTypeInfo().IsGenericType && objType.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter)
{
ClassDataContract dc = (ClassDataContract)DataContract.GetDataContract(objType);
_ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments));
_ilg.New(dc.KeyValuePairAdapterConstructorInfo);
}
else
{
_ilg.ConvertValue(objectArg.ArgType, objType);
}
_ilg.Stloc(_objectLocal);
}
private void InvokeOnSerializing(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnSerializing(classContract.BaseContract);
if (classContract.OnSerializing != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnSerializing);
}
}
private void InvokeOnSerialized(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnSerialized(classContract.BaseContract);
if (classContract.OnSerialized != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnSerialized);
}
}
private void WriteClass(ClassDataContract classContract)
{
InvokeOnSerializing(classContract);
{
if (classContract.ContractNamespaces.Length > 1)
{
_contractNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "contractNamespaces");
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.ContractNamespacesField);
_ilg.Store(_contractNamespacesLocal);
}
_memberNamesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "memberNames");
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.MemberNamesField);
_ilg.Store(_memberNamesLocal);
for (int i = 0; i < classContract.ChildElementNamespaces.Length; i++)
{
if (classContract.ChildElementNamespaces[i] != null)
{
_childElementNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "childElementNamespaces");
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespacesProperty);
_ilg.Store(_childElementNamespacesLocal);
}
}
WriteMembers(classContract, null, classContract);
}
InvokeOnSerialized(classContract);
}
private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract)
{
int memberCount = (classContract.BaseContract == null) ? 0 :
WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract);
LocalBuilder namespaceLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString), "ns");
if (_contractNamespacesLocal == null)
{
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty);
}
else
_ilg.LoadArrayElement(_contractNamespacesLocal, _typeIndex - 1);
_ilg.Store(namespaceLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classContract.Members.Count);
for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
{
DataMember member = classContract.Members[i];
Type memberType = member.MemberType;
LocalBuilder memberValue = null;
if (member.IsGetOnlyCollection)
{
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.StoreIsGetOnlyCollectionMethod);
}
if (!member.EmitDefaultValue)
{
memberValue = LoadMemberValue(member);
_ilg.IfNotDefaultValue(memberValue);
}
bool writeXsiType = CheckIfMemberHasConflict(member, classContract, derivedMostClassContract);
if (writeXsiType || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, null /*arrayItemIndex*/, namespaceLocal, null /*nameLocal*/, i + _childElementIndex))
{
WriteStartElement(memberType, classContract.Namespace, namespaceLocal, null /*nameLocal*/, i + _childElementIndex);
if (classContract.ChildElementNamespaces[i + _childElementIndex] != null)
{
_ilg.Load(_xmlWriterArg);
_ilg.LoadArrayElement(_childElementNamespacesLocal, i + _childElementIndex);
_ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod);
}
if (memberValue == null)
memberValue = LoadMemberValue(member);
WriteValue(memberValue, writeXsiType);
WriteEndElement();
}
if (!member.EmitDefaultValue)
{
if (member.IsRequired)
{
_ilg.Else();
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMustBeEmittedMethod, member.Name, classContract.UnderlyingType);
}
_ilg.EndIf();
}
}
_typeIndex++;
_childElementIndex += classContract.Members.Count;
return memberCount;
}
private LocalBuilder LoadMemberValue(DataMember member)
{
_ilg.LoadAddress(_objectLocal);
_ilg.LoadMember(member.MemberInfo);
LocalBuilder memberValue = _ilg.DeclareLocal(member.MemberType, member.Name + "Value");
_ilg.Stloc(memberValue);
return memberValue;
}
private void WriteCollection(CollectionDataContract collectionContract)
{
LocalBuilder itemNamespace = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemNamespace");
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty);
_ilg.Store(itemNamespace);
LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemName");
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.CollectionItemNameProperty);
_ilg.Store(itemName);
if (collectionContract.ChildElementNamespace != null)
{
_ilg.Load(_xmlWriterArg);
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespaceProperty);
_ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod);
}
if (collectionContract.Kind == CollectionKind.Array)
{
Type itemType = collectionContract.ItemType;
LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementArrayCountMethod, _xmlWriterArg, _objectLocal);
if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, _objectLocal, itemName, itemNamespace))
{
_ilg.For(i, 0, _objectLocal);
if (!TryWritePrimitive(itemType, null /*value*/, null /*memberInfo*/, i /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/))
{
WriteStartElement(itemType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/);
_ilg.LoadArrayElement(_objectLocal, i);
LocalBuilder memberValue = _ilg.DeclareLocal(itemType, "memberValue");
_ilg.Stloc(memberValue);
WriteValue(memberValue, false /*writeXsiType*/);
WriteEndElement();
}
_ilg.EndFor();
}
}
else
{
MethodInfo incrementCollectionCountMethod = null;
switch (collectionContract.Kind)
{
case CollectionKind.Collection:
case CollectionKind.List:
case CollectionKind.Dictionary:
incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod;
break;
case CollectionKind.GenericCollection:
case CollectionKind.GenericList:
incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType);
break;
case CollectionKind.GenericDictionary:
incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments()));
break;
}
if (incrementCollectionCountMethod != null)
{
_ilg.Call(_contextArg, incrementCollectionCountMethod, _xmlWriterArg, _objectLocal);
}
bool isDictionary = false, isGenericDictionary = false;
Type enumeratorType = null;
Type[] keyValueTypes = null;
if (collectionContract.Kind == CollectionKind.GenericDictionary)
{
isGenericDictionary = true;
keyValueTypes = collectionContract.ItemType.GetGenericArguments();
enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes);
}
else if (collectionContract.Kind == CollectionKind.Dictionary)
{
isDictionary = true;
keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
enumeratorType = Globals.TypeOfDictionaryEnumerator;
}
else
{
enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType;
}
MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
if (moveNextMethod == null || getCurrentMethod == null)
{
if (enumeratorType.GetTypeInfo().IsInterface)
{
if (moveNextMethod == null)
moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod;
if (getCurrentMethod == null)
getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod;
}
else
{
Type ienumeratorInterface = Globals.TypeOfIEnumerator;
CollectionKind kind = collectionContract.Kind;
if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable)
{
Type[] interfaceTypes = enumeratorType.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
if (interfaceType.GetTypeInfo().IsGenericType
&& interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric
&& interfaceType.GetGenericArguments()[0] == collectionContract.ItemType)
{
ienumeratorInterface = interfaceType;
break;
}
}
}
if (moveNextMethod == null)
moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface);
if (getCurrentMethod == null)
getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
}
}
Type elementType = getCurrentMethod.ReturnType;
LocalBuilder currentValue = _ilg.DeclareLocal(elementType, "currentValue");
LocalBuilder enumerator = _ilg.DeclareLocal(enumeratorType, "enumerator");
_ilg.Call(_objectLocal, collectionContract.GetEnumeratorMethod);
if (isDictionary)
{
_ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, Globals.TypeOfIDictionaryEnumerator);
_ilg.New(XmlFormatGeneratorStatics.DictionaryEnumeratorCtor);
}
else if (isGenericDictionary)
{
Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes));
ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam });
_ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam);
_ilg.New(dictEnumCtor);
}
_ilg.Stloc(enumerator);
_ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod);
if (incrementCollectionCountMethod == null)
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
}
if (!TryWritePrimitive(elementType, currentValue, null /*memberInfo*/, null /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/))
{
WriteStartElement(elementType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/);
if (isGenericDictionary || isDictionary)
{
_ilg.Call(_dataContractArg, XmlFormatGeneratorStatics.GetItemContractMethod);
_ilg.Load(_xmlWriterArg);
_ilg.Load(currentValue);
_ilg.ConvertValue(currentValue.LocalType, Globals.TypeOfObject);
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.WriteXmlValueMethod);
}
else
{
WriteValue(currentValue, false /*writeXsiType*/);
}
WriteEndElement();
}
_ilg.EndForEach(moveNextMethod);
}
}
private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder ns, LocalBuilder name, int nameIndex)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
return false;
// load xmlwriter
if (type.GetTypeInfo().IsValueType)
{
_ilg.Load(_xmlWriterArg);
}
else
{
_ilg.Load(_contextArg);
_ilg.Load(_xmlWriterArg);
}
// load primitive value
if (value != null)
{
_ilg.Load(value);
}
else if (memberInfo != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.LoadMember(memberInfo);
}
else
{
_ilg.LoadArrayElement(_objectLocal, arrayItemIndex);
}
// load name
if (name != null)
{
_ilg.Load(name);
}
else
{
_ilg.LoadArrayElement(_memberNamesLocal, nameIndex);
}
// load namespace
_ilg.Load(ns);
// call method to write primitive
_ilg.Call(primitiveContract.XmlFormatWriterMethod);
return true;
}
private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName, LocalBuilder itemNamespace)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
if (primitiveContract == null)
return false;
string writeArrayMethod = null;
switch (itemType.GetTypeCode())
{
case TypeCode.Boolean:
writeArrayMethod = "WriteBooleanArray";
break;
case TypeCode.DateTime:
writeArrayMethod = "WriteDateTimeArray";
break;
case TypeCode.Decimal:
writeArrayMethod = "WriteDecimalArray";
break;
case TypeCode.Int32:
writeArrayMethod = "WriteInt32Array";
break;
case TypeCode.Int64:
writeArrayMethod = "WriteInt64Array";
break;
case TypeCode.Single:
writeArrayMethod = "WriteSingleArray";
break;
case TypeCode.Double:
writeArrayMethod = "WriteDoubleArray";
break;
default:
break;
}
if (writeArrayMethod != null)
{
_ilg.Load(_xmlWriterArg);
_ilg.Load(value);
_ilg.Load(itemName);
_ilg.Load(itemNamespace);
_ilg.Call(typeof(XmlWriterDelegator).GetMethod(writeArrayMethod, Globals.ScanAllMembers, new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }));
return true;
}
return false;
}
private void WriteValue(LocalBuilder memberValue, bool writeXsiType)
{
Type memberType = memberValue.LocalType;
bool isNullableOfT = (memberType.GetTypeInfo().IsGenericType &&
memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable);
if (memberType.GetTypeInfo().IsValueType && !isNullableOfT)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
if (primitiveContract != null && !writeXsiType)
_ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue);
else
InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, memberValue, memberType, writeXsiType);
}
else
{
if (isNullableOfT)
{
memberValue = UnwrapNullableObject(memberValue);//Leaves !HasValue on stack
memberType = memberValue.LocalType;
}
else
{
_ilg.Load(memberValue);
_ilg.Load(null);
_ilg.Ceq();
}
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType));
_ilg.Else();
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType)
{
if (isNullableOfT)
{
_ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue);
}
else
{
_ilg.Call(_contextArg, primitiveContract.XmlFormatContentWriterMethod, _xmlWriterArg, memberValue);
}
}
else
{
if (memberType == Globals.TypeOfObject ||//boxed Nullable<T>
memberType == Globals.TypeOfValueType ||
((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType))
{
_ilg.Load(memberValue);
_ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject);
memberValue = _ilg.DeclareLocal(Globals.TypeOfObject, "unwrappedMemberValue");
memberType = memberValue.LocalType;
_ilg.Stloc(memberValue);
_ilg.If(memberValue, Cmp.EqualTo, null);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType));
_ilg.Else();
}
InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod),
memberValue, memberType, writeXsiType);
if (memberType == Globals.TypeOfObject) //boxed Nullable<T>
_ilg.EndIf();
}
_ilg.EndIf();
}
}
private void InternalSerialize(MethodInfo methodInfo, LocalBuilder memberValue, Type memberType, bool writeXsiType)
{
_ilg.Load(_contextArg);
_ilg.Load(_xmlWriterArg);
_ilg.Load(memberValue);
_ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject);
//In SL GetTypeHandle throws MethodAccessException as its internal and extern.
//So as a workaround, call XmlObjectSerializerWriteContext.IsMemberTypeSameAsMemberValue that
//does the actual comparison and returns the bool value we care.
_ilg.Call(null, XmlFormatGeneratorStatics.IsMemberTypeSameAsMemberValue, memberValue, memberType);
_ilg.Load(writeXsiType);
_ilg.Load(DataContract.GetId(memberType.TypeHandle));
_ilg.Ldtoken(memberType);
_ilg.Call(methodInfo);
}
private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !HasValue on stack
{
Type memberType = memberValue.LocalType;
Label onNull = _ilg.DefineLabel();
Label end = _ilg.DefineLabel();
_ilg.Load(memberValue);
while (memberType.GetTypeInfo().IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable)
{
Type innerType = memberType.GetGenericArguments()[0];
_ilg.Dup();
_ilg.Call(XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod(innerType));
_ilg.Brfalse(onNull);
_ilg.Call(XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod(innerType));
memberType = innerType;
}
memberValue = _ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue");
_ilg.Stloc(memberValue);
_ilg.Load(false); //isNull
_ilg.Br(end);
_ilg.MarkLabel(onNull);
_ilg.Pop();
_ilg.Call(XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod(memberType));
_ilg.Stloc(memberValue);
_ilg.Load(true);//isNull
_ilg.MarkLabel(end);
return memberValue;
}
private bool NeedsPrefix(Type type, XmlDictionaryString ns)
{
return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0);
}
private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder namespaceLocal, LocalBuilder nameLocal, int nameIndex)
{
bool needsPrefix = NeedsPrefix(type, ns);
_ilg.Load(_xmlWriterArg);
// prefix
if (needsPrefix)
_ilg.Load(Globals.ElementPrefix);
// localName
if (nameLocal == null)
_ilg.LoadArrayElement(_memberNamesLocal, nameIndex);
else
_ilg.Load(nameLocal);
// namespace
_ilg.Load(namespaceLocal);
_ilg.Call(needsPrefix ? XmlFormatGeneratorStatics.WriteStartElementMethod3 : XmlFormatGeneratorStatics.WriteStartElementMethod2);
}
private void WriteEndElement()
{
_ilg.Call(_xmlWriterArg, XmlFormatGeneratorStatics.WriteEndElementMethod);
}
private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract)
{
// Check for conflict with base type members
if (CheckIfConflictingMembersHaveDifferentTypes(member))
return true;
// Check for conflict with derived type members
string name = member.Name;
string ns = classContract.StableName.Namespace;
ClassDataContract currentContract = derivedMostClassContract;
while (currentContract != null && currentContract != classContract)
{
if (ns == currentContract.StableName.Namespace)
{
List<DataMember> members = currentContract.Members;
for (int j = 0; j < members.Count; j++)
{
if (name == members[j].Name)
return CheckIfConflictingMembersHaveDifferentTypes(members[j]);
}
}
currentContract = currentContract.BaseContract;
}
return false;
}
private bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member)
{
while (member.ConflictingMember != null)
{
if (member.MemberType != member.ConflictingMember.MemberType)
return true;
member = member.ConflictingMember;
}
return false;
}
}
}
#endif
}
| |
#if !BESTHTTP_DISABLE_SIGNALR
using System;
using System.Collections.Generic;
using BestHTTP.SignalR.Messages;
using BestHTTP.SignalR.JsonEncoders;
namespace BestHTTP.SignalR.Transports
{
public delegate void OnTransportStateChangedDelegate(TransportBase transport, TransportStates oldState, TransportStates newState);
public abstract class TransportBase
{
private const int MaxRetryCount = 5;
#region Public Properties
/// <summary>
/// Name of the transport.
/// </summary>
public string Name { get; protected set; }
/// <summary>
/// True if the manager has to check the last message received time and reconnect if too much time passes.
/// </summary>
public abstract bool SupportsKeepAlive { get; }
/// <summary>
/// Type of the transport. Used mainly by the manager in its BuildUri function.
/// </summary>
public abstract TransportTypes Type { get; }
/// <summary>
/// Reference to the manager.
/// </summary>
public IConnection Connection { get; protected set; }
/// <summary>
/// The current state of the transport.
/// </summary>
public TransportStates State
{
get { return _state; }
protected set
{
TransportStates old = _state;
_state = value;
if (OnStateChanged != null)
OnStateChanged(this, old, _state);
}
}
public TransportStates _state;
/// <summary>
/// Thi event called when the transport's State set to a new value.
/// </summary>
public event OnTransportStateChangedDelegate OnStateChanged;
#endregion
public TransportBase(string name, Connection connection)
{
this.Name = name;
this.Connection = connection;
this.State = TransportStates.Initial;
}
#region Abstract functions
/// <summary>
/// Start to connect to the server
/// </summary>
public abstract void Connect();
/// <summary>
/// Stop the connection
/// </summary>
public abstract void Stop();
/// <summary>
/// The transport specific implementation to send the given json string to the server.
/// </summary>
protected abstract void SendImpl(string json);
/// <summary>
/// Called when the Start request finished successfully, or after a reconnect.
/// Manager.TransportOpened(); called from the TransportBase after this call
/// </summary>
protected abstract void Started();
/// <summary>
/// Called when the abort request finished successfully.
/// </summary>
protected abstract void Aborted();
#endregion
/// <summary>
/// Called after a succesful connect/reconnect. The transport implementations have to call this function.
/// </summary>
protected void OnConnected()
{
if (this.State != TransportStates.Reconnecting)
{
// Send the Start request
Start();
}
else
{
Connection.TransportReconnected();
Started();
this.State = TransportStates.Started;
}
}
#region Start Request Sending
/// <summary>
/// Sends out the /start request to the server.
/// </summary>
protected void Start()
{
HTTPManager.Logger.Information("Transport - " + this.Name, "Sending Start Request");
this.State = TransportStates.Starting;
if (this.Connection.Protocol > ProtocolVersions.Protocol_2_0)
{
var request = new HTTPRequest(Connection.BuildUri(RequestTypes.Start, this), HTTPMethods.Get, true, true, OnStartRequestFinished);
request.Tag = 0;
request.DisableRetry = true;
request.Timeout = Connection.NegotiationResult.ConnectionTimeout + TimeSpan.FromSeconds(10);
Connection.PrepareRequest(request, RequestTypes.Start);
request.Send();
}
else
{
// The transport and the signalr protocol now started
this.State = TransportStates.Started;
Started();
Connection.TransportStarted();
}
}
private void OnStartRequestFinished(HTTPRequest req, HTTPResponse resp)
{
switch (req.State)
{
case HTTPRequestStates.Finished:
if (resp.IsSuccess)
{
HTTPManager.Logger.Information("Transport - " + this.Name, "Start - Returned: " + resp.DataAsText);
string response = Connection.ParseResponse(resp.DataAsText);
if (response != "started")
{
Connection.Error(string.Format("Expected 'started' response, but '{0}' found!", response));
return;
}
// The transport and the signalr protocol now started
this.State = TransportStates.Started;
Started();
Connection.TransportStarted();
return;
}
else
HTTPManager.Logger.Warning("Transport - " + this.Name, string.Format("Start - request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}",
resp.StatusCode,
resp.Message,
resp.DataAsText,
req.CurrentUri));
goto default;
default:
HTTPManager.Logger.Information("Transport - " + this.Name, "Start request state: " + req.State.ToString());
// The request may not reached the server. Try it again.
int retryCount = (int)req.Tag;
if (retryCount++ < MaxRetryCount)
{
req.Tag = retryCount;
req.Send();
}
else
Connection.Error("Failed to send Start request.");
break;
}
}
#endregion
#region Abort Implementation
/// <summary>
/// Will abort the transport. In SignalR 'Abort'ing is a graceful process, while 'Close'ing is a hard-abortion...
/// </summary>
public virtual void Abort()
{
if (this.State != TransportStates.Started)
return;
this.State = TransportStates.Closing;
var request = new HTTPRequest(Connection.BuildUri(RequestTypes.Abort, this), HTTPMethods.Get, true, true, OnAbortRequestFinished);
// Retry counter
request.Tag = 0;
request.DisableRetry = true;
Connection.PrepareRequest(request, RequestTypes.Abort);
request.Send();
}
protected void AbortFinished()
{
this.State = TransportStates.Closed;
Connection.TransportAborted();
this.Aborted();
}
private void OnAbortRequestFinished(HTTPRequest req, HTTPResponse resp)
{
switch (req.State)
{
case HTTPRequestStates.Finished:
if (resp.IsSuccess)
{
HTTPManager.Logger.Information("Transport - " + this.Name, "Abort - Returned: " + resp.DataAsText);
if (this.State == TransportStates.Closing)
AbortFinished();
}
else
{
HTTPManager.Logger.Warning("Transport - " + this.Name, string.Format("Abort - Handshake request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}",
resp.StatusCode,
resp.Message,
resp.DataAsText,
req.CurrentUri));
// try again
goto default;
}
break;
default:
HTTPManager.Logger.Information("Transport - " + this.Name, "Abort request state: " + req.State.ToString());
// The request may not reached the server. Try it again.
int retryCount = (int)req.Tag;
if (retryCount++ < MaxRetryCount)
{
req.Tag = retryCount;
req.Send();
}
else
Connection.Error("Failed to send Abort request!");
break;
}
}
#endregion
#region Send Implementation
/// <summary>
/// Sends the given json string to the wire.
/// </summary>
/// <param name="jsonStr"></param>
public void Send(string jsonStr)
{
try
{
HTTPManager.Logger.Information("Transport - " + this.Name, "Sending: " + jsonStr);
SendImpl(jsonStr);
}
catch (Exception ex)
{
HTTPManager.Logger.Exception("Transport - " + this.Name, "Send", ex);
}
}
#endregion
#region Helper Functions
/// <summary>
/// Start the reconnect process
/// </summary>
public void Reconnect()
{
HTTPManager.Logger.Information("Transport - " + this.Name, "Reconnecting");
Stop();
this.State = TransportStates.Reconnecting;
Connect();
}
/// <summary>
/// When the json string is successfully parsed will return with an IServerMessage implementation.
/// </summary>
public static IServerMessage Parse(IJsonEncoder encoder, string json)
{
// Nothing to parse?
if (string.IsNullOrEmpty(json))
{
HTTPManager.Logger.Error("MessageFactory", "Parse - called with empty or null string!");
return null;
}
// We don't have to do further decoding, if it's an empty json object, then it's a KeepAlive message from the server
if (json.Length == 2 && json == "{}")
return new KeepAliveMessage();
IDictionary<string, object> msg = null;
try
{
// try to decode the json message with the encoder
msg = encoder.DecodeMessage(json);
}
catch(Exception ex)
{
HTTPManager.Logger.Exception("MessageFactory", "Parse - encoder.DecodeMessage", ex);
return null;
}
if (msg == null)
{
HTTPManager.Logger.Error("MessageFactory", "Parse - Json Decode failed for json string: \"" + json + "\"");
return null;
}
// "C" is for message id
IServerMessage result = null;
if (!msg.ContainsKey("C"))
{
// If there are no ErrorMessage in the object, then it was a success
if (!msg.ContainsKey("E"))
result = new ResultMessage();
else
result = new FailureMessage();
}
else
result = new MultiMessage();
result.Parse(msg);
return result;
}
#endregion
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using CultureInfo = System.Globalization.CultureInfo;
using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute;
using StringBuilder = System.Text.StringBuilder;
namespace System.Xml.Linq
{
/// <summary>
/// Represents nodes (elements, comments, document type, processing instruction,
/// and text nodes) in the XML tree.
/// </summary>
/// <remarks>
/// Nodes in the XML tree consist of objects of the following classes:
/// <see cref="XElement"/>,
/// <see cref="XComment"/>,
/// <see cref="XDocument"/>,
/// <see cref="XProcessingInstruction"/>,
/// <see cref="XText"/>,
/// <see cref="XDocumentType"/>
/// Note that an <see cref="XAttribute"/> is not an <see cref="XNode"/>.
/// </remarks>
public abstract class XNode : XObject
{
private static XNodeDocumentOrderComparer s_documentOrderComparer;
private static XNodeEqualityComparer s_equalityComparer;
internal XNode next;
internal XNode() { }
/// <summary>
/// Gets the next sibling node of this node.
/// </summary>
/// <remarks>
/// If this property does not have a parent, or if there is no next node,
/// then this property returns null.
/// </remarks>
public XNode NextNode
{
get
{
return parent == null || this == parent.content ? null : next;
}
}
/// <summary>
/// Gets the previous sibling node of this node.
/// </summary>
/// <remarks>
/// If this property does not have a parent, or if there is no previous node,
/// then this property returns null.
/// </remarks>
public XNode PreviousNode
{
get
{
if (parent == null) return null;
XNode n = ((XNode)parent.content).next;
XNode p = null;
while (n != this)
{
p = n;
n = n.next;
}
return p;
}
}
/// <summary>
/// Gets a comparer that can compare the relative position of two nodes.
/// </summary>
public static XNodeDocumentOrderComparer DocumentOrderComparer
{
get
{
if (s_documentOrderComparer == null) s_documentOrderComparer = new XNodeDocumentOrderComparer();
return s_documentOrderComparer;
}
}
/// <summary>
/// Gets a comparer that can compare two nodes for value equality.
/// </summary>
public static XNodeEqualityComparer EqualityComparer
{
get
{
if (s_equalityComparer == null) s_equalityComparer = new XNodeEqualityComparer();
return s_equalityComparer;
}
}
/// <overloads>
/// Adds the specified content immediately after this node. The
/// content can be simple content, a collection of
/// content objects, a parameter list of content objects,
/// or null.
/// </overloads>
/// <summary>
/// Adds the specified content immediately after this node.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// to be added after this node.
/// </param>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void AddAfterSelf(object content)
{
if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent);
new Inserter(parent, this).Add(content);
}
/// <summary>
/// Adds the specified content immediately after this node.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
public void AddAfterSelf(params object[] content)
{
AddAfterSelf((object)content);
}
/// <overloads>
/// Adds the specified content immediately before this node. The
/// content can be simple content, a collection of
/// content objects, a parameter list of content objects,
/// or null.
/// </overloads>
/// <summary>
/// Adds the specified content immediately before this node.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// to be added after this node.
/// </param>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void AddBeforeSelf(object content)
{
if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent);
XNode p = (XNode)parent.content;
while (p.next != this) p = p.next;
if (p == parent.content) p = null;
new Inserter(parent, p).Add(content);
}
/// <summary>
/// Adds the specified content immediately before this node.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
public void AddBeforeSelf(params object[] content)
{
AddBeforeSelf((object)content);
}
/// <overloads>
/// Returns an collection of the ancestor elements for this node.
/// Optionally an node name can be specified to filter for a specific ancestor element.
/// </overloads>
/// <summary>
/// Returns a collection of the ancestor elements of this node.
/// </summary>
/// <returns>
/// The ancestor elements of this node.
/// </returns>
/// <remarks>
/// This method will not return itself in the results.
/// </remarks>
public IEnumerable<XElement> Ancestors()
{
return GetAncestors(null, false);
}
/// <summary>
/// Returns a collection of the ancestor elements of this node with the specified name.
/// </summary>
/// <param name="name">
/// The name of the ancestor elements to find.
/// </param>
/// <returns>
/// A collection of the ancestor elements of this node with the specified name.
/// </returns>
/// <remarks>
/// This method will not return itself in the results.
/// </remarks>
public IEnumerable<XElement> Ancestors(XName name)
{
return name != null ? GetAncestors(name, false) : XElement.EmptySequence;
}
/// <summary>
/// Compares two nodes to determine their relative XML document order.
/// </summary>
/// <param name="n1">First node to compare.</param>
/// <param name="n2">Second node to compare.</param>
/// <returns>
/// 0 if the nodes are equal; -1 if n1 is before n2; 1 if n1 is after n2.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Thrown if the two nodes do not share a common ancestor.
/// </exception>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Reviewed.")]
public static int CompareDocumentOrder(XNode n1, XNode n2)
{
if (n1 == n2) return 0;
if (n1 == null) return -1;
if (n2 == null) return 1;
if (n1.parent != n2.parent)
{
int height = 0;
XNode p1 = n1;
while (p1.parent != null)
{
p1 = p1.parent;
height++;
}
XNode p2 = n2;
while (p2.parent != null)
{
p2 = p2.parent;
height--;
}
if (p1 != p2) throw new InvalidOperationException(SR.InvalidOperation_MissingAncestor);
if (height < 0)
{
do
{
n2 = n2.parent;
height++;
} while (height != 0);
if (n1 == n2) return -1;
}
else if (height > 0)
{
do
{
n1 = n1.parent;
height--;
} while (height != 0);
if (n1 == n2) return 1;
}
while (n1.parent != n2.parent)
{
n1 = n1.parent;
n2 = n2.parent;
}
}
else if (n1.parent == null)
{
throw new InvalidOperationException(SR.InvalidOperation_MissingAncestor);
}
XNode n = (XNode)n1.parent.content;
while (true)
{
n = n.next;
if (n == n1) return -1;
if (n == n2) return 1;
}
}
/// <summary>
/// Creates an <see cref="XmlReader"/> for the node.
/// </summary>
/// <returns>An <see cref="XmlReader"/> that can be used to read the node and its descendants.</returns>
public XmlReader CreateReader()
{
return new XNodeReader(this, null);
}
/// <summary>
/// Creates an <see cref="XmlReader"/> for the node.
/// </summary>
/// <param name="readerOptions">
/// Options to be used for the returned reader. These override the default usage of annotations from the tree.
/// </param>
/// <returns>An <see cref="XmlReader"/> that can be used to read the node and its descendants.</returns>
public XmlReader CreateReader(ReaderOptions readerOptions)
{
return new XNodeReader(this, null, readerOptions);
}
/// <summary>
/// Returns a collection of the sibling nodes after this node, in document order.
/// </summary>
/// <remarks>
/// This method only includes sibling nodes in the returned collection.
/// </remarks>
/// <returns>The nodes after this node.</returns>
public IEnumerable<XNode> NodesAfterSelf()
{
XNode n = this;
while (n.parent != null && n != n.parent.content)
{
n = n.next;
yield return n;
}
}
/// <summary>
/// Returns a collection of the sibling nodes before this node, in document order.
/// </summary>
/// <remarks>
/// This method only includes sibling nodes in the returned collection.
/// </remarks>
/// <returns>The nodes after this node.</returns>
public IEnumerable<XNode> NodesBeforeSelf()
{
if (parent != null)
{
XNode n = (XNode)parent.content;
do
{
n = n.next;
if (n == this) break;
yield return n;
} while (parent != null && parent == n.parent);
}
}
/// <summary>
/// Returns a collection of the sibling element nodes after this node, in document order.
/// </summary>
/// <remarks>
/// This method only includes sibling element nodes in the returned collection.
/// </remarks>
/// <returns>The element nodes after this node.</returns>
public IEnumerable<XElement> ElementsAfterSelf()
{
return GetElementsAfterSelf(null);
}
/// <summary>
/// Returns a collection of the sibling element nodes with the specified name
/// after this node, in document order.
/// </summary>
/// <remarks>
/// This method only includes sibling element nodes in the returned collection.
/// </remarks>
/// <returns>The element nodes after this node with the specified name.</returns>
/// <param name="name">The name of elements to enumerate.</param>
public IEnumerable<XElement> ElementsAfterSelf(XName name)
{
return name != null ? GetElementsAfterSelf(name) : XElement.EmptySequence;
}
/// <summary>
/// Returns a collection of the sibling element nodes before this node, in document order.
/// </summary>
/// <remarks>
/// This method only includes sibling element nodes in the returned collection.
/// </remarks>
/// <returns>The element nodes before this node.</returns>
public IEnumerable<XElement> ElementsBeforeSelf()
{
return GetElementsBeforeSelf(null);
}
/// <summary>
/// Returns a collection of the sibling element nodes with the specified name
/// before this node, in document order.
/// </summary>
/// <remarks>
/// This method only includes sibling element nodes in the returned collection.
/// </remarks>
/// <returns>The element nodes before this node with the specified name.</returns>
/// <param name="name">The name of elements to enumerate.</param>
public IEnumerable<XElement> ElementsBeforeSelf(XName name)
{
return name != null ? GetElementsBeforeSelf(name) : XElement.EmptySequence;
}
/// <summary>
/// Determines if the current node appears after a specified node
/// in terms of document order.
/// </summary>
/// <param name="node">The node to compare for document order.</param>
/// <returns>True if this node appears after the specified node; false if not.</returns>
public bool IsAfter(XNode node)
{
return CompareDocumentOrder(this, node) > 0;
}
/// <summary>
/// Determines if the current node appears before a specified node
/// in terms of document order.
/// </summary>
/// <param name="node">The node to compare for document order.</param>
/// <returns>True if this node appears before the specified node; false if not.</returns>
public bool IsBefore(XNode node)
{
return CompareDocumentOrder(this, node) < 0;
}
/// <summary>
/// Creates an <see cref="XNode"/> from an <see cref="XmlReader"/>.
/// The runtime type of the node is determined by the node type
/// (<see cref="XObject.NodeType"/>) of the first node encountered
/// in the reader.
/// </summary>
/// <param name="reader">An <see cref="XmlReader"/> positioned at the node to read into this <see cref="XNode"/>.</param>
/// <returns>An <see cref="XNode"/> that contains the nodes read from the reader.</returns>
/// <exception cref="InvalidOperationException">
/// Thrown if the <see cref="XmlReader"/> is not positioned on a recognized node type.
/// </exception>
public static XNode ReadFrom(XmlReader reader)
{
if (reader == null) throw new ArgumentNullException(nameof(reader));
if (reader.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
switch (reader.NodeType)
{
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
return new XText(reader);
case XmlNodeType.CDATA:
return new XCData(reader);
case XmlNodeType.Comment:
return new XComment(reader);
case XmlNodeType.DocumentType:
return new XDocumentType(reader);
case XmlNodeType.Element:
return new XElement(reader);
case XmlNodeType.ProcessingInstruction:
return new XProcessingInstruction(reader);
default:
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, reader.NodeType));
}
}
/// <summary>
/// Creates an <see cref="XNode"/> from an <see cref="XmlReader"/>.
/// The runtime type of the node is determined by the node type
/// (<see cref="XObject.NodeType"/>) of the first node encountered
/// in the reader.
/// </summary>
/// <param name="reader">An <see cref="XmlReader"/> positioned at the node to read into this <see cref="XNode"/>.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>An <see cref="XNode"/> that contains the nodes read from the reader.</returns>
/// <exception cref="InvalidOperationException">
/// Thrown if the <see cref="XmlReader"/> is not positioned on a recognized node type.
/// </exception>
public static Task<XNode> ReadFromAsync(XmlReader reader, CancellationToken cancellationToken)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<XNode>(cancellationToken);
return ReadFromAsyncInternal(reader, cancellationToken);
}
private static async Task<XNode> ReadFromAsyncInternal(XmlReader reader, CancellationToken cancellationToken)
{
if (reader.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
XNode ret;
switch (reader.NodeType)
{
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
ret = new XText(reader.Value);
break;
case XmlNodeType.CDATA:
ret = new XCData(reader.Value);
break;
case XmlNodeType.Comment:
ret = new XComment(reader.Value);
break;
case XmlNodeType.DocumentType:
var name = reader.Name;
var publicId = reader.GetAttribute("PUBLIC");
var systemId = reader.GetAttribute("SYSTEM");
var internalSubset = reader.Value;
ret = new XDocumentType(name, publicId, systemId, internalSubset);
break;
case XmlNodeType.Element:
return await XElement.CreateAsync(reader, cancellationToken).ConfigureAwait(false);
case XmlNodeType.ProcessingInstruction:
var target = reader.Name;
var data = reader.Value;
ret = new XProcessingInstruction(target, data);
break;
default:
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, reader.NodeType));
}
cancellationToken.ThrowIfCancellationRequested();
await reader.ReadAsync().ConfigureAwait(false);
return ret;
}
/// <summary>
/// Removes this XNode from the underlying XML tree.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
public void Remove()
{
if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent);
parent.RemoveNode(this);
}
/// <overloads>
/// Replaces this node with the specified content. The
/// content can be simple content, a collection of
/// content objects, a parameter list of content objects,
/// or null.
/// </overloads>
/// <summary>
/// Replaces the content of this <see cref="XNode"/>.
/// </summary>
/// <param name="content">Content that replaces this node.</param>
public void ReplaceWith(object content)
{
if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent);
XContainer c = parent;
XNode p = (XNode)parent.content;
while (p.next != this) p = p.next;
if (p == parent.content) p = null;
parent.RemoveNode(this);
if (p != null && p.parent != c) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
new Inserter(c, p).Add(content);
}
/// <summary>
/// Replaces this node with the specified content.
/// </summary>
/// <param name="content">Content that replaces this node.</param>
public void ReplaceWith(params object[] content)
{
ReplaceWith((object)content);
}
/// <summary>
/// Provides the formatted XML text representation.
/// You can use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options.
/// </summary>
/// <returns>A formatted XML string.</returns>
public override string ToString()
{
return GetXmlString(GetSaveOptionsFromAnnotations());
}
/// <summary>
/// Provides the XML text representation.
/// </summary>
/// <param name="options">
/// If SaveOptions.DisableFormatting is enabled the output is not indented.
/// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed.
/// </param>
/// <returns>An XML string.</returns>
public string ToString(SaveOptions options)
{
return GetXmlString(options);
}
/// <summary>
/// Compares the values of two nodes, including the values of all descendant nodes.
/// </summary>
/// <param name="n1">The first node to compare.</param>
/// <param name="n2">The second node to compare.</param>
/// <returns>true if the nodes are equal, false otherwise.</returns>
/// <remarks>
/// A null node is equal to another null node but unequal to a non-null
/// node. Two <see cref="XNode"/> objects of different types are never equal. Two
/// <see cref="XText"/> nodes are equal if they contain the same text. Two
/// <see cref="XElement"/> nodes are equal if they have the same tag name, the same
/// set of attributes with the same values, and, ignoring comments and processing
/// instructions, contain two equal length sequences of equal content nodes.
/// Two <see cref="XDocument"/>s are equal if their root nodes are equal. Two
/// <see cref="XComment"/> nodes are equal if they contain the same comment text.
/// Two <see cref="XProcessingInstruction"/> nodes are equal if they have the same
/// target and data. Two <see cref="XDocumentType"/> nodes are equal if the have the
/// same name, public id, system id, and internal subset.</remarks>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Reviewed.")]
public static bool DeepEquals(XNode n1, XNode n2)
{
if (n1 == n2) return true;
if (n1 == null || n2 == null) return false;
return n1.DeepEquals(n2);
}
/// <summary>
/// Write the current node to an <see cref="XmlWriter"/>.
/// </summary>
/// <param name="writer">The <see cref="XmlWriter"/> to write the current node into.</param>
public abstract void WriteTo(XmlWriter writer);
/// <summary>
/// Write the current node to an <see cref="XmlWriter"/>.
/// </summary>
/// <param name="writer">The <see cref="XmlWriter"/> to write the current node into.</param>
/// <param name="cancellationToken">A cancellation token.</param>
public abstract Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken);
internal virtual void AppendText(StringBuilder sb)
{
}
internal abstract XNode CloneNode();
internal abstract bool DeepEquals(XNode node);
internal IEnumerable<XElement> GetAncestors(XName name, bool self)
{
XElement e = (self ? this : parent) as XElement;
while (e != null)
{
if (name == null || e.name == name) yield return e;
e = e.parent as XElement;
}
}
private IEnumerable<XElement> GetElementsAfterSelf(XName name)
{
XNode n = this;
while (n.parent != null && n != n.parent.content)
{
n = n.next;
XElement e = n as XElement;
if (e != null && (name == null || e.name == name)) yield return e;
}
}
private IEnumerable<XElement> GetElementsBeforeSelf(XName name)
{
if (parent != null)
{
XNode n = (XNode)parent.content;
do
{
n = n.next;
if (n == this) break;
XElement e = n as XElement;
if (e != null && (name == null || e.name == name)) yield return e;
} while (parent != null && parent == n.parent);
}
}
internal abstract int GetDeepHashCode();
// The settings simulate a non-validating processor with the external
// entity resolution disabled. The processing of the internal subset is
// enabled by default. In order to prevent DoS attacks, the expanded
// size of the internal subset is limited to 10 million characters.
internal static XmlReaderSettings GetXmlReaderSettings(LoadOptions o)
{
XmlReaderSettings rs = new XmlReaderSettings();
if ((o & LoadOptions.PreserveWhitespace) == 0) rs.IgnoreWhitespace = true;
// DtdProcessing.Parse; Parse is not defined in the public contract
rs.DtdProcessing = (DtdProcessing)2;
rs.MaxCharactersFromEntities = (long)1e7;
// rs.XmlResolver = null;
return rs;
}
internal static XmlWriterSettings GetXmlWriterSettings(SaveOptions o)
{
XmlWriterSettings ws = new XmlWriterSettings();
if ((o & SaveOptions.DisableFormatting) == 0) ws.Indent = true;
if ((o & SaveOptions.OmitDuplicateNamespaces) != 0) ws.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
return ws;
}
private string GetXmlString(SaveOptions o)
{
using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
if ((o & SaveOptions.DisableFormatting) == 0) ws.Indent = true;
if ((o & SaveOptions.OmitDuplicateNamespaces) != 0) ws.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
if (this is XText) ws.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlWriter w = XmlWriter.Create(sw, ws))
{
XDocument n = this as XDocument;
if (n != null)
{
n.WriteContentTo(w);
}
else
{
WriteTo(w);
}
}
return sw.ToString();
}
}
}
}
| |
/*-
* Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved.
*
* See the file LICENSE for license information.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml;
using NUnit.Framework;
using BerkeleyDB;
namespace CsharpAPITest {
[TestFixture]
public class ForeignKeyTest : CSharpTestFixture
{
[TestFixtureSetUp]
public void RunBeforeTests() {
testFixtureName = "ForeignKeyTest";
base.SetUpTestfixture();
}
[Test]
public void TestAbortBTree() {
testName = "TestAbortBTree";
TestForeignKeyDelete(DatabaseType.BTREE, ForeignKeyDeleteAction.ABORT);
}
[Test]
public void TestAbortHash() {
testName = "TestAbortHash";
TestForeignKeyDelete(DatabaseType.HASH, ForeignKeyDeleteAction.ABORT);
}
[Test]
public void TestAbortQueue() {
testName = "TestAbortQueue";
TestForeignKeyDelete(DatabaseType.QUEUE, ForeignKeyDeleteAction.ABORT);
}
[Test]
public void TestAbortRecno() {
testName = "TestAbortRecno";
TestForeignKeyDelete(DatabaseType.RECNO, ForeignKeyDeleteAction.ABORT);
}
[Test]
public void TestCascadeBTree() {
testName = "TestCascadeBTree";
TestForeignKeyDelete(DatabaseType.BTREE, ForeignKeyDeleteAction.CASCADE);
}
[Test]
public void TestCascadeHash() {
testName = "TestCascadeHash";
TestForeignKeyDelete(DatabaseType.HASH, ForeignKeyDeleteAction.CASCADE);
}
[Test]
public void TestCascadeQueue() {
testName = "TestCascadeQueue";
TestForeignKeyDelete(DatabaseType.QUEUE, ForeignKeyDeleteAction.CASCADE);
}
[Test]
public void TestCascadeRecno() {
testName = "TestCascadeRecno";
TestForeignKeyDelete(DatabaseType.RECNO, ForeignKeyDeleteAction.CASCADE);
}
[Test]
public void TestNullifyBTree() {
testName = "TestNullifyBTree";
TestForeignKeyDelete(DatabaseType.BTREE, ForeignKeyDeleteAction.NULLIFY);
}
[Test]
public void TestNullifyHash() {
testName = "TestNullifyHash";
TestForeignKeyDelete(DatabaseType.HASH, ForeignKeyDeleteAction.NULLIFY);
}
[Test]
public void TestNullifyQueue() {
testName = "TestNullifyQueue";
TestForeignKeyDelete(DatabaseType.QUEUE, ForeignKeyDeleteAction.NULLIFY);
}
[Test]
public void TestNullifyRecno() {
testName = "TestNullifyRecno";
TestForeignKeyDelete(DatabaseType.RECNO, ForeignKeyDeleteAction.NULLIFY);
}
public void TestForeignKeyDelete(DatabaseType dbtype, ForeignKeyDeleteAction action) {
SetUpTest(true);
string dbFileName = testHome + "/" + testName + ".db";
string fdbFileName = testHome + "/" + testName + "foreign.db";
string sdbFileName = testHome + "/" + testName + "sec.db";
Database primaryDB, fdb;
SecondaryDatabase secDB;
// Open primary database.
if (dbtype == DatabaseType.BTREE) {
BTreeDatabaseConfig btConfig = new BTreeDatabaseConfig();
btConfig.Creation = CreatePolicy.ALWAYS;
primaryDB = BTreeDatabase.Open(dbFileName, btConfig);
fdb = BTreeDatabase.Open(fdbFileName, btConfig);
} else if (dbtype == DatabaseType.HASH) {
HashDatabaseConfig hConfig = new HashDatabaseConfig();
hConfig.Creation = CreatePolicy.ALWAYS;
primaryDB = HashDatabase.Open(dbFileName, hConfig);
fdb = HashDatabase.Open(fdbFileName, hConfig);
} else if (dbtype == DatabaseType.QUEUE) {
QueueDatabaseConfig qConfig = new QueueDatabaseConfig();
qConfig.Creation = CreatePolicy.ALWAYS;
qConfig.Length = 4;
primaryDB = QueueDatabase.Open(dbFileName, qConfig);
fdb = QueueDatabase.Open(fdbFileName, qConfig);
} else if (dbtype == DatabaseType.RECNO) {
RecnoDatabaseConfig rConfig = new RecnoDatabaseConfig();
rConfig.Creation = CreatePolicy.ALWAYS;
primaryDB = RecnoDatabase.Open(dbFileName, rConfig);
fdb = RecnoDatabase.Open(fdbFileName, rConfig);
} else {
throw new ArgumentException("Invalid DatabaseType");
}
// Open secondary database.
if (dbtype == DatabaseType.BTREE) {
SecondaryBTreeDatabaseConfig secbtConfig =
new SecondaryBTreeDatabaseConfig(primaryDB,
new SecondaryKeyGenDelegate(SecondaryKeyGen));
secbtConfig.Creation = CreatePolicy.ALWAYS;
secbtConfig.Duplicates = DuplicatesPolicy.SORTED;
if (action == ForeignKeyDeleteAction.NULLIFY)
secbtConfig.SetForeignKeyConstraint(fdb, action, new ForeignKeyNullifyDelegate(Nullify));
else
secbtConfig.SetForeignKeyConstraint(fdb, action);
secDB = SecondaryBTreeDatabase.Open(sdbFileName, secbtConfig);
} else if (dbtype == DatabaseType.HASH) {
SecondaryHashDatabaseConfig sechConfig =
new SecondaryHashDatabaseConfig(primaryDB,
new SecondaryKeyGenDelegate(SecondaryKeyGen));
sechConfig.Creation = CreatePolicy.ALWAYS;
sechConfig.Duplicates = DuplicatesPolicy.SORTED;
if (action == ForeignKeyDeleteAction.NULLIFY)
sechConfig.SetForeignKeyConstraint(fdb, action, new ForeignKeyNullifyDelegate(Nullify));
else
sechConfig.SetForeignKeyConstraint(fdb, action);
secDB = SecondaryHashDatabase.Open(sdbFileName, sechConfig);
} else if (dbtype == DatabaseType.QUEUE) {
SecondaryQueueDatabaseConfig secqConfig =
new SecondaryQueueDatabaseConfig(primaryDB,
new SecondaryKeyGenDelegate(SecondaryKeyGen));
secqConfig.Creation = CreatePolicy.ALWAYS;
secqConfig.Length = 4;
if (action == ForeignKeyDeleteAction.NULLIFY)
secqConfig.SetForeignKeyConstraint(fdb, action, new ForeignKeyNullifyDelegate(Nullify));
else
secqConfig.SetForeignKeyConstraint(fdb, action);
secDB = SecondaryQueueDatabase.Open(sdbFileName, secqConfig);
} else if (dbtype == DatabaseType.RECNO) {
SecondaryRecnoDatabaseConfig secrConfig =
new SecondaryRecnoDatabaseConfig(primaryDB,
new SecondaryKeyGenDelegate(SecondaryKeyGen));
secrConfig.Creation = CreatePolicy.ALWAYS;
if (action == ForeignKeyDeleteAction.NULLIFY)
secrConfig.SetForeignKeyConstraint(fdb, action, new ForeignKeyNullifyDelegate(Nullify));
else
secrConfig.SetForeignKeyConstraint(fdb, action);
secDB = SecondaryRecnoDatabase.Open(sdbFileName, secrConfig);
} else {
throw new ArgumentException("Invalid DatabaseType");
}
/* Use integer keys for Queue/Recno support. */
fdb.Put(new DatabaseEntry(BitConverter.GetBytes(100)),
new DatabaseEntry(BitConverter.GetBytes(1001)));
fdb.Put(new DatabaseEntry(BitConverter.GetBytes(200)),
new DatabaseEntry(BitConverter.GetBytes(2002)));
fdb.Put(new DatabaseEntry(BitConverter.GetBytes(300)),
new DatabaseEntry(BitConverter.GetBytes(3003)));
primaryDB.Put(new DatabaseEntry(BitConverter.GetBytes(1)),
new DatabaseEntry(BitConverter.GetBytes(100)));
primaryDB.Put(new DatabaseEntry(BitConverter.GetBytes(2)),
new DatabaseEntry(BitConverter.GetBytes(200)));
if (dbtype == DatabaseType.BTREE || dbtype == DatabaseType.HASH)
primaryDB.Put(new DatabaseEntry(BitConverter.GetBytes(3)),
new DatabaseEntry(BitConverter.GetBytes(100)));
try {
fdb.Delete(new DatabaseEntry(BitConverter.GetBytes(100)));
} catch (ForeignConflictException) {
Assert.AreEqual(action, ForeignKeyDeleteAction.ABORT);
}
if (action == ForeignKeyDeleteAction.ABORT) {
Assert.IsTrue(secDB.Exists(new DatabaseEntry(BitConverter.GetBytes(100))));
Assert.IsTrue(primaryDB.Exists(new DatabaseEntry(BitConverter.GetBytes(1))));
Assert.IsTrue(fdb.Exists(new DatabaseEntry(BitConverter.GetBytes(100))));
} else if (action == ForeignKeyDeleteAction.CASCADE) {
try {
Assert.IsFalse(secDB.Exists(new DatabaseEntry(BitConverter.GetBytes(100))));
} catch (KeyEmptyException) {
Assert.IsTrue(dbtype == DatabaseType.QUEUE || dbtype == DatabaseType.RECNO);
}
try {
Assert.IsFalse(primaryDB.Exists(new DatabaseEntry(BitConverter.GetBytes(1))));
} catch (KeyEmptyException) {
Assert.IsTrue(dbtype == DatabaseType.QUEUE || dbtype == DatabaseType.RECNO);
}
try {
Assert.IsFalse(fdb.Exists(new DatabaseEntry(BitConverter.GetBytes(100))));
} catch (KeyEmptyException) {
Assert.IsTrue(dbtype == DatabaseType.QUEUE || dbtype == DatabaseType.RECNO);
}
} else if (action == ForeignKeyDeleteAction.NULLIFY) {
try {
Assert.IsFalse(secDB.Exists(new DatabaseEntry(BitConverter.GetBytes(100))));
} catch (KeyEmptyException) {
Assert.IsTrue(dbtype == DatabaseType.QUEUE || dbtype == DatabaseType.RECNO);
}
Assert.IsTrue(primaryDB.Exists(new DatabaseEntry(BitConverter.GetBytes(1))));
try {
Assert.IsFalse(fdb.Exists(new DatabaseEntry(BitConverter.GetBytes(100))));
} catch (KeyEmptyException) {
Assert.IsTrue(dbtype == DatabaseType.QUEUE || dbtype == DatabaseType.RECNO);
}
}
// Close secondary database.
secDB.Close();
// Close primary database.
primaryDB.Close();
// Close foreign database
fdb.Close();
}
public DatabaseEntry SecondaryKeyGen(
DatabaseEntry key, DatabaseEntry data) {
DatabaseEntry dbtGen;
int skey = BitConverter.ToInt32(data.Data, 0);
// don't index secondary key of 0
if (skey == 0)
return null;
dbtGen = new DatabaseEntry(data.Data);
return dbtGen;
}
public DatabaseEntry Nullify(DatabaseEntry key, DatabaseEntry data, DatabaseEntry fkey) {
DatabaseEntry ret = new DatabaseEntry(BitConverter.GetBytes(0));
return ret;
}
}
}
| |
// 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.Diagnostics.Contracts;
using System.Text;
namespace System.IO
{
public static partial class Path
{
public static readonly char DirectorySeparatorChar = '/';
public static readonly char VolumeSeparatorChar = '/';
public static readonly char PathSeparator = ':';
private const string DirectorySeparatorCharAsString = "/";
private static readonly char[] InvalidFileNameChars = { '\0', '/' };
private static readonly int MaxPath = Interop.Sys.MaxPath;
private static readonly int MaxLongPath = MaxPath;
// Expands the given path to a fully qualified path.
public static string GetFullPath(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Arg_PathIllegal);
PathInternal.CheckInvalidPathChars(path);
// Expand with current directory if necessary
if (!IsPathRooted(path))
{
path = Combine(Interop.Sys.GetCwd(), path);
}
// We would ideally use realpath to do this, but it resolves symlinks, requires that the file actually exist,
// and turns it into a full path, which we only want if fullCheck is true.
string collapsedString = RemoveRelativeSegments(path);
Debug.Assert(collapsedString.Length < path.Length || collapsedString.ToString() == path,
"Either we've removed characters, or the string should be unmodified from the input path.");
if (collapsedString.Length > MaxPath)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
string result = collapsedString.Length == 0 ? DirectorySeparatorCharAsString : collapsedString;
return result;
}
/// <summary>
/// Try to remove relative segments from the given path (without combining with a root).
/// </summary>
/// <param name="skip">Skip the specified number of characters before evaluating.</param>
private static string RemoveRelativeSegments(string path, int skip = 0)
{
bool flippedSeparator = false;
// Remove "//", "/./", and "/../" from the path by copying each character to the output,
// except the ones we're removing, such that the builder contains the normalized path
// at the end.
var sb = StringBuilderCache.Acquire(path.Length);
if (skip > 0)
{
sb.Append(path, 0, skip);
}
int componentCharCount = 0;
for (int i = skip; i < path.Length; i++)
{
char c = path[i];
if (PathInternal.IsDirectorySeparator(c) && i + 1 < path.Length)
{
componentCharCount = 0;
// Skip this character if it's a directory separator and if the next character is, too,
// e.g. "parent//child" => "parent/child"
if (PathInternal.IsDirectorySeparator(path[i + 1]))
{
continue;
}
// Skip this character and the next if it's referring to the current directory,
// e.g. "parent/./child" =? "parent/child"
if ((i + 2 == path.Length || PathInternal.IsDirectorySeparator(path[i + 2])) &&
path[i + 1] == '.')
{
i++;
continue;
}
// Skip this character and the next two if it's referring to the parent directory,
// e.g. "parent/child/../grandchild" => "parent/grandchild"
if (i + 2 < path.Length &&
(i + 3 == path.Length || PathInternal.IsDirectorySeparator(path[i + 3])) &&
path[i + 1] == '.' && path[i + 2] == '.')
{
// Unwind back to the last slash (and if there isn't one, clear out everything).
int s;
for (s = sb.Length - 1; s >= 0; s--)
{
if (PathInternal.IsDirectorySeparator(sb[s]))
{
sb.Length = s;
break;
}
}
if (s < 0)
{
sb.Length = 0;
}
i += 2;
continue;
}
}
if (++componentCharCount > PathInternal.MaxComponentLength)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
// Normalize the directory separator if needed
if (c != Path.DirectorySeparatorChar && c == Path.AltDirectorySeparatorChar)
{
c = Path.DirectorySeparatorChar;
flippedSeparator = true;
}
sb.Append(c);
}
if (flippedSeparator || sb.Length != path.Length)
{
return StringBuilderCache.GetStringAndRelease(sb);
}
else
{
// We haven't changed the source path, return the original
StringBuilderCache.Release(sb);
return path;
}
}
private static string RemoveLongPathPrefix(string path)
{
return path; // nop. There's nothing special about "long" paths on Unix.
}
public static string GetTempPath()
{
const string TempEnvVar = "TMPDIR";
const string DefaultTempPath = "/tmp/";
// Get the temp path from the TMPDIR environment variable.
// If it's not set, just return the default path.
// If it is, return it, ensuring it ends with a slash.
string path = Environment.GetEnvironmentVariable(TempEnvVar);
return
string.IsNullOrEmpty(path) ? DefaultTempPath :
PathInternal.IsDirectorySeparator(path[path.Length - 1]) ? path :
path + DirectorySeparatorChar;
}
public static string GetTempFileName()
{
const string Suffix = ".tmp";
const int SuffixByteLength = 4;
// mkstemps takes a char* and overwrites the XXXXXX with six characters
// that'll result in a unique file name.
string template = GetTempPath() + "tmpXXXXXX" + Suffix + "\0";
byte[] name = Encoding.UTF8.GetBytes(template);
// Create, open, and close the temp file.
IntPtr fd = Interop.CheckIo(Interop.Sys.MksTemps(name, SuffixByteLength));
Interop.Sys.Close(fd); // ignore any errors from close; nothing to do if cleanup isn't possible
// 'name' is now the name of the file
Debug.Assert(name[name.Length - 1] == '\0');
return Encoding.UTF8.GetString(name, 0, name.Length - 1); // trim off the trailing '\0'
}
public static bool IsPathRooted(string path)
{
if (path == null)
return false;
PathInternal.CheckInvalidPathChars(path);
return path.Length > 0 && path[0] == DirectorySeparatorChar;
}
public static string GetPathRoot(string path)
{
if (path == null) return null;
return IsPathRooted(path) ? DirectorySeparatorCharAsString : String.Empty;
}
private static unsafe void GetCryptoRandomBytes(byte* bytes, int byteCount)
{
Debug.Assert(bytes != null);
Debug.Assert(byteCount >= 0);
if (!Interop.Crypto.GetRandomBytes(bytes, byteCount))
{
throw new InvalidOperationException(SR.InvalidOperation_Cryptography);
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace UnityEngine.UI
{
/// <summary>
/// Labels are graphics that display text.
/// </summary>
[AddComponentMenu("UI/Text", 11)]
public class Text : MaskableGraphic, ILayoutElement
{
[SerializeField] private FontData m_FontData = FontData.defaultFontData;
[TextArea(3, 10)][SerializeField] protected string m_Text = String.Empty;
private TextGenerator m_TextCache;
private TextGenerator m_TextCacheForLayout;
private static float kEpsilon = 0.0001f;
static protected Material s_DefaultText = null;
// We use this flag instead of Unregistering/Registering the callback to avoid allocation.
[NonSerialized] private bool m_DisableFontTextureChangedCallback = false;
protected Text()
{ }
/// <summary>
/// Get or set the material used by this Text.
/// </summary>
public TextGenerator cachedTextGenerator
{
get { return m_TextCache ?? (m_TextCache = m_Text.Length != 0 ? new TextGenerator(m_Text.Length) : new TextGenerator()); }
}
public TextGenerator cachedTextGeneratorForLayout
{
get { return m_TextCacheForLayout ?? (m_TextCacheForLayout = new TextGenerator()); }
}
public override Material defaultMaterial
{
get
{
if (s_DefaultText == null)
s_DefaultText = Canvas.GetDefaultCanvasTextMaterial();
return s_DefaultText;
}
}
/// <summary>
/// Text's texture comes from the font.
/// </summary>
public override Texture mainTexture
{
get
{
if (font != null && font.material != null && font.material.mainTexture != null)
return font.material.mainTexture;
if (m_Material != null)
return m_Material.mainTexture;
return base.mainTexture;
}
}
public void FontTextureChanged()
{
// Only invoke if we are not destroyed.
if (!this)
{
FontUpdateTracker.UntrackText(this);
return;
}
if (m_DisableFontTextureChangedCallback)
return;
cachedTextGenerator.Invalidate();
if (!IsActive())
return;
// this is a bit hacky, but it is currently the
// cleanest solution....
// if we detect the font texture has changed and are in a rebuild loop
// we just regenerate the verts for the new UV's
if (CanvasUpdateRegistry.IsRebuildingGraphics() || CanvasUpdateRegistry.IsRebuildingLayout())
UpdateGeometry();
else
SetAllDirty();
}
public Font font
{
get
{
return m_FontData.font;
}
set
{
if (m_FontData.font == value)
return;
FontUpdateTracker.UntrackText(this);
m_FontData.font = value;
FontUpdateTracker.TrackText(this);
SetAllDirty();
}
}
/// <summary>
/// Text that's being displayed by the Text.
/// </summary>
public virtual string text
{
get
{
return m_Text;
}
set
{
if (String.IsNullOrEmpty(value))
{
if (String.IsNullOrEmpty(m_Text))
return;
m_Text = "";
SetVerticesDirty();
}
else if (m_Text != value)
{
m_Text = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
}
/// <summary>
/// Whether this Text will support rich text.
/// </summary>
public bool supportRichText
{
get
{
return m_FontData.richText;
}
set
{
if (m_FontData.richText == value)
return;
m_FontData.richText = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
/// <summary>
/// Wrap mode used by the text.
/// </summary>
public bool resizeTextForBestFit
{
get
{
return m_FontData.bestFit;
}
set
{
if (m_FontData.bestFit == value)
return;
m_FontData.bestFit = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public int resizeTextMinSize
{
get
{
return m_FontData.minSize;
}
set
{
if (m_FontData.minSize == value)
return;
m_FontData.minSize = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public int resizeTextMaxSize
{
get
{
return m_FontData.maxSize;
}
set
{
if (m_FontData.maxSize == value)
return;
m_FontData.maxSize = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
/// <summary>
/// Alignment anchor used by the text.
/// </summary>
public TextAnchor alignment
{
get
{
return m_FontData.alignment;
}
set
{
if (m_FontData.alignment == value)
return;
m_FontData.alignment = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public int fontSize
{
get
{
return m_FontData.fontSize;
}
set
{
if (m_FontData.fontSize == value)
return;
m_FontData.fontSize = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public HorizontalWrapMode horizontalOverflow
{
get
{
return m_FontData.horizontalOverflow;
}
set
{
if (m_FontData.horizontalOverflow == value)
return;
m_FontData.horizontalOverflow = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public VerticalWrapMode verticalOverflow
{
get
{
return m_FontData.verticalOverflow;
}
set
{
if (m_FontData.verticalOverflow == value)
return;
m_FontData.verticalOverflow = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public float lineSpacing
{
get
{
return m_FontData.lineSpacing;
}
set
{
if (m_FontData.lineSpacing == value)
return;
m_FontData.lineSpacing = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
/// <summary>
/// Font style used by the Text's text.
/// </summary>
public FontStyle fontStyle
{
get
{
return m_FontData.fontStyle;
}
set
{
if (m_FontData.fontStyle == value)
return;
m_FontData.fontStyle = value;
SetVerticesDirty();
SetLayoutDirty();
}
}
public float pixelsPerUnit
{
get
{
var localCanvas = canvas;
if (!localCanvas)
return 1;
// For dynamic fonts, ensure we use one pixel per pixel on the screen.
if (!font || font.dynamic)
return localCanvas.scaleFactor;
// For non-dynamic fonts, calculate pixels per unit based on specified font size relative to font object's own font size.
if (m_FontData.fontSize <= 0)
return 1;
return font.fontSize / (float)m_FontData.fontSize;
}
}
protected override void OnEnable()
{
base.OnEnable();
cachedTextGenerator.Invalidate();
FontUpdateTracker.TrackText(this);
}
protected override void OnDisable()
{
FontUpdateTracker.UntrackText(this);
base.OnDisable();
}
protected override void UpdateGeometry()
{
if (font != null)
{
base.UpdateGeometry();
}
}
#if UNITY_EDITOR
protected override void Reset()
{
font = Resources.GetBuiltinResource<Font>("Arial.ttf");
}
#endif
public TextGenerationSettings GetGenerationSettings(Vector2 extents)
{
var settings = new TextGenerationSettings();
// Settings affected by pixels density
var pixelsPerUnitCached = pixelsPerUnit;
settings.generationExtents = extents * pixelsPerUnitCached + Vector2.one * kEpsilon;
if (font != null && font.dynamic)
{
settings.fontSize = Mathf.FloorToInt(m_FontData.fontSize * pixelsPerUnitCached);
settings.resizeTextMinSize = Mathf.FloorToInt(m_FontData.minSize * pixelsPerUnitCached);
settings.resizeTextMaxSize = Mathf.FloorToInt(m_FontData.maxSize * pixelsPerUnitCached);
}
// Other settings
settings.textAnchor = m_FontData.alignment;
settings.color = color;
settings.font = font;
settings.pivot = rectTransform.pivot;
settings.richText = m_FontData.richText;
settings.lineSpacing = m_FontData.lineSpacing;
settings.fontStyle = m_FontData.fontStyle;
settings.resizeTextForBestFit = m_FontData.bestFit;
settings.updateBounds = false;
settings.horizontalOverflow = m_FontData.horizontalOverflow;
settings.verticalOverflow = m_FontData.verticalOverflow;
return settings;
}
static public Vector2 GetTextAnchorPivot(TextAnchor anchor)
{
switch (anchor)
{
case TextAnchor.LowerLeft: return new Vector2(0, 0);
case TextAnchor.LowerCenter: return new Vector2(0.5f, 0);
case TextAnchor.LowerRight: return new Vector2(1, 0);
case TextAnchor.MiddleLeft: return new Vector2(0, 0.5f);
case TextAnchor.MiddleCenter: return new Vector2(0.5f, 0.5f);
case TextAnchor.MiddleRight: return new Vector2(1, 0.5f);
case TextAnchor.UpperLeft: return new Vector2(0, 1);
case TextAnchor.UpperCenter: return new Vector2(0.5f, 1);
case TextAnchor.UpperRight: return new Vector2(1, 1);
default: return Vector2.zero;
}
}
/// <summary>
/// Draw the Text.
/// </summary>
protected override void OnFillVBO(List<UIVertex> vbo)
{
if (font == null)
return;
// We dont care if we the font Texture changes while we are doing our Update.
// The end result of cachedTextGenerator will be valid for this instance.
// Otherwise we can get issues like Case 619238.
m_DisableFontTextureChangedCallback = true;
Vector2 extents = rectTransform.rect.size;
var settings = GetGenerationSettings(extents);
cachedTextGenerator.Populate(m_Text, settings);
Rect inputRect = rectTransform.rect;
// get the text alignment anchor point for the text in local space
Vector2 textAnchorPivot = GetTextAnchorPivot(m_FontData.alignment);
Vector2 refPoint = Vector2.zero;
refPoint.x = (textAnchorPivot.x == 1 ? inputRect.xMax : inputRect.xMin);
refPoint.y = (textAnchorPivot.y == 0 ? inputRect.yMin : inputRect.yMax);
// Determine fraction of pixel to offset text mesh.
Vector2 roundingOffset = PixelAdjustPoint(refPoint) - refPoint;
// Apply the offset to the vertices
IList<UIVertex> verts = cachedTextGenerator.verts;
float unitsPerPixel = 1 / pixelsPerUnit;
if (roundingOffset != Vector2.zero)
{
for (int i = 0; i < verts.Count; i++)
{
UIVertex uiv = verts[i];
uiv.position *= unitsPerPixel;
uiv.position.x += roundingOffset.x;
uiv.position.y += roundingOffset.y;
vbo.Add(uiv);
}
}
else
{
for (int i = 0; i < verts.Count; i++)
{
UIVertex uiv = verts[i];
uiv.position *= unitsPerPixel;
vbo.Add(uiv);
}
}
m_DisableFontTextureChangedCallback = false;
}
public virtual void CalculateLayoutInputHorizontal() { }
public virtual void CalculateLayoutInputVertical() { }
public virtual float minWidth
{
get { return 0; }
}
public virtual float preferredWidth
{
get
{
var settings = GetGenerationSettings(Vector2.zero);
return cachedTextGeneratorForLayout.GetPreferredWidth(m_Text, settings) / pixelsPerUnit;
}
}
public virtual float flexibleWidth { get { return -1; } }
public virtual float minHeight
{
get { return 0; }
}
public virtual float preferredHeight
{
get
{
var settings = GetGenerationSettings(new Vector2(rectTransform.rect.size.x, 0.0f));
return cachedTextGeneratorForLayout.GetPreferredHeight(m_Text, settings) / pixelsPerUnit;
}
}
public virtual float flexibleHeight { get { return -1; } }
public virtual int layoutPriority { get { return 0; } }
#if UNITY_EDITOR
public override void OnRebuildRequested()
{
// After a Font asset gets re-imported the managed side gets deleted and recreated,
// that means the delegates are not persisted.
// so we need to properly enforce a consistent state here.
FontUpdateTracker.UntrackText(this);
FontUpdateTracker.TrackText(this);
// Also the textgenerator is no longer valid.
cachedTextGenerator.Invalidate();
base.OnRebuildRequested();
}
#endif // if UNITY_EDITOR
}
}
| |
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>
/// Controller class for Sys_Paciente
/// </summary>
[System.ComponentModel.DataObject]
public partial class SysPacienteController
{
// Preload our schema..
SysPaciente thisSchemaLoad = new SysPaciente();
private string userName = String.Empty;
protected string UserName
{
get
{
if (userName.Length == 0)
{
if (System.Web.HttpContext.Current != null)
{
userName=System.Web.HttpContext.Current.User.Identity.Name;
}
else
{
userName=System.Threading.Thread.CurrentPrincipal.Identity.Name;
}
}
return userName;
}
}
[DataObjectMethod(DataObjectMethodType.Select, true)]
public SysPacienteCollection FetchAll()
{
SysPacienteCollection coll = new SysPacienteCollection();
Query qry = new Query(SysPaciente.Schema);
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public SysPacienteCollection FetchByID(object IdPaciente)
{
SysPacienteCollection coll = new SysPacienteCollection().Where("idPaciente", IdPaciente).Load();
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public SysPacienteCollection FetchByQuery(Query qry)
{
SysPacienteCollection coll = new SysPacienteCollection();
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public bool Delete(object IdPaciente)
{
return (SysPaciente.Delete(IdPaciente) == 1);
}
[DataObjectMethod(DataObjectMethodType.Delete, false)]
public bool Destroy(object IdPaciente)
{
return (SysPaciente.Destroy(IdPaciente) == 1);
}
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Insert, true)]
public void Insert(int IdEfector,string Apellido,string Nombre,int NumeroDocumento,int IdSexo,DateTime FechaNacimiento,int IdEstado,int IdMotivoNI,int IdPais,int IdProvincia,int IdNivelInstruccion,int IdSituacionLaboral,int IdProfesion,int IdOcupacion,string Calle,int Numero,string Piso,string Departamento,string Manzana,int IdBarrio,int IdLocalidad,int IdDepartamento,int IdProvinciaDomicilio,string Referencia,string InformacionContacto,bool Cronico,int IdObraSocial,int IdUsuario,DateTime FechaAlta,DateTime FechaDefuncion,DateTime FechaUltimaActualizacion,int IdEstadoCivil,int IdEtnia,int IdPoblacion,int IdIdioma,string OtroBarrio,string Camino,string Campo,bool EsUrbano,string Lote,string Parcela,string Edificio,bool Activo,DateTime? FechaAltaObraSocial,string NumeroAfiliado,string NumeroExtranjero,string TelefonoFijo,string TelefonoCelular,string Email,string Latitud,string Longitud)
{
SysPaciente item = new SysPaciente();
item.IdEfector = IdEfector;
item.Apellido = Apellido;
item.Nombre = Nombre;
item.NumeroDocumento = NumeroDocumento;
item.IdSexo = IdSexo;
item.FechaNacimiento = FechaNacimiento;
item.IdEstado = IdEstado;
item.IdMotivoNI = IdMotivoNI;
item.IdPais = IdPais;
item.IdProvincia = IdProvincia;
item.IdNivelInstruccion = IdNivelInstruccion;
item.IdSituacionLaboral = IdSituacionLaboral;
item.IdProfesion = IdProfesion;
item.IdOcupacion = IdOcupacion;
item.Calle = Calle;
item.Numero = Numero;
item.Piso = Piso;
item.Departamento = Departamento;
item.Manzana = Manzana;
item.IdBarrio = IdBarrio;
item.IdLocalidad = IdLocalidad;
item.IdDepartamento = IdDepartamento;
item.IdProvinciaDomicilio = IdProvinciaDomicilio;
item.Referencia = Referencia;
item.InformacionContacto = InformacionContacto;
item.Cronico = Cronico;
item.IdObraSocial = IdObraSocial;
item.IdUsuario = IdUsuario;
item.FechaAlta = FechaAlta;
item.FechaDefuncion = FechaDefuncion;
item.FechaUltimaActualizacion = FechaUltimaActualizacion;
item.IdEstadoCivil = IdEstadoCivil;
item.IdEtnia = IdEtnia;
item.IdPoblacion = IdPoblacion;
item.IdIdioma = IdIdioma;
item.OtroBarrio = OtroBarrio;
item.Camino = Camino;
item.Campo = Campo;
item.EsUrbano = EsUrbano;
item.Lote = Lote;
item.Parcela = Parcela;
item.Edificio = Edificio;
item.Activo = Activo;
item.FechaAltaObraSocial = FechaAltaObraSocial;
item.NumeroAfiliado = NumeroAfiliado;
item.NumeroExtranjero = NumeroExtranjero;
item.TelefonoFijo = TelefonoFijo;
item.TelefonoCelular = TelefonoCelular;
item.Email = Email;
item.Latitud = Latitud;
item.Longitud = Longitud;
item.Save(UserName);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Update, true)]
public void Update(int IdPaciente,int IdEfector,string Apellido,string Nombre,int NumeroDocumento,int IdSexo,DateTime FechaNacimiento,int IdEstado,int IdMotivoNI,int IdPais,int IdProvincia,int IdNivelInstruccion,int IdSituacionLaboral,int IdProfesion,int IdOcupacion,string Calle,int Numero,string Piso,string Departamento,string Manzana,int IdBarrio,int IdLocalidad,int IdDepartamento,int IdProvinciaDomicilio,string Referencia,string InformacionContacto,bool Cronico,int IdObraSocial,int IdUsuario,DateTime FechaAlta,DateTime FechaDefuncion,DateTime FechaUltimaActualizacion,int IdEstadoCivil,int IdEtnia,int IdPoblacion,int IdIdioma,string OtroBarrio,string Camino,string Campo,bool EsUrbano,string Lote,string Parcela,string Edificio,bool Activo,DateTime? FechaAltaObraSocial,string NumeroAfiliado,string NumeroExtranjero,string TelefonoFijo,string TelefonoCelular,string Email,string Latitud,string Longitud)
{
SysPaciente item = new SysPaciente();
item.MarkOld();
item.IsLoaded = true;
item.IdPaciente = IdPaciente;
item.IdEfector = IdEfector;
item.Apellido = Apellido;
item.Nombre = Nombre;
item.NumeroDocumento = NumeroDocumento;
item.IdSexo = IdSexo;
item.FechaNacimiento = FechaNacimiento;
item.IdEstado = IdEstado;
item.IdMotivoNI = IdMotivoNI;
item.IdPais = IdPais;
item.IdProvincia = IdProvincia;
item.IdNivelInstruccion = IdNivelInstruccion;
item.IdSituacionLaboral = IdSituacionLaboral;
item.IdProfesion = IdProfesion;
item.IdOcupacion = IdOcupacion;
item.Calle = Calle;
item.Numero = Numero;
item.Piso = Piso;
item.Departamento = Departamento;
item.Manzana = Manzana;
item.IdBarrio = IdBarrio;
item.IdLocalidad = IdLocalidad;
item.IdDepartamento = IdDepartamento;
item.IdProvinciaDomicilio = IdProvinciaDomicilio;
item.Referencia = Referencia;
item.InformacionContacto = InformacionContacto;
item.Cronico = Cronico;
item.IdObraSocial = IdObraSocial;
item.IdUsuario = IdUsuario;
item.FechaAlta = FechaAlta;
item.FechaDefuncion = FechaDefuncion;
item.FechaUltimaActualizacion = FechaUltimaActualizacion;
item.IdEstadoCivil = IdEstadoCivil;
item.IdEtnia = IdEtnia;
item.IdPoblacion = IdPoblacion;
item.IdIdioma = IdIdioma;
item.OtroBarrio = OtroBarrio;
item.Camino = Camino;
item.Campo = Campo;
item.EsUrbano = EsUrbano;
item.Lote = Lote;
item.Parcela = Parcela;
item.Edificio = Edificio;
item.Activo = Activo;
item.FechaAltaObraSocial = FechaAltaObraSocial;
item.NumeroAfiliado = NumeroAfiliado;
item.NumeroExtranjero = NumeroExtranjero;
item.TelefonoFijo = TelefonoFijo;
item.TelefonoCelular = TelefonoCelular;
item.Email = Email;
item.Latitud = Latitud;
item.Longitud = Longitud;
item.Save(UserName);
}
}
}
| |
// 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.Diagnostics.Contracts;
using System.IO;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public abstract class HttpContent : IDisposable
{
private HttpContentHeaders _headers;
private MemoryStream _bufferedContent;
private bool _disposed;
private Stream _contentReadStream;
private bool _canCalculateLength;
internal const long MaxBufferSize = Int32.MaxValue;
internal static readonly Encoding DefaultStringEncoding = Encoding.UTF8;
private const int UTF8CodePage = 65001;
private const int UTF8PreambleLength = 3;
private const byte UTF8PreambleByte0 = 0xEF;
private const byte UTF8PreambleByte1 = 0xBB;
private const byte UTF8PreambleByte2 = 0xBF;
private const int UTF8PreambleFirst2Bytes = 0xEFBB;
#if !NETNative
// UTF32 not supported on Phone
private const int UTF32CodePage = 12000;
private const int UTF32PreambleLength = 4;
private const byte UTF32PreambleByte0 = 0xFF;
private const byte UTF32PreambleByte1 = 0xFE;
private const byte UTF32PreambleByte2 = 0x00;
private const byte UTF32PreambleByte3 = 0x00;
#endif
private const int UTF32OrUnicodePreambleFirst2Bytes = 0xFFFE;
private const int UnicodeCodePage = 1200;
private const int UnicodePreambleLength = 2;
private const byte UnicodePreambleByte0 = 0xFF;
private const byte UnicodePreambleByte1 = 0xFE;
private const int BigEndianUnicodeCodePage = 1201;
private const int BigEndianUnicodePreambleLength = 2;
private const byte BigEndianUnicodePreambleByte0 = 0xFE;
private const byte BigEndianUnicodePreambleByte1 = 0xFF;
private const int BigEndianUnicodePreambleFirst2Bytes = 0xFEFF;
#if DEBUG
static HttpContent()
{
// Ensure the encoding constants used in this class match the actual data from the Encoding class
AssertEncodingConstants(Encoding.UTF8, UTF8CodePage, UTF8PreambleLength, UTF8PreambleFirst2Bytes,
UTF8PreambleByte0,
UTF8PreambleByte1,
UTF8PreambleByte2);
#if !NETNative
// UTF32 not supported on Phone
AssertEncodingConstants(Encoding.UTF32, UTF32CodePage, UTF32PreambleLength, UTF32OrUnicodePreambleFirst2Bytes,
UTF32PreambleByte0,
UTF32PreambleByte1,
UTF32PreambleByte2,
UTF32PreambleByte3);
#endif
AssertEncodingConstants(Encoding.Unicode, UnicodeCodePage, UnicodePreambleLength, UTF32OrUnicodePreambleFirst2Bytes,
UnicodePreambleByte0,
UnicodePreambleByte1);
AssertEncodingConstants(Encoding.BigEndianUnicode, BigEndianUnicodeCodePage, BigEndianUnicodePreambleLength, BigEndianUnicodePreambleFirst2Bytes,
BigEndianUnicodePreambleByte0,
BigEndianUnicodePreambleByte1);
}
private static void AssertEncodingConstants(Encoding encoding, int codePage, int preambleLength, int first2Bytes, params byte[] preamble)
{
Debug.Assert(encoding != null);
Debug.Assert(preamble != null);
Debug.Assert(codePage == encoding.CodePage,
"Encoding code page mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual (Encoding.CodePage): {1}", codePage, encoding.CodePage);
byte[] actualPreamble = encoding.GetPreamble();
Debug.Assert(preambleLength == actualPreamble.Length,
"Encoding preamble length mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual (Encoding.GetPreamble().Length): {1}", preambleLength, actualPreamble.Length);
Debug.Assert(actualPreamble.Length >= 2);
int actualFirst2Bytes = actualPreamble[0] << 8 | actualPreamble[1];
Debug.Assert(first2Bytes == actualFirst2Bytes,
"Encoding preamble first 2 bytes mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual: {1}", first2Bytes, actualFirst2Bytes);
Debug.Assert(preamble.Length == actualPreamble.Length,
"Encoding preamble mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}",
BitConverter.ToString(preamble),
BitConverter.ToString(actualPreamble));
for (int i = 0; i < preamble.Length; i++)
{
Debug.Assert(preamble[i] == actualPreamble[i],
"Encoding preamble mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}",
BitConverter.ToString(preamble),
BitConverter.ToString(actualPreamble));
}
}
#endif
public HttpContentHeaders Headers
{
get
{
if (_headers == null)
{
_headers = new HttpContentHeaders(GetComputedOrBufferLength);
}
return _headers;
}
}
private bool IsBuffered
{
get { return _bufferedContent != null; }
}
#if NETNative
internal void SetBuffer(byte[] buffer, int offset, int count)
{
_bufferedContent = new MemoryStream(buffer, offset, count, false, true);
}
internal bool TryGetBuffer(out ArraySegment<byte> buffer)
{
if (_bufferedContent == null)
{
return false;
}
return _bufferedContent.TryGetBuffer(out buffer);
}
#endif
protected HttpContent()
{
// Log to get an ID for the current content. This ID is used when the content gets associated to a message.
if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", null);
// We start with the assumption that we can calculate the content length.
_canCalculateLength = true;
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
}
public Task<string> ReadAsStringAsync()
{
CheckDisposed();
var tcs = new TaskCompletionSource<string>(this);
LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) =>
{
var innerTcs = (TaskCompletionSource<string>)state;
var innerThis = (HttpContent)innerTcs.Task.AsyncState;
if (HttpUtilities.HandleFaultsAndCancelation(task, innerTcs))
{
return;
}
if (innerThis._bufferedContent.Length == 0)
{
innerTcs.TrySetResult(string.Empty);
return;
}
// We don't validate the Content-Encoding header: If the content was encoded, it's the caller's
// responsibility to make sure to only call ReadAsString() on already decoded content. E.g. if the
// Content-Encoding is 'gzip' the user should set HttpClientHandler.AutomaticDecompression to get a
// decoded response stream.
Encoding encoding = null;
int bomLength = -1;
byte[] data = innerThis.GetDataBuffer(innerThis._bufferedContent);
int dataLength = (int)innerThis._bufferedContent.Length; // Data is the raw buffer, it may not be full.
// If we do have encoding information in the 'Content-Type' header, use that information to convert
// the content to a string.
if ((innerThis.Headers.ContentType != null) && (innerThis.Headers.ContentType.CharSet != null))
{
try
{
encoding = Encoding.GetEncoding(innerThis.Headers.ContentType.CharSet);
// Byte-order-mark (BOM) characters may be present even if a charset was specified.
bomLength = GetPreambleLength(data, dataLength, encoding);
}
catch (ArgumentException e)
{
innerTcs.TrySetException(new InvalidOperationException(SR.net_http_content_invalid_charset, e));
return;
}
}
// If no content encoding is listed in the ContentType HTTP header, or no Content-Type header present,
// then check for a BOM in the data to figure out the encoding.
if (encoding == null)
{
if (!TryDetectEncoding(data, dataLength, out encoding, out bomLength))
{
// Use the default encoding (UTF8) if we couldn't detect one.
encoding = DefaultStringEncoding;
// We already checked to see if the data had a UTF8 BOM in TryDetectEncoding
// and DefaultStringEncoding is UTF8, so the bomLength is 0.
bomLength = 0;
}
}
try
{
// Drop the BOM when decoding the data.
string result = encoding.GetString(data, bomLength, dataLength - bomLength);
innerTcs.TrySetResult(result);
}
catch (Exception ex)
{
innerTcs.TrySetException(ex);
}
});
return tcs.Task;
}
public Task<byte[]> ReadAsByteArrayAsync()
{
CheckDisposed();
var tcs = new TaskCompletionSource<byte[]>(this);
LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) =>
{
var innerTcs = (TaskCompletionSource<byte[]>)state;
var innerThis = (HttpContent)innerTcs.Task.AsyncState;
if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs))
{
innerTcs.TrySetResult(innerThis._bufferedContent.ToArray());
}
});
return tcs.Task;
}
public Task<Stream> ReadAsStreamAsync()
{
CheckDisposed();
TaskCompletionSource<Stream> tcs = new TaskCompletionSource<Stream>(this);
if (_contentReadStream == null && IsBuffered)
{
byte[] data = this.GetDataBuffer(_bufferedContent);
// We can cast bufferedContent.Length to 'int' since the length will always be in the 'int' range
// The .NET Framework doesn't support array lengths > int.MaxValue.
Debug.Assert(_bufferedContent.Length <= (long)int.MaxValue);
_contentReadStream = new MemoryStream(data, 0,
(int)_bufferedContent.Length, false);
}
if (_contentReadStream != null)
{
tcs.TrySetResult(_contentReadStream);
return tcs.Task;
}
CreateContentReadStreamAsync().ContinueWithStandard(tcs, (task, state) =>
{
var innerTcs = (TaskCompletionSource<Stream>)state;
var innerThis = (HttpContent)innerTcs.Task.AsyncState;
if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs))
{
innerThis._contentReadStream = task.Result;
innerTcs.TrySetResult(innerThis._contentReadStream);
}
});
return tcs.Task;
}
protected abstract Task SerializeToStreamAsync(Stream stream, TransportContext context);
public Task CopyToAsync(Stream stream, TransportContext context)
{
CheckDisposed();
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
try
{
Task task = null;
if (IsBuffered)
{
byte[] data = this.GetDataBuffer(_bufferedContent);
task = stream.WriteAsync(data, 0, (int)_bufferedContent.Length);
}
else
{
task = SerializeToStreamAsync(stream, context);
CheckTaskNotNull(task);
}
// If the copy operation fails, wrap the exception in an HttpRequestException() if appropriate.
task.ContinueWithStandard(tcs, (copyTask, state) =>
{
var innerTcs = (TaskCompletionSource<object>)state;
if (copyTask.IsFaulted)
{
innerTcs.TrySetException(GetStreamCopyException(copyTask.Exception.GetBaseException()));
}
else if (copyTask.IsCanceled)
{
innerTcs.TrySetCanceled();
}
else
{
innerTcs.TrySetResult(null);
}
});
}
catch (IOException e)
{
tcs.TrySetException(GetStreamCopyException(e));
}
catch (ObjectDisposedException e)
{
tcs.TrySetException(GetStreamCopyException(e));
}
return tcs.Task;
}
public Task CopyToAsync(Stream stream)
{
return CopyToAsync(stream, null);
}
public Task LoadIntoBufferAsync()
{
return LoadIntoBufferAsync(MaxBufferSize);
}
// No "CancellationToken" parameter needed since canceling the CTS will close the connection, resulting
// in an exception being thrown while we're buffering.
// If buffering is used without a connection, it is supposed to be fast, thus no cancellation required.
public Task LoadIntoBufferAsync(long maxBufferSize)
{
CheckDisposed();
if (maxBufferSize > HttpContent.MaxBufferSize)
{
// This should only be hit when called directly; HttpClient/HttpClientHandler
// will not exceed this limit.
throw new ArgumentOutOfRangeException(nameof(maxBufferSize), maxBufferSize,
string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
}
if (IsBuffered)
{
// If we already buffered the content, just return a completed task.
return Task.CompletedTask;
}
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
Exception error = null;
MemoryStream tempBuffer = CreateMemoryStream(maxBufferSize, out error);
if (tempBuffer == null)
{
// We don't throw in LoadIntoBufferAsync(): set the task as faulted and return the task.
Debug.Assert(error != null);
tcs.TrySetException(error);
}
else
{
try
{
Task task = SerializeToStreamAsync(tempBuffer, null);
CheckTaskNotNull(task);
task.ContinueWithStandard(copyTask =>
{
try
{
if (copyTask.IsFaulted)
{
tempBuffer.Dispose(); // Cleanup partially filled stream.
tcs.TrySetException(GetStreamCopyException(copyTask.Exception.GetBaseException()));
return;
}
if (copyTask.IsCanceled)
{
tempBuffer.Dispose(); // Cleanup partially filled stream.
tcs.TrySetCanceled();
return;
}
tempBuffer.Seek(0, SeekOrigin.Begin); // Rewind after writing data.
_bufferedContent = tempBuffer;
tcs.TrySetResult(null);
}
catch (Exception e)
{
// Make sure we catch any exception, otherwise the task will catch it and throw in the finalizer.
tcs.TrySetException(e);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, "LoadIntoBufferAsync", e);
}
});
}
catch (IOException e)
{
tcs.TrySetException(GetStreamCopyException(e));
}
catch (ObjectDisposedException e)
{
tcs.TrySetException(GetStreamCopyException(e));
}
}
return tcs.Task;
}
protected virtual Task<Stream> CreateContentReadStreamAsync()
{
var tcs = new TaskCompletionSource<Stream>(this);
// By default just buffer the content to a memory stream. Derived classes can override this behavior
// if there is a better way to retrieve the content as stream (e.g. byte array/string use a more efficient
// way, like wrapping a read-only MemoryStream around the bytes/string)
LoadIntoBufferAsync().ContinueWithStandard(tcs, (task, state) =>
{
var innerTcs = (TaskCompletionSource<Stream>)state;
var innerThis = (HttpContent)innerTcs.Task.AsyncState;
if (!HttpUtilities.HandleFaultsAndCancelation(task, innerTcs))
{
innerTcs.TrySetResult(innerThis._bufferedContent);
}
});
return tcs.Task;
}
// Derived types return true if they're able to compute the length. It's OK if derived types return false to
// indicate that they're not able to compute the length. The transport channel needs to decide what to do in
// that case (send chunked, buffer first, etc.).
protected internal abstract bool TryComputeLength(out long length);
private long? GetComputedOrBufferLength()
{
CheckDisposed();
if (IsBuffered)
{
return _bufferedContent.Length;
}
// If we already tried to calculate the length, but the derived class returned 'false', then don't try
// again; just return null.
if (_canCalculateLength)
{
long length = 0;
if (TryComputeLength(out length))
{
return length;
}
// Set flag to make sure next time we don't try to compute the length, since we know that we're unable
// to do so.
_canCalculateLength = false;
}
return null;
}
private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error)
{
Contract.Ensures((Contract.Result<MemoryStream>() != null) ||
(Contract.ValueAtReturn<Exception>(out error) != null));
error = null;
// If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the
// content length exceeds the max. buffer size.
long? contentLength = Headers.ContentLength;
if (contentLength != null)
{
Debug.Assert(contentLength >= 0);
if (contentLength > maxBufferSize)
{
error = new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize));
return null;
}
// We can safely cast contentLength to (int) since we just checked that it is <= maxBufferSize.
return new LimitMemoryStream((int)maxBufferSize, (int)contentLength);
}
// We couldn't determine the length of the buffer. Create a memory stream with an empty buffer.
return new LimitMemoryStream((int)maxBufferSize, 0);
}
private byte[] GetDataBuffer(MemoryStream stream)
{
// TODO: Use TryGetBuffer() instead of ToArray().
return stream.ToArray();
}
#region IDisposable Members
protected virtual void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
if (_contentReadStream != null)
{
_contentReadStream.Dispose();
}
if (IsBuffered)
{
_bufferedContent.Dispose();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Helpers
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
}
private void CheckTaskNotNull(Task task)
{
if (task == null)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_content_no_task_returned_copytoasync, this.GetType().ToString()));
throw new InvalidOperationException(SR.net_http_content_no_task_returned);
}
}
private static Exception GetStreamCopyException(Exception originalException)
{
// HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream
// provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content
// types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple
// exceptions (depending on the underlying transport), but just HttpRequestExceptions
// Custom stream should throw either IOException or HttpRequestException.
// We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we
// don't want to hide such "usage error" exceptions in HttpRequestException.
// ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in
// the response stream being closed.
Exception result = originalException;
if ((result is IOException) || (result is ObjectDisposedException))
{
result = new HttpRequestException(SR.net_http_content_stream_copy_error, result);
}
return result;
}
private static int GetPreambleLength(byte[] data, int dataLength, Encoding encoding)
{
Debug.Assert(data != null);
Debug.Assert(dataLength <= data.Length);
Debug.Assert(encoding != null);
switch (encoding.CodePage)
{
case UTF8CodePage:
return (dataLength >= UTF8PreambleLength
&& data[0] == UTF8PreambleByte0
&& data[1] == UTF8PreambleByte1
&& data[2] == UTF8PreambleByte2) ? UTF8PreambleLength : 0;
#if !NETNative
// UTF32 not supported on Phone
case UTF32CodePage:
return (dataLength >= UTF32PreambleLength
&& data[0] == UTF32PreambleByte0
&& data[1] == UTF32PreambleByte1
&& data[2] == UTF32PreambleByte2
&& data[3] == UTF32PreambleByte3) ? UTF32PreambleLength : 0;
#endif
case UnicodeCodePage:
return (dataLength >= UnicodePreambleLength
&& data[0] == UnicodePreambleByte0
&& data[1] == UnicodePreambleByte1) ? UnicodePreambleLength : 0;
case BigEndianUnicodeCodePage:
return (dataLength >= BigEndianUnicodePreambleLength
&& data[0] == BigEndianUnicodePreambleByte0
&& data[1] == BigEndianUnicodePreambleByte1) ? BigEndianUnicodePreambleLength : 0;
default:
byte[] preamble = encoding.GetPreamble();
return ByteArrayHasPrefix(data, dataLength, preamble) ? preamble.Length : 0;
}
}
private static bool TryDetectEncoding(byte[] data, int dataLength, out Encoding encoding, out int preambleLength)
{
Debug.Assert(data != null);
Debug.Assert(dataLength <= data.Length);
if (dataLength >= 2)
{
int first2Bytes = data[0] << 8 | data[1];
switch (first2Bytes)
{
case UTF8PreambleFirst2Bytes:
if (dataLength >= UTF8PreambleLength && data[2] == UTF8PreambleByte2)
{
encoding = Encoding.UTF8;
preambleLength = UTF8PreambleLength;
return true;
}
break;
case UTF32OrUnicodePreambleFirst2Bytes:
#if !NETNative
// UTF32 not supported on Phone
if (dataLength >= UTF32PreambleLength && data[2] == UTF32PreambleByte2 && data[3] == UTF32PreambleByte3)
{
encoding = Encoding.UTF32;
preambleLength = UTF32PreambleLength;
}
else
#endif
{
encoding = Encoding.Unicode;
preambleLength = UnicodePreambleLength;
}
return true;
case BigEndianUnicodePreambleFirst2Bytes:
encoding = Encoding.BigEndianUnicode;
preambleLength = BigEndianUnicodePreambleLength;
return true;
}
}
encoding = null;
preambleLength = 0;
return false;
}
private static bool ByteArrayHasPrefix(byte[] byteArray, int dataLength, byte[] prefix)
{
if (prefix == null || byteArray == null || prefix.Length > dataLength || prefix.Length == 0)
return false;
for (int i = 0; i < prefix.Length; i++)
{
if (prefix[i] != byteArray[i])
return false;
}
return true;
}
#endregion Helpers
private class LimitMemoryStream : MemoryStream
{
private int _maxSize;
public LimitMemoryStream(int maxSize, int capacity)
: base(capacity)
{
_maxSize = maxSize;
}
public override void Write(byte[] buffer, int offset, int count)
{
CheckSize(count);
base.Write(buffer, offset, count);
}
public override void WriteByte(byte value)
{
CheckSize(1);
base.WriteByte(value);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckSize(count);
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
private void CheckSize(int countToAdd)
{
if (_maxSize - Length < countToAdd)
{
throw new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, _maxSize));
}
}
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System.Collections.Generic;
using Encog.ML.Data;
using Encog.Util;
namespace Encog.ML.HMM.Alog
{
/// <summary>
/// The forward-backward algorithm is an inference algorithm for hidden Markov
/// models which computes the posterior marginals of all hidden state variables
/// given a sequence of observations.
/// </summary>
public class ForwardBackwardCalculator
{
/// <summary>
/// Alpha matrix.
/// </summary>
protected double[][] Alpha;
/// <summary>
/// Beta matrix.
/// </summary>
protected double[][] Beta;
/// <summary>
/// Probability.
/// </summary>
protected double probability;
/// <summary>
/// Construct an empty object.
/// </summary>
protected ForwardBackwardCalculator()
{
}
/// <summary>
/// Construct the forward/backward calculator.
/// </summary>
/// <param name="oseq">The sequence to use.</param>
/// <param name="hmm">THe hidden markov model to use.</param>
public ForwardBackwardCalculator(IMLDataSet oseq,
HiddenMarkovModel hmm)
: this(oseq, hmm, true, false)
{
}
/// <summary>
/// Construct the object.
/// </summary>
/// <param name="oseq">The sequence.</param>
/// <param name="hmm">The hidden markov model to use.</param>
/// <param name="doAlpha">Do alpha?</param>
/// <param name="doBeta">Do beta?</param>
public ForwardBackwardCalculator(IMLDataSet oseq,
HiddenMarkovModel hmm, bool doAlpha, bool doBeta)
{
if (oseq.Count < 1)
{
throw new EncogError("Empty sequence");
}
if (doAlpha)
{
ComputeAlpha(hmm, oseq);
}
if (doBeta)
{
ComputeBeta(hmm, oseq);
}
ComputeProbability(oseq, hmm, doAlpha, doBeta);
}
/// <summary>
/// Alpha element.
/// </summary>
/// <param name="t">The row.</param>
/// <param name="i">The column.</param>
/// <returns>The element.</returns>
public double AlphaElement(int t, int i)
{
if (Alpha == null)
{
throw new EncogError("Alpha array has not "
+ "been computed");
}
return Alpha[t][i];
}
/// <summary>
/// Beta element, best element.
/// </summary>
/// <param name="t">From.</param>
/// <param name="i">To.</param>
/// <returns>The element.</returns>
public double BetaElement(int t, int i)
{
if (Beta == null)
{
throw new EncogError("Beta array has not "
+ "been computed");
}
return Beta[t][i];
}
/// <summary>
/// Compute alpha.
/// </summary>
/// <param name="hmm">The hidden markov model.</param>
/// <param name="oseq">The sequence.</param>
protected void ComputeAlpha(HiddenMarkovModel hmm,
IMLDataSet oseq)
{
Alpha = EngineArray.AllocateDouble2D((int) oseq.Count, hmm.StateCount);
for (int i = 0; i < hmm.StateCount; i++)
{
ComputeAlphaInit(hmm, oseq[0], i);
}
IEnumerator<IMLDataPair> seqIterator = oseq.GetEnumerator();
if (seqIterator.MoveNext())
{
for (int t = 1; t < oseq.Count; t++)
{
seqIterator.MoveNext(); /////
IMLDataPair observation = seqIterator.Current;
for (int i = 0; i < hmm.StateCount; i++)
{
ComputeAlphaStep(hmm, observation, t, i);
}
}
}
}
/// <summary>
/// Compute the alpha init.
/// </summary>
/// <param name="hmm">THe hidden markov model.</param>
/// <param name="o">The element.</param>
/// <param name="i">The state.</param>
protected void ComputeAlphaInit(HiddenMarkovModel hmm,
IMLDataPair o, int i)
{
Alpha[0][i] = hmm.GetPi(i)
*hmm.StateDistributions[i].Probability(o);
}
/// <summary>
/// Compute the alpha step.
/// </summary>
/// <param name="hmm">The hidden markov model.</param>
/// <param name="o">The sequence element.</param>
/// <param name="t">The alpha step.</param>
/// <param name="j">The column.</param>
protected void ComputeAlphaStep(HiddenMarkovModel hmm,
IMLDataPair o, int t, int j)
{
double sum = 0.0;
for (int i = 0; i < hmm.StateCount; i++)
{
sum += Alpha[t - 1][i]*hmm.TransitionProbability[i][j];
}
Alpha[t][j] = sum*hmm.StateDistributions[j].Probability(o);
}
/// <summary>
/// Compute the beta step.
/// </summary>
/// <param name="hmm">The hidden markov model.</param>
/// <param name="oseq">The sequence.</param>
protected void ComputeBeta(HiddenMarkovModel hmm, IMLDataSet oseq)
{
Beta = EngineArray.AllocateDouble2D((int) oseq.Count, hmm.StateCount);
for (int i = 0; i < hmm.StateCount; i++)
{
Beta[oseq.Count - 1][i] = 1.0;
}
for (var t = (int) (oseq.Count - 2); t >= 0; t--)
{
for (int i = 0; i < hmm.StateCount; i++)
{
ComputeBetaStep(hmm, oseq[t + 1], t, i);
}
}
}
/// <summary>
/// Compute the beta step.
/// </summary>
/// <param name="hmm">The hidden markov model.</param>
/// <param name="o">THe data par to compute.</param>
/// <param name="t">THe matrix row.</param>
/// <param name="i">THe matrix column.</param>
protected void ComputeBetaStep(HiddenMarkovModel hmm,
IMLDataPair o, int t, int i)
{
double sum = 0.0;
for (int j = 0; j < hmm.StateCount; j++)
{
sum += Beta[t + 1][j]*hmm.TransitionProbability[i][j]
*hmm.StateDistributions[j].Probability(o);
}
Beta[t][i] = sum;
}
/// <summary>
/// Compute the probability.
/// </summary>
/// <param name="oseq">The sequence.</param>
/// <param name="hmm">THe hidden markov model.</param>
/// <param name="doAlpha">Perform alpha step?</param>
/// <param name="doBeta">Perform beta step?</param>
private void ComputeProbability(IMLDataSet oseq,
HiddenMarkovModel hmm, bool doAlpha, bool doBeta)
{
probability = 0.0;
if (doAlpha)
{
for (int i = 0; i < hmm.StateCount; i++)
{
probability += Alpha[oseq.Count - 1][i];
}
}
else
{
for (int i = 0; i < hmm.StateCount; i++)
{
probability += hmm.GetPi(i)
*hmm.StateDistributions[i].Probability(oseq[0])
*Beta[0][i];
}
}
}
/// <summary>
/// The probability.
/// </summary>
/// <returns>The probability.</returns>
public double Probability()
{
return probability;
}
}
}
| |
// 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.Text;
using System.IO;
using System.Xml;
using Microsoft.Test.ModuleCore;
using XmlCoreTest.Common;
public enum NodeFlags
{
None = 0,
EmptyElement = 1,
HasValue = 2,
SingleQuote = 4,
DefaultAttribute = 8,
UnparsedEntities = 16,
IsWhitespace = 32,
DocumentRoot = 64,
AttributeTextNode = 128,
MixedContent = 256,
Indent = 512
}
abstract public class CXmlBase
{
protected XmlNodeType pnType;
protected string pstrName;
protected string pstrLocalName;
protected string pstrPrefix;
protected string pstrNamespace;
internal int pnDepth;
internal NodeFlags peFlags = NodeFlags.None;
internal CXmlBase prNextNode = null;
internal CXmlBase prParentNode = null;
internal CXmlBase prFirstChildNode = null;
internal CXmlBase prLastChildNode = null;
internal int pnChildNodes = 0;
//
// Constructors
//
public CXmlBase(string strPrefix, string strName, string strLocalName, XmlNodeType NodeType, string strNamespace)
{
pstrPrefix = strPrefix;
pstrName = strName;
pstrLocalName = strLocalName;
pnType = NodeType;
pstrNamespace = strNamespace;
}
public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType, string strNamespace)
: this(strPrefix, strName, strName, NodeType, strNamespace)
{ }
public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType)
: this(strPrefix, strName, strName, NodeType, "")
{ }
public CXmlBase(string strName, XmlNodeType NodeType)
: this("", strName, strName, NodeType, "")
{ }
//
// Virtual Methods and Properties
//
abstract public void Write(XmlWriter rXmlWriter);
abstract public string Xml { get; }
abstract public void WriteXml(TextWriter rTW);
abstract public string Value { get; }
//
// Public Methods and Properties
//
public string Name
{
get { return pstrName; }
}
public string LocalName
{
get { return pstrLocalName; }
}
public string Prefix
{
get { return pstrPrefix; }
}
public string Namespace
{
get { return pstrNamespace; }
}
public int Depth
{
get { return pnDepth; }
}
public XmlNodeType NodeType
{
get { return pnType; }
}
public NodeFlags Flags
{
get { return peFlags; }
}
public int ChildNodeCount
{
get { return pnChildNodes; }
}
public void InsertNode(CXmlBase rNode)
{
if (prFirstChildNode == null)
{
prFirstChildNode = prLastChildNode = rNode;
}
else
{
prLastChildNode.prNextNode = rNode;
prLastChildNode = rNode;
}
if ((this.peFlags & NodeFlags.IsWhitespace) == 0)
pnChildNodes++;
rNode.prParentNode = this;
}
//
// Internal Methods and Properties
//
internal CXmlBase _Child(int n)
{
int i;
int j;
CXmlBase rChild = prFirstChildNode;
for (i = 0, j = 0; rChild != null; i++, rChild = rChild.prNextNode)
{
if ((rChild.peFlags & NodeFlags.IsWhitespace) == 0)
{
if (j++ == n) break;
}
}
return rChild;
}
internal CXmlBase _Child(string str)
{
CXmlBase rChild;
for (rChild = prFirstChildNode; rChild != null; rChild = rChild.prNextNode)
if (rChild.Name == str) break;
return rChild;
}
}
public class CXmlAttribute : CXmlBase
{
//
// Constructor
//
public CXmlAttribute(XmlReader rXmlReader)
: base(rXmlReader.Prefix, rXmlReader.Name, rXmlReader.LocalName, rXmlReader.NodeType, rXmlReader.NamespaceURI)
{
if (rXmlReader.IsDefault)
peFlags |= NodeFlags.DefaultAttribute;
}
//
// Public Methods and Properties (Override)
//
override public void Write(XmlWriter rXmlWriter)
{
CXmlBase rNode;
if ((this.peFlags & NodeFlags.DefaultAttribute) == 0)
{
rXmlWriter.WriteStartAttribute(this.Prefix, this.LocalName, this.Namespace);
for (rNode = this.prFirstChildNode; rNode != null; rNode = rNode.prNextNode)
{
rNode.Write(rXmlWriter);
}
rXmlWriter.WriteEndAttribute();
}
}
override public string Xml
{
get
{
CXmlCache._rBufferWriter.Dispose();
WriteXml(CXmlCache._rBufferWriter);
return CXmlCache._rBufferWriter.ToString();
}
}
override public void WriteXml(TextWriter rTW)
{
if ((this.peFlags & NodeFlags.DefaultAttribute) == 0)
{
CXmlBase rNode;
rTW.Write(' ' + this.Name + '=' + this.Quote);
for (rNode = this.prFirstChildNode; rNode != null; rNode = rNode.prNextNode)
{
rNode.WriteXml(rTW);
}
rTW.Write(this.Quote);
}
}
//
// Public Methods and Properties
//
override public string Value
{
get
{
CXmlNode rNode;
string strValue = string.Empty;
for (rNode = (CXmlNode)this.prFirstChildNode; rNode != null; rNode = rNode.NextNode)
strValue += rNode.Value;
return strValue;
}
}
public CXmlAttribute NextAttribute
{
get { return (CXmlAttribute)this.prNextNode; }
}
public char Quote
{
get { return ((base.peFlags & NodeFlags.SingleQuote) != 0 ? '\'' : '"'); }
set { if (value == '\'') base.peFlags |= NodeFlags.SingleQuote; else base.peFlags &= ~NodeFlags.SingleQuote; }
}
public CXmlNode FirstChild
{
get { return (CXmlNode)base.prFirstChildNode; }
}
public CXmlNode Child(int n)
{
return (CXmlNode)base._Child(n);
}
public CXmlNode Child(string str)
{
return (CXmlNode)base._Child(str);
}
}
public class CXmlNode : CXmlBase
{
internal string _strValue = null;
private CXmlAttribute _rFirstAttribute = null;
private CXmlAttribute _rLastAttribute = null;
private int _nAttributeCount = 0;
//
// Constructors
//
public CXmlNode(string strPrefix, string strName, XmlNodeType NodeType)
: base(strPrefix, strName, NodeType)
{ }
public CXmlNode(XmlReader rXmlReader)
: base(rXmlReader.Prefix, rXmlReader.Name, rXmlReader.LocalName, rXmlReader.NodeType, rXmlReader.NamespaceURI)
{
peFlags |= CXmlCache._eDefaultFlags;
if (NodeType == XmlNodeType.Whitespace ||
NodeType == XmlNodeType.SignificantWhitespace)
{
peFlags |= NodeFlags.IsWhitespace;
}
if (rXmlReader.IsEmptyElement)
{
peFlags |= NodeFlags.EmptyElement;
}
if (rXmlReader.HasValue)
{
peFlags |= NodeFlags.HasValue;
_strValue = rXmlReader.Value;
}
}
//
// Public Methods and Properties (Override)
//
override public void Write(XmlWriter rXmlWriter)
{
CXmlBase rNode;
CXmlAttribute rAttribute;
string DocTypePublic = null;
string DocTypeSystem = null;
switch (this.NodeType)
{
case XmlNodeType.CDATA:
rXmlWriter.WriteCData(_strValue);
break;
case XmlNodeType.Comment:
rXmlWriter.WriteComment(_strValue);
break;
case XmlNodeType.DocumentType:
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
{
if (rAttribute.Name == "PUBLIC") { DocTypePublic = rAttribute.Value; }
if (rAttribute.Name == "SYSTEM") { DocTypeSystem = rAttribute.Value; }
}
rXmlWriter.WriteDocType(this.Name, DocTypePublic, DocTypeSystem, _strValue);
break;
case XmlNodeType.EntityReference:
rXmlWriter.WriteEntityRef(this.Name);
break;
case XmlNodeType.ProcessingInstruction:
rXmlWriter.WriteProcessingInstruction(this.Name, _strValue);
break;
case XmlNodeType.Text:
if (this.Name == string.Empty)
{
if ((this.Flags & NodeFlags.UnparsedEntities) == 0)
{
rXmlWriter.WriteString(_strValue);
}
else
{
rXmlWriter.WriteRaw(_strValue.ToCharArray(), 0, _strValue.Length);
}
}
else
{
if (this.pstrName[0] == '#')
rXmlWriter.WriteCharEntity(_strValue[0]);
else
rXmlWriter.WriteEntityRef(this.Name);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if ((this.prParentNode.peFlags & NodeFlags.DocumentRoot) != 0)
rXmlWriter.WriteRaw(_strValue.ToCharArray(), 0, _strValue.Length);
else
rXmlWriter.WriteString(_strValue);
break;
case XmlNodeType.Element:
rXmlWriter.WriteStartElement(this.Prefix, this.LocalName, null);
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
{
rAttribute.Write(rXmlWriter);
}
if ((this.Flags & NodeFlags.EmptyElement) == 0)
rXmlWriter.WriteString(string.Empty);
for (rNode = base.prFirstChildNode; rNode != null; rNode = rNode.prNextNode)
{
rNode.Write(rXmlWriter);
}
// Should only produce empty tag if the original document used empty tag
if ((this.Flags & NodeFlags.EmptyElement) == 0)
rXmlWriter.WriteFullEndElement();
else
rXmlWriter.WriteEndElement();
break;
case XmlNodeType.XmlDeclaration:
rXmlWriter.WriteRaw("<?xml " + _strValue + "?>");
break;
default:
throw (new Exception("Node.Write: Unhandled node type " + this.NodeType.ToString()));
}
}
override public string Xml
{
get
{
CXmlCache._rBufferWriter.Dispose();
WriteXml(CXmlCache._rBufferWriter);
return CXmlCache._rBufferWriter.ToString();
}
}
override public void WriteXml(TextWriter rTW)
{
String strXml;
CXmlAttribute rAttribute;
CXmlBase rNode;
switch (this.pnType)
{
case XmlNodeType.Text:
if (this.pstrName == "")
{
rTW.Write(_strValue);
}
else
{
if (this.pstrName.StartsWith("#"))
{
rTW.Write("&" + Convert.ToString(Convert.ToInt32(_strValue[0])) + ";");
}
else
{
rTW.Write("&" + this.Name + ";");
}
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.DocumentType:
rTW.Write(_strValue);
break;
case XmlNodeType.Element:
strXml = this.Name;
rTW.Write('<' + strXml);
//Put in all the Attributes
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
{
rAttribute.WriteXml(rTW);
}
//If there is children, put those in, otherwise close the tag.
if ((base.peFlags & NodeFlags.EmptyElement) == 0)
{
rTW.Write('>');
for (rNode = base.prFirstChildNode; rNode != null; rNode = rNode.prNextNode)
{
rNode.WriteXml(rTW);
}
rTW.Write("</" + strXml + ">");
}
else
{
rTW.Write(" />");
}
break;
case XmlNodeType.EntityReference:
rTW.Write("&" + this.pstrName + ";");
break;
case XmlNodeType.Notation:
rTW.Write("<!NOTATION " + _strValue + ">");
break;
case XmlNodeType.CDATA:
rTW.Write("<![CDATA[" + _strValue + "]]>");
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
rTW.Write("<?" + this.pstrName + " " + _strValue + "?>");
break;
case XmlNodeType.Comment:
rTW.Write("<!--" + _strValue + "-->");
break;
default:
throw (new Exception("Unhandled NodeType " + this.pnType.ToString()));
}
}
//
// Public Methods and Properties
//
public string NodeValue
{
get { return _strValue; }
}
override public string Value
{
get
{
string strValue = "";
CXmlNode rChild;
if ((this.peFlags & NodeFlags.HasValue) != 0)
{
char chEnt;
int nIndexAmp = 0;
int nIndexSem = 0;
if ((this.peFlags & NodeFlags.UnparsedEntities) == 0)
return _strValue;
strValue = _strValue;
while ((nIndexAmp = strValue.IndexOf('&', nIndexAmp)) != -1)
{
nIndexSem = strValue.IndexOf(';', nIndexAmp);
chEnt = ResolveCharEntity(strValue.Substring(nIndexAmp + 1, nIndexSem - nIndexAmp - 1));
if (chEnt != char.MinValue)
{
strValue = strValue.Substring(0, nIndexAmp) + chEnt + strValue.Substring(nIndexSem + 1);
nIndexAmp++;
}
else
nIndexAmp = nIndexSem;
}
return strValue;
}
for (rChild = (CXmlNode)this.prFirstChildNode; rChild != null; rChild = (CXmlNode)rChild.prNextNode)
{
strValue = strValue + rChild.Value;
}
return strValue;
}
}
public CXmlNode NextNode
{
get
{
CXmlBase rNode = this.prNextNode;
while (rNode != null &&
(rNode.Flags & NodeFlags.IsWhitespace) != 0)
rNode = rNode.prNextNode;
return (CXmlNode)rNode;
}
}
public CXmlNode FirstChild
{
get
{
CXmlBase rNode = this.prFirstChildNode;
while (rNode != null &&
(rNode.Flags & NodeFlags.IsWhitespace) != 0)
rNode = rNode.prNextNode;
return (CXmlNode)rNode;
}
}
public CXmlNode Child(int n)
{
int i;
CXmlNode rChild;
i = 0;
for (rChild = FirstChild; rChild != null; rChild = rChild.NextNode)
if (i++ == n) break;
return rChild;
}
public CXmlNode Child(string str)
{
return (CXmlNode)base._Child(str);
}
public int Type
{
get { return Convert.ToInt32(base.pnType); }
}
public CXmlAttribute FirstAttribute
{
get { return _rFirstAttribute; }
}
public int AttributeCount
{
get { return _nAttributeCount; }
}
public CXmlAttribute Attribute(int n)
{
int i;
CXmlAttribute rAttribute;
i = 0;
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
if (i++ == n) break;
return rAttribute;
}
public CXmlAttribute Attribute(string str)
{
CXmlAttribute rAttribute;
for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute)
{
if (rAttribute.Name == str) break;
}
return rAttribute;
}
public void AddAttribute(CXmlAttribute rAttribute)
{
if (_rFirstAttribute == null)
{
_rFirstAttribute = rAttribute;
}
else
{
_rLastAttribute.prNextNode = rAttribute;
}
_rLastAttribute = rAttribute;
_nAttributeCount++;
}
private char ResolveCharEntity(string strName)
{
if (strName[0] == '#')
if (strName[1] == 'x')
return Convert.ToChar(Convert.ToInt32(strName.Substring(2), 16));
else
return Convert.ToChar(Convert.ToInt32(strName.Substring(1)));
if (strName == "lt")
return '<';
if (strName == "gt")
return '>';
if (strName == "amp")
return '&';
if (strName == "apos")
return '\'';
if (strName == "quot")
return '"';
return char.MinValue;
}
}
public class CXmlCache
{
//CXmlCache Properties
private bool _fTrace = false;
private bool _fThrow = true;
private bool _fReadNode = true;
private int _hr = 0;
private Encoding _eEncoding = System.Text.Encoding.UTF8;
private string _strParseError = "";
//XmlReader Properties
private bool _fNamespaces = true;
private bool _fValidationCallback = false;
private bool _fExpandAttributeValues = false;
//Internal stuff
protected XmlReader prXmlReader = null;
protected CXmlNode prDocumentRootNode;
protected CXmlNode prRootNode = null;
internal static NodeFlags _eDefaultFlags = NodeFlags.None;
static internal BufferWriter _rBufferWriter = new BufferWriter();
//
// Constructor
//
public CXmlCache() { }
//
// Public Methods and Properties
//
public virtual bool Load(XmlReader rXmlReader)
{
//Hook up your reader as my reader
prXmlReader = rXmlReader;
//Process the Document
try
{
prDocumentRootNode = new CXmlNode("", "", XmlNodeType.Element);
prDocumentRootNode.peFlags = NodeFlags.DocumentRoot | NodeFlags.Indent;
Process(prDocumentRootNode);
for (prRootNode = prDocumentRootNode.FirstChild; prRootNode != null && prRootNode.NodeType != XmlNodeType.Element; prRootNode = prRootNode.NextNode) ;
}
catch (Exception e)
{
//Unhook your reader
prXmlReader = null;
_strParseError = e.ToString();
if (_fThrow)
{
throw (e);
}
if (_hr == 0)
_hr = -1;
return false;
}
//Unhook your reader
prXmlReader = null;
return true;
}
public bool Load(string strFileName)
{
XmlReader rXmlTextReader;
bool fRet;
rXmlTextReader = XmlReader.Create(FilePathUtil.getStream(strFileName));
fRet = Load(rXmlTextReader);
return fRet;
}
public void Save(string strName)
{
Save(strName, false, _eEncoding);
}
public void Save(string strName, bool fOverWrite)
{
Save(strName, fOverWrite, _eEncoding);
}
public void Save(string strName, bool fOverWrite, System.Text.Encoding Encoding)
{
CXmlBase rNode;
XmlWriter rXmlTextWriter = null;
try
{
rXmlTextWriter = XmlWriter.Create(FilePathUtil.getStream(strName));
for (rNode = prDocumentRootNode.prFirstChildNode; rNode != null; rNode = rNode.prNextNode)
{
rNode.Write(rXmlTextWriter);
}
rXmlTextWriter.Dispose();
}
catch (Exception e)
{
DebugTrace(e.ToString());
if (rXmlTextWriter != null)
rXmlTextWriter.Dispose();
throw (e);
}
}
virtual public string Xml
{
get
{
_rBufferWriter.Dispose();
WriteXml(_rBufferWriter);
return _rBufferWriter.ToString();
}
}
public void WriteXml(TextWriter rTW)
{
CXmlBase rNode;
//Spit out the document
for (rNode = prDocumentRootNode.prFirstChildNode; rNode != null; rNode = rNode.prNextNode)
rNode.WriteXml(rTW);
}
public CXmlNode RootNode
{
get { return prRootNode; }
}
public string ParseError
{
get { return _strParseError; }
}
public int ParseErrorCode
{
get { return _hr; }
}
//
// XmlReader Properties
//
public bool Namespaces
{
set { _fNamespaces = value; }
get { return _fNamespaces; }
}
public bool UseValidationCallback
{
set { _fValidationCallback = value; }
get { return _fValidationCallback; }
}
public bool ExpandAttributeValues
{
set { _fExpandAttributeValues = value; }
get { return _fExpandAttributeValues; }
}
//
// Internal Properties
//
public bool Throw
{
get { return _fThrow; }
set { _fThrow = value; }
}
public bool Trace
{
set { _fTrace = value; }
get { return _fTrace; }
}
//
//Private Methods
//
private void DebugTrace(string str)
{
DebugTrace(str, 0);
}
private void DebugTrace(string str, int nDepth)
{
if (_fTrace)
{
int i;
for (i = 0; i < nDepth; i++)
TestLog.Write(" ");
TestLog.WriteLine(str);
}
}
private void DebugTrace(XmlReader rXmlReader)
{
if (_fTrace)
{
string str;
str = rXmlReader.NodeType.ToString() + ", Depth=" + rXmlReader.Depth + " Name=";
if (rXmlReader.Prefix != "")
{
str += rXmlReader.Prefix + ":";
}
str += rXmlReader.LocalName;
if (rXmlReader.HasValue)
str += " Value=" + rXmlReader.Value;
DebugTrace(str, rXmlReader.Depth);
}
}
protected void Process(CXmlBase rParentNode)
{
CXmlNode rNewNode;
while (true)
{
//We want to pop if Read() returns false, aka EOF
if (_fReadNode)
{
if (!prXmlReader.Read())
{
DebugTrace("Read() == false");
return;
}
}
else
{
if (!prXmlReader.ReadAttributeValue())
{
DebugTrace("ReadAttributeValue() == false");
return;
}
}
DebugTrace(prXmlReader);
//We also want to pop if we get an EndElement or EndEntity
if (prXmlReader.NodeType == XmlNodeType.EndElement ||
prXmlReader.NodeType == XmlNodeType.EndEntity)
{
DebugTrace("NodeType == EndElement or EndEntity");
return;
}
rNewNode = GetNewNode(prXmlReader);
rNewNode.pnDepth = prXmlReader.Depth;
// Test for MixedContent and set Indent if necessary
if ((rParentNode.Flags & NodeFlags.MixedContent) != 0)
{
rNewNode.peFlags |= NodeFlags.MixedContent;
// Indent is off for all new nodes
}
else
{
rNewNode.peFlags |= NodeFlags.Indent; // Turn on Indent for current Node
}
// Set all Depth 0 nodes to No Mixed Content and Indent True
if (prXmlReader.Depth == 0)
{
rNewNode.peFlags |= NodeFlags.Indent; // Turn on Indent
rNewNode.peFlags &= ~NodeFlags.MixedContent; // Turn off MixedContent
}
rParentNode.InsertNode(rNewNode);
//Do some special stuff based on NodeType
switch (prXmlReader.NodeType)
{
case XmlNodeType.Element:
if (prXmlReader.MoveToFirstAttribute())
{
do
{
CXmlAttribute rNewAttribute = new CXmlAttribute(prXmlReader);
rNewNode.AddAttribute(rNewAttribute);
if (_fExpandAttributeValues)
{
DebugTrace("Attribute: " + prXmlReader.Name);
_fReadNode = false;
Process(rNewAttribute);
_fReadNode = true;
}
else
{
CXmlNode rValueNode = new CXmlNode("", "", XmlNodeType.Text);
rValueNode.peFlags = _eDefaultFlags | NodeFlags.HasValue;
rValueNode._strValue = prXmlReader.Value;
DebugTrace(" Value=" + rValueNode.Value, prXmlReader.Depth + 1);
rNewAttribute.InsertNode(rValueNode);
}
} while (prXmlReader.MoveToNextAttribute());
}
if ((rNewNode.Flags & NodeFlags.EmptyElement) == 0)
Process(rNewNode);
break;
case XmlNodeType.XmlDeclaration:
string strValue = rNewNode.NodeValue;
int nPos = strValue.IndexOf("encoding");
if (nPos != -1)
{
int nEnd;
nPos = strValue.IndexOf("=", nPos); //Find the = sign
nEnd = strValue.IndexOf("\"", nPos) + 1; //Find the next " character
nPos = strValue.IndexOf("'", nPos) + 1; //Find the next ' character
if (nEnd == 0 || (nPos < nEnd && nPos > 0)) //Pick the one that's closer to the = sign
{
nEnd = strValue.IndexOf("'", nPos);
}
else
{
nPos = nEnd;
nEnd = strValue.IndexOf("\"", nPos);
}
string sEncodeName = strValue.Substring(nPos, nEnd - nPos);
DebugTrace("XMLDecl contains encoding " + sEncodeName);
if (sEncodeName.ToUpper() == "UCS-2")
{
sEncodeName = "unicode";
}
_eEncoding = System.Text.Encoding.GetEncoding(sEncodeName);
}
break;
case XmlNodeType.ProcessingInstruction:
break;
case XmlNodeType.Text:
if (!_fReadNode)
{
rNewNode.peFlags = _eDefaultFlags | NodeFlags.AttributeTextNode;
}
rNewNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for current node
rNewNode.peFlags &= ~NodeFlags.Indent; // turn off Indent for current node
rParentNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for Parent Node
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.CDATA:
rNewNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for current node
rNewNode.peFlags &= ~NodeFlags.Indent; // turn off Indent for current node
rParentNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for Parent Node
break;
case XmlNodeType.Comment:
case XmlNodeType.Notation:
break;
case XmlNodeType.DocumentType:
if (prXmlReader.MoveToFirstAttribute())
{
do
{
CXmlAttribute rNewAttribute = new CXmlAttribute(prXmlReader);
rNewNode.AddAttribute(rNewAttribute);
CXmlNode rValueNode = new CXmlNode(prXmlReader);
rValueNode._strValue = prXmlReader.Value;
rNewAttribute.InsertNode(rValueNode);
} while (prXmlReader.MoveToNextAttribute());
}
break;
default:
TestLog.WriteLine("UNHANDLED TYPE, " + prXmlReader.NodeType.ToString() + " IN Process()!");
break;
}
}
}
protected virtual CXmlNode GetNewNode(XmlReader rXmlReader)
{
return new CXmlNode(rXmlReader);
}
}
public class ChecksumWriter : TextWriter
{
private int _nPosition = 0;
private Decimal _dResult = 0;
private Encoding _encoding;
// --------------------------------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------------------------------
public ChecksumWriter()
{
_encoding = Encoding.UTF8;
}
// --------------------------------------------------------------------------------------------------
// Properties
// --------------------------------------------------------------------------------------------------
public Decimal CheckSum
{
get { return _dResult; }
}
public override Encoding Encoding
{
get { return _encoding; }
}
// --------------------------------------------------------------------------------------------------
// Public methods
// --------------------------------------------------------------------------------------------------
override public void Write(String str)
{
int i;
int m;
m = str.Length;
for (i = 0; i < m; i++)
{
Write(str[i]);
}
}
override public void Write(Char[] rgch)
{
int i;
int m;
m = rgch.Length;
for (i = 0; i < m; i++)
{
Write(rgch[i]);
}
}
override public void Write(Char[] rgch, Int32 iOffset, Int32 iCount)
{
int i;
int m;
m = iOffset + iCount;
for (i = iOffset; i < m; i++)
{
Write(rgch[i]);
}
}
override public void Write(Char ch)
{
_dResult += Math.Round((Decimal)(ch / (_nPosition + 1.0)), 10);
_nPosition++;
}
public new void Dispose()
{
_nPosition = 0;
_dResult = 0;
}
}
public class BufferWriter : TextWriter
{
private int _nBufferSize = 0;
private int _nBufferUsed = 0;
private int _nBufferGrow = 1024;
private Char[] _rgchBuffer = null;
private Encoding _encoding;
// --------------------------------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------------------------------
public BufferWriter()
{
_encoding = Encoding.UTF8;
}
// --------------------------------------------------------------------------------------------------
// Properties
// --------------------------------------------------------------------------------------------------
override public string ToString()
{
return new String(_rgchBuffer, 0, _nBufferUsed);
}
public override Encoding Encoding
{
get { return _encoding; }
}
// --------------------------------------------------------------------------------------------------
// Public methods
// --------------------------------------------------------------------------------------------------
override public void Write(String str)
{
int i;
int m;
m = str.Length;
for (i = 0; i < m; i++)
{
Write(str[i]);
}
}
override public void Write(Char[] rgch)
{
int i;
int m;
m = rgch.Length;
for (i = 0; i < m; i++)
{
Write(rgch[i]);
}
}
override public void Write(Char[] rgch, Int32 iOffset, Int32 iCount)
{
int i;
int m;
m = iOffset + iCount;
for (i = iOffset; i < m; i++)
{
Write(rgch[i]);
}
}
override public void Write(Char ch)
{
if (_nBufferUsed == _nBufferSize)
{
Char[] rgchTemp = new Char[_nBufferSize + _nBufferGrow];
for (_nBufferUsed = 0; _nBufferUsed < _nBufferSize; _nBufferUsed++)
rgchTemp[_nBufferUsed] = _rgchBuffer[_nBufferUsed];
_rgchBuffer = rgchTemp;
_nBufferSize += _nBufferGrow;
if (_nBufferGrow < (1024 * 1024))
_nBufferGrow *= 2;
}
_rgchBuffer[_nBufferUsed++] = ch;
}
public new void Dispose()
{
//Set nBufferUsed to 0, so we start writing from the beginning of the buffer.
_nBufferUsed = 0;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace SpaJumpstart.WebServices.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
namespace EIDSS.Reports.Document.Veterinary.LivestockInvestigation
{
partial class VaccinationReport
{
/// <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 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(VaccinationReport));
this.Detail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand();
this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand();
this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel();
this.xrTableHeader = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.vaccinationDataSet1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.VaccinationDataSet();
this.sp_rep_VET_AvianCase_VaccinationTableAdapter = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.VaccinationDataSetTableAdapters.sp_rep_VET_AvianCase_VaccinationTableAdapter();
this.topMarginBand1 = new DevExpress.XtraReports.UI.TopMarginBand();
this.bottomMarginBand1 = new DevExpress.XtraReports.UI.BottomMarginBand();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTableHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.vaccinationDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// Detail
//
this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Name = "Detail";
this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// xrTable1
//
this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow2});
this.xrTable1.StylePriority.UseBorders = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell6,
this.xrTableCell7,
this.xrTableCell8});
this.xrTableRow2.Name = "xrTableRow2";
this.xrTableRow2.Weight = 0.65999999999999992;
//
// xrTableCell5
//
this.xrTableCell5.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.Diagnosis")});
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.Weight = 0.860153256704981;
//
// xrTableCell6
//
this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.datVaccinationDate", "{0:dd/MM/yyyy}")});
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Weight = 0.4195402298850574;
//
// xrTableCell7
//
this.xrTableCell7.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.strType")});
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.Weight = 0.86206896551724144;
//
// xrTableCell8
//
this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetVaccination.strRouteAdministered")});
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.Weight = 0.85823754789272033;
//
// PageHeader
//
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.Name = "PageHeader";
this.PageHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.PageHeader.StylePriority.UseFont = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.Name = "PageFooter";
this.PageFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel1,
this.xrTableHeader});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Name = "ReportHeader";
this.ReportHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.ReportHeader.StylePriority.UseFont = false;
this.ReportHeader.StylePriority.UsePadding = false;
this.ReportHeader.StylePriority.UseTextAlignment = false;
//
// xrLabel1
//
this.xrLabel1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel1, "xrLabel1");
this.xrLabel1.Name = "xrLabel1";
this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel1.StylePriority.UseBorders = false;
this.xrLabel1.StylePriority.UseFont = false;
//
// xrTableHeader
//
this.xrTableHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTableHeader, "xrTableHeader");
this.xrTableHeader.Name = "xrTableHeader";
this.xrTableHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1});
this.xrTableHeader.StylePriority.UseBorders = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell4,
this.xrTableCell1,
this.xrTableCell2,
this.xrTableCell3});
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Weight = 0.65999999999999992;
//
// xrTableCell4
//
this.xrTableCell4.Multiline = true;
this.xrTableCell4.Name = "xrTableCell4";
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Weight = 0.860153256704981;
//
// xrTableCell1
//
this.xrTableCell1.Name = "xrTableCell1";
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Weight = 0.4195402298850574;
//
// xrTableCell2
//
this.xrTableCell2.Name = "xrTableCell2";
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Weight = 0.86206896551724144;
//
// xrTableCell3
//
this.xrTableCell3.Name = "xrTableCell3";
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Weight = 0.85823754789272033;
//
// vaccinationDataSet1
//
this.vaccinationDataSet1.DataSetName = "VaccinationDataSet";
this.vaccinationDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// sp_rep_VET_AvianCase_VaccinationTableAdapter
//
this.sp_rep_VET_AvianCase_VaccinationTableAdapter.ClearBeforeFill = true;
//
// topMarginBand1
//
resources.ApplyResources(this.topMarginBand1, "topMarginBand1");
this.topMarginBand1.Name = "topMarginBand1";
//
// bottomMarginBand1
//
resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1");
this.bottomMarginBand1.Name = "bottomMarginBand1";
//
// VaccinationReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.topMarginBand1,
this.bottomMarginBand1});
this.DataAdapter = this.sp_rep_VET_AvianCase_VaccinationTableAdapter;
this.DataMember = "spRepVetVaccination";
this.DataSource = this.vaccinationDataSet1;
this.ExportOptions.Xls.SheetName = resources.GetString("VaccinationReport.ExportOptions.Xls.SheetName");
this.ExportOptions.Xlsx.SheetName = resources.GetString("VaccinationReport.ExportOptions.Xlsx.SheetName");
resources.ApplyResources(this, "$this");
this.Version = "10.1";
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTableHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.vaccinationDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailBand Detail;
private DevExpress.XtraReports.UI.PageHeaderBand PageHeader;
private DevExpress.XtraReports.UI.PageFooterBand PageFooter;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader;
private DevExpress.XtraReports.UI.XRTable xrTableHeader;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private VaccinationDataSet vaccinationDataSet1;
private EIDSS.Reports.Document.Veterinary.LivestockInvestigation.VaccinationDataSetTableAdapters.sp_rep_VET_AvianCase_VaccinationTableAdapter sp_rep_VET_AvianCase_VaccinationTableAdapter;
private DevExpress.XtraReports.UI.XRLabel xrLabel1;
private DevExpress.XtraReports.UI.TopMarginBand topMarginBand1;
private DevExpress.XtraReports.UI.BottomMarginBand bottomMarginBand1;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Xml;
namespace System.Runtime.Serialization.Json
{
internal class JsonCollectionDataContract : JsonDataContract
{
private JsonCollectionDataContractCriticalHelper _helper;
public JsonCollectionDataContract(CollectionDataContract traditionalDataContract)
: base(new JsonCollectionDataContractCriticalHelper(traditionalDataContract))
{
_helper = base.Helper as JsonCollectionDataContractCriticalHelper;
}
#if uapaot
[RemovableFeature(ReflectionBasedSerializationFeature.Name)]
#endif
private JsonFormatCollectionReaderDelegate CreateJsonFormatReaderDelegate()
{
return new ReflectionJsonCollectionReader().ReflectionReadCollection;
}
internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate
{
get
{
if (_helper.JsonFormatReaderDelegate == null)
{
lock (this)
{
if (_helper.JsonFormatReaderDelegate == null)
{
JsonFormatCollectionReaderDelegate tempDelegate;
if (DataContractSerializer.Option == SerializationOption.ReflectionOnly)
{
tempDelegate = CreateJsonFormatReaderDelegate();
}
#if uapaot
else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup)
{
tempDelegate = JsonDataContract.TryGetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract)?.CollectionReaderDelegate;
tempDelegate = tempDelegate ?? CreateJsonFormatReaderDelegate();
if (tempDelegate == null)
throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType.ToString()));
}
#endif
else
{
#if uapaot
tempDelegate = JsonDataContract.GetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract).CollectionReaderDelegate;
#else
tempDelegate = new JsonFormatReaderGenerator().GenerateCollectionReader(TraditionalCollectionDataContract);
#endif
}
Interlocked.MemoryBarrier();
_helper.JsonFormatReaderDelegate = tempDelegate;
}
}
}
return _helper.JsonFormatReaderDelegate;
}
}
#if uapaot
[RemovableFeature(ReflectionBasedSerializationFeature.Name)]
#endif
private JsonFormatGetOnlyCollectionReaderDelegate CreateJsonFormatGetOnlyReaderDelegate()
{
return new ReflectionJsonCollectionReader().ReflectionReadGetOnlyCollection;
}
internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelegate
{
get
{
if (_helper.JsonFormatGetOnlyReaderDelegate == null)
{
lock (this)
{
if (_helper.JsonFormatGetOnlyReaderDelegate == null)
{
CollectionKind kind = this.TraditionalCollectionDataContract.Kind;
if (this.TraditionalDataContract.UnderlyingType.IsInterface && (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable))
{
throw new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(this.TraditionalDataContract.UnderlyingType)));
}
JsonFormatGetOnlyCollectionReaderDelegate tempDelegate;
if (DataContractSerializer.Option == SerializationOption.ReflectionOnly)
{
tempDelegate = CreateJsonFormatGetOnlyReaderDelegate();
}
#if uapaot
else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup)
{
tempDelegate = JsonDataContract.TryGetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract)?.GetOnlyCollectionReaderDelegate;
tempDelegate = tempDelegate ?? CreateJsonFormatGetOnlyReaderDelegate();
if (tempDelegate == null)
throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType.ToString()));
}
#endif
else
{
#if uapaot
tempDelegate = JsonDataContract.GetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract).GetOnlyCollectionReaderDelegate;
#else
tempDelegate = new JsonFormatReaderGenerator().GenerateGetOnlyCollectionReader(TraditionalCollectionDataContract);
#endif
}
Interlocked.MemoryBarrier();
_helper.JsonFormatGetOnlyReaderDelegate = tempDelegate;
}
}
}
return _helper.JsonFormatGetOnlyReaderDelegate;
}
}
#if uapaot
[RemovableFeature(ReflectionBasedSerializationFeature.Name)]
#endif
private JsonFormatCollectionWriterDelegate CreateJsonFormatWriterDelegate()
{
return new ReflectionJsonFormatWriter().ReflectionWriteCollection;
}
internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate
{
get
{
if (_helper.JsonFormatWriterDelegate == null)
{
lock (this)
{
if (_helper.JsonFormatWriterDelegate == null)
{
JsonFormatCollectionWriterDelegate tempDelegate;
if (DataContractSerializer.Option == SerializationOption.ReflectionOnly)
{
tempDelegate = CreateJsonFormatWriterDelegate();
}
#if uapaot
else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup)
{
tempDelegate = JsonDataContract.TryGetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract)?.CollectionWriterDelegate;
tempDelegate = tempDelegate ?? CreateJsonFormatWriterDelegate();
if (tempDelegate == null)
throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType.ToString()));
}
#endif
else
{
#if uapaot
tempDelegate = JsonDataContract.GetReadWriteDelegatesFromGeneratedAssembly(TraditionalCollectionDataContract).CollectionWriterDelegate;
#else
tempDelegate = new JsonFormatWriterGenerator().GenerateCollectionWriter(TraditionalCollectionDataContract);
#endif
}
Interlocked.MemoryBarrier();
_helper.JsonFormatWriterDelegate = tempDelegate;
}
}
}
return _helper.JsonFormatWriterDelegate;
}
}
private CollectionDataContract TraditionalCollectionDataContract => _helper.TraditionalCollectionDataContract;
public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
jsonReader.Read();
object o = null;
if (context.IsGetOnlyCollection)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
JsonFormatGetOnlyReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, JsonGlobals.itemDictionaryString, TraditionalCollectionDataContract);
}
else
{
o = JsonFormatReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, JsonGlobals.itemDictionaryString, TraditionalCollectionDataContract);
}
jsonReader.ReadEndElement();
return o;
}
public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalCollectionDataContract);
}
private class JsonCollectionDataContractCriticalHelper : JsonDataContractCriticalHelper
{
private JsonFormatCollectionReaderDelegate _jsonFormatReaderDelegate;
private JsonFormatGetOnlyCollectionReaderDelegate _jsonFormatGetOnlyReaderDelegate;
private JsonFormatCollectionWriterDelegate _jsonFormatWriterDelegate;
private CollectionDataContract _traditionalCollectionDataContract;
public JsonCollectionDataContractCriticalHelper(CollectionDataContract traditionalDataContract)
: base(traditionalDataContract)
{
_traditionalCollectionDataContract = traditionalDataContract;
}
internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate
{
get { return _jsonFormatReaderDelegate; }
set { _jsonFormatReaderDelegate = value; }
}
internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelegate
{
get { return _jsonFormatGetOnlyReaderDelegate; }
set { _jsonFormatGetOnlyReaderDelegate = value; }
}
internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate
{
get { return _jsonFormatWriterDelegate; }
set { _jsonFormatWriterDelegate = value; }
}
internal CollectionDataContract TraditionalCollectionDataContract
{
get { return _traditionalCollectionDataContract; }
}
}
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at https://github.com/jeremyskinner/FluentValidation
#endregion
namespace FluentValidation.Internal {
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Resources;
using Results;
using Validators;
/// <summary>
/// Defines a rule associated with a property.
/// </summary>
public class PropertyRule : IValidationRule {
readonly List<IPropertyValidator> validators = new List<IPropertyValidator>();
Func<CascadeMode> cascadeModeThunk = () => ValidatorOptions.CascadeMode;
string propertyDisplayName;
string propertyName;
/// <summary>
/// Property associated with this rule.
/// </summary>
public MemberInfo Member { get; private set; }
/// <summary>
/// Function that can be invoked to retrieve the value of the property.
/// </summary>
public Func<object, object> PropertyFunc { get; private set; }
/// <summary>
/// Expression that was used to create the rule.
/// </summary>
public LambdaExpression Expression { get; private set; }
/// <summary>
/// String source that can be used to retrieve the display name (if null, falls back to the property name)
/// </summary>
public IStringSource DisplayName { get; set; }
/// <summary>
/// Rule set that this rule belongs to (if specified)
/// </summary>
public string RuleSet { get; set; }
/// <summary>
/// Function that will be invoked if any of the validators associated with this rule fail.
/// </summary>
public Action<object> OnFailure { get; set; }
/// <summary>
/// The current validator being configured by this rule.
/// </summary>
public IPropertyValidator CurrentValidator { get; private set; }
/// <summary>
/// Type of the property being validated
/// </summary>
public Type TypeToValidate { get; private set; }
/// <summary>
/// Cascade mode for this rule.
/// </summary>
public CascadeMode CascadeMode {
get { return cascadeModeThunk(); }
set { cascadeModeThunk = () => value; }
}
/// <summary>
/// Validators associated with this rule.
/// </summary>
public IEnumerable<IPropertyValidator> Validators {
get { return validators; }
}
/// <summary>
/// Creates a new property rule.
/// </summary>
/// <param name="member">Property</param>
/// <param name="propertyFunc">Function to get the property value</param>
/// <param name="expression">Lambda expression used to create the rule</param>
/// <param name="cascadeModeThunk">Function to get the cascade mode.</param>
/// <param name="typeToValidate">Type to validate</param>
/// <param name="containerType">Container type that owns the property</param>
public PropertyRule(MemberInfo member, Func<object, object> propertyFunc, LambdaExpression expression, Func<CascadeMode> cascadeModeThunk, Type typeToValidate, Type containerType) {
Member = member;
PropertyFunc = propertyFunc;
Expression = expression;
OnFailure = x => { };
TypeToValidate = typeToValidate;
this.cascadeModeThunk = cascadeModeThunk;
DependentRules = new List<IValidationRule>();
PropertyName = ValidatorOptions.PropertyNameResolver(containerType, member, expression);
DisplayName = new LazyStringSource(x => ValidatorOptions.DisplayNameResolver(containerType, member, expression));
}
/// <summary>
/// Creates a new property rule from a lambda expression.
/// </summary>
public static PropertyRule Create<T, TProperty>(Expression<Func<T, TProperty>> expression) {
return Create(expression, () => ValidatorOptions.CascadeMode);
}
/// <summary>
/// Creates a new property rule from a lambda expression.
/// </summary>
public static PropertyRule Create<T, TProperty>(Expression<Func<T, TProperty>> expression, Func<CascadeMode> cascadeModeThunk) {
var member = expression.GetMember();
// We can't use the expression tree as a key in the cache, as it doesn't implement GetHashCode/Equals in a useful way.
// Instead we'll use the MemberInfo as the key, but this only works for member expressions.
// If this is not a member expression (eg, a RuleFor(x => x) or a RuleFor(x => x.Foo())) then we won't cache the result.
// We could probably make the cache more robust in future.
var compiled = member == null || ValidatorOptions.DisableAccessorCache ? expression.Compile() : AccessorCache<T>.GetCachedAccessor(member, expression);
return new PropertyRule(member, compiled.CoerceToNonGeneric(), expression, cascadeModeThunk, typeof(TProperty), typeof(T));
}
/// <summary>
/// Adds a validator to the rule.
/// </summary>
public void AddValidator(IPropertyValidator validator) {
CurrentValidator = validator;
validators.Add(validator);
}
/// <summary>
/// Replaces a validator in this rule. Used to wrap validators.
/// </summary>
public void ReplaceValidator(IPropertyValidator original, IPropertyValidator newValidator) {
var index = validators.IndexOf(original);
if (index > -1) {
validators[index] = newValidator;
if (ReferenceEquals(CurrentValidator, original)) {
CurrentValidator = newValidator;
}
}
}
/// <summary>
/// Remove a validator in this rule.
/// </summary>
public void RemoveValidator(IPropertyValidator original) {
if (ReferenceEquals(CurrentValidator, original)) {
CurrentValidator = validators.LastOrDefault(x => x != original);
}
validators.Remove(original);
}
/// <summary>
/// Clear all validators from this rule.
/// </summary>
public void ClearValidators() {
CurrentValidator = null;
validators.Clear();
}
/// <summary>
/// Returns the property name for the property being validated.
/// Returns null if it is not a property being validated (eg a method call)
/// </summary>
public string PropertyName {
get { return propertyName; }
set {
propertyName = value;
propertyDisplayName = propertyName.SplitPascalCase();
}
}
/// <summary>
/// Allows custom creation of an error message
/// </summary>
public Func<PropertyValidatorContext, string> MessageBuilder { get; set; }
/// <summary>
/// Dependent rules
/// </summary>
public List<IValidationRule> DependentRules { get; private set; }
/// <summary>
/// Display name for the property.
/// </summary>
public string GetDisplayName() {
string result = null;
if (DisplayName != null) {
result = DisplayName.GetString(null /*We don't have a model object at this point*/);
}
if (result == null) {
result = propertyDisplayName;
}
return result;
}
/// <summary>
/// Performs validation using a validation context and returns a collection of Validation Failures.
/// </summary>
/// <param name="context">Validation Context</param>
/// <returns>A collection of validation failures</returns>
public virtual IEnumerable<ValidationFailure> Validate(ValidationContext context) {
string displayName = GetDisplayName();
if (PropertyName == null && displayName == null) {
//No name has been specified. Assume this is a model-level rule, so we should use empty string instead.
displayName = string.Empty;
}
// Construct the full name of the property, taking into account overriden property names and the chain (if we're in a nested validator)
string propertyName = context.PropertyChain.BuildPropertyName(PropertyName ?? displayName);
// Ensure that this rule is allowed to run.
// The validatselector has the opportunity to veto this before any of the validators execute.
if (!context.Selector.CanExecute(this, propertyName, context)) {
yield break;
}
var cascade = cascadeModeThunk();
bool hasAnyFailure = false;
// Invoke each validator and collect its results.
foreach (var validator in validators) {
var results = InvokePropertyValidator(context, validator, propertyName);
bool hasFailure = false;
foreach (var result in results) {
hasAnyFailure = true;
hasFailure = true;
yield return result;
}
// If there has been at least one failure, and our CascadeMode has been set to StopOnFirst
// then don't continue to the next rule
if (cascade == FluentValidation.CascadeMode.StopOnFirstFailure && hasFailure) {
break;
}
}
if (hasAnyFailure) {
// Callback if there has been at least one property validator failed.
OnFailure(context.InstanceToValidate);
}
else {
foreach (var dependentRule in DependentRules) {
foreach (var failure in dependentRule.Validate(context)) {
yield return failure;
}
}
}
}
/// <summary>
/// Performs asynchronous validation using a validation context and returns a collection of Validation Failures.
/// </summary>
/// <param name="context">Validation Context</param>
/// <param name="cancellation"></param>
/// <returns>A collection of validation failures</returns>
public Task<IEnumerable<ValidationFailure>> ValidateAsync(ValidationContext context, CancellationToken cancellation) {
try {
var displayName = GetDisplayName();
if (PropertyName == null && displayName == null)
{
//No name has been specified. Assume this is a model-level rule, so we should use empty string instead.
displayName = string.Empty;
}
// Construct the full name of the property, taking into account overriden property names and the chain (if we're in a nested validator)
var propertyName = context.PropertyChain.BuildPropertyName(PropertyName ?? displayName);
// Ensure that this rule is allowed to run.
// The validatselector has the opportunity to veto this before any of the validators execute.
if (!context.Selector.CanExecute(this, propertyName, context)) {
return TaskHelpers.FromResult(Enumerable.Empty<ValidationFailure>());
}
var cascade = cascadeModeThunk();
var failures = new List<ValidationFailure>();
var fastExit = false;
// Firstly, invoke all syncronous validators and collect their results.
foreach (var validator in validators.Where(v => !v.IsAsync)) {
if (cancellation.IsCancellationRequested) {
return TaskHelpers.Canceled<IEnumerable<ValidationFailure>>();
}
var results = InvokePropertyValidator(context, validator, propertyName);
failures.AddRange(results);
// If there has been at least one failure, and our CascadeMode has been set to StopOnFirst
// then don't continue to the next rule
if (fastExit = (cascade == CascadeMode.StopOnFirstFailure && failures.Count > 0)) {
break;
}
}
//if StopOnFirstFailure triggered then we exit
if (fastExit && failures.Count > 0) {
// Callback if there has been at least one property validator failed.
OnFailure(context.InstanceToValidate);
return TaskHelpers.FromResult(failures.AsEnumerable());
}
var asyncValidators = validators.Where(v => v.IsAsync).ToList();
// if there's no async validators then we exit
if (asyncValidators.Count == 0) {
if (failures.Count > 0) {
// Callback if there has been at least one property validator failed.
OnFailure(context.InstanceToValidate);
}
else
{
RunDependentRulesAsync(failures, context, cancellation);
}
return TaskHelpers.FromResult(failures.AsEnumerable());
}
//Then call asyncronous validators in non-blocking way
var validations =
asyncValidators
// .Select(v => v.ValidateAsync(new PropertyValidatorContext(context, this, propertyName), cancellation)
.Select(v => InvokePropertyValidatorAsync(context, v, propertyName, cancellation)
//this is thread safe because tasks are launched sequencially
.Then(fs => failures.AddRange(fs), runSynchronously: true)
);
return
TaskHelpers.Iterate(
validations,
breakCondition: _ => cascade == CascadeMode.StopOnFirstFailure && failures.Count > 0,
cancellationToken: cancellation
).Then(() => {
if (failures.Count > 0) {
OnFailure(context.InstanceToValidate);
}
else
{
RunDependentRulesAsync(failures, context, cancellation);
}
return failures.AsEnumerable();
},
runSynchronously: true
);
}
catch (Exception ex) {
return TaskHelpers.FromError<IEnumerable<ValidationFailure>>(ex);
}
}
private void RunDependentRulesAsync(List<ValidationFailure> failures, ValidationContext context, CancellationToken cancellation)
{
foreach (var dependentRule in DependentRules)
{
dependentRule.ValidateAsync(context, cancellation).Then(x => { failures.AddRange(x); }, cancellation, true);
}
}
/// <summary>
/// Invokes the validator asynchronously
/// </summary>
/// <param name="context"></param>
/// <param name="validator"></param>
/// <param name="propertyName"></param>
/// <param name="cancellation"></param>
/// <returns></returns>
protected virtual Task<IEnumerable<ValidationFailure>> InvokePropertyValidatorAsync(ValidationContext context, IPropertyValidator validator, string propertyName, CancellationToken cancellation) {
return validator.ValidateAsync(new PropertyValidatorContext(context, this, propertyName), cancellation);
}
/// <summary>
/// Invokes a property validator using the specified validation context.
/// </summary>
protected virtual IEnumerable<ValidationFailure> InvokePropertyValidator(ValidationContext context, IPropertyValidator validator, string propertyName) {
var propertyContext = new PropertyValidatorContext(context, this, propertyName);
return validator.Validate(propertyContext);
}
/// <summary>
/// Applies a condition to the rule
/// </summary>
/// <param name="predicate"></param>
/// <param name="applyConditionTo"></param>
public void ApplyCondition(Func<object, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) {
// Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain.
if (applyConditionTo == ApplyConditionTo.AllValidators) {
foreach (var validator in Validators.ToList()) {
var wrappedValidator = new DelegatingValidator(predicate, validator);
ReplaceValidator(validator, wrappedValidator);
}
foreach (var dependentRule in DependentRules.ToList()) {
dependentRule.ApplyCondition(predicate, applyConditionTo);
}
}
else {
var wrappedValidator = new DelegatingValidator(predicate, CurrentValidator);
ReplaceValidator(CurrentValidator, wrappedValidator);
}
}
/// <summary>
/// Applies the condition to the rule asynchronously
/// </summary>
/// <param name="predicate"></param>
/// <param name="applyConditionTo"></param>
public void ApplyAsyncCondition(Func<object, Task<bool>> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) {
// Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain.
if (applyConditionTo == ApplyConditionTo.AllValidators) {
foreach (var validator in Validators.ToList()) {
var wrappedValidator = new DelegatingValidator(predicate, validator);
ReplaceValidator(validator, wrappedValidator);
}
foreach (var dependentRule in DependentRules.ToList()) {
dependentRule.ApplyAsyncCondition(predicate, applyConditionTo);
}
}
else {
var wrappedValidator = new DelegatingValidator(predicate, CurrentValidator);
ReplaceValidator(CurrentValidator, wrappedValidator);
}
}
}
/// <summary>
/// Include rule
/// </summary>
public class IncludeRule : PropertyRule {
/// <summary>
/// Creates a new IncludeRule
/// </summary>
/// <param name="validator"></param>
/// <param name="cascadeModeThunk"></param>
/// <param name="typeToValidate"></param>
/// <param name="containerType"></param>
public IncludeRule(IValidator validator, Func<CascadeMode> cascadeModeThunk, Type typeToValidate, Type containerType) : base(null, x => x, null, cascadeModeThunk, typeToValidate, containerType) {
AddValidator(new ChildValidatorAdaptor(validator));
}
/// <summary>
/// Creates a new include rule from an existing validator
/// </summary>
/// <param name="validator"></param>
/// <param name="cascadeModeThunk"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IncludeRule Create<T>(IValidator validator, Func<CascadeMode> cascadeModeThunk) {
return new IncludeRule(validator, cascadeModeThunk, typeof(T), typeof(T));
}
}
}
| |
//
// SiteMembershipConditionTest.cs -
// NUnit Test Cases for SiteMembershipCondition
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// (C) 2004 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.Collections;
using System.Security;
using System.Security.Policy;
namespace MonoTests.System.Security.Policy {
[TestFixture]
public class SiteMembershipConditionTest {
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void SiteMembershipCondition_Null ()
{
SiteMembershipCondition smc = new SiteMembershipCondition (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void SiteMembershipCondition_Empty ()
{
SiteMembershipCondition smc = new SiteMembershipCondition (String.Empty);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void SiteMembershipCondition_FileUrl ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("file://mono/index.html");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void SiteMembershipCondition_FullUrlWithPort ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("http://www.go-mono.com:8080/index.html");
}
[Test]
public void SiteMembershipCondition_GoMonoWebSite ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("www.go-mono.com");
Assert.AreEqual ("www.go-mono.com", smc.Site, "Site");
Assert.AreEqual ("Site - www.go-mono.com", smc.ToString (), "ToString");
SiteMembershipCondition smc2 = (SiteMembershipCondition) smc.Copy ();
Assert.AreEqual (smc.Site, smc2.Site, "Copy.Site");
Assert.AreEqual (smc.GetHashCode (), smc2.GetHashCode (), "Copy.GetHashCode");
SecurityElement se = smc2.ToXml ();
SiteMembershipCondition smc3 = new SiteMembershipCondition ("*");
smc3.FromXml (se);
Assert.AreEqual (smc.Site, smc3.Site, "ToXml/FromXml");
Assert.IsTrue (smc.Equals (smc2), "Equals");
SiteMembershipCondition smc4 = new SiteMembershipCondition ("go-mono.com");
Assert.IsFalse (smc.Equals (smc4), "!Equals");
}
[Test]
public void Site_AllGoMonoSite ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("*.go-mono.com");
Assert.AreEqual ("*.go-mono.com", smc.Site, "Site");
Assert.AreEqual ("Site - *.go-mono.com", smc.ToString (), "ToString");
SiteMembershipCondition smc2 = (SiteMembershipCondition) smc.Copy ();
Assert.AreEqual (smc.Site, smc2.Site, "Copy.Site");
Assert.AreEqual (smc.GetHashCode (), smc2.GetHashCode (), "Copy.GetHashCode");
SecurityElement se = smc2.ToXml ();
SiteMembershipCondition smc3 = new SiteMembershipCondition ("*");
smc3.FromXml (se);
Assert.AreEqual (smc.Site, smc3.Site, "ToXml/FromXml");
Assert.IsTrue (smc.Equals (smc2), "Equals");
SiteMembershipCondition smc4 = new SiteMembershipCondition ("go-mono.com");
Assert.IsFalse (smc.Equals (smc4), "!Equals");
}
[Test]
public void Check ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("*.go-mono.com");
Evidence e = null;
Assert.IsFalse (smc.Check (e), "Check(null)");
e = new Evidence ();
Assert.IsFalse (smc.Check (e), "Check (empty)");
e.AddHost (new Zone (SecurityZone.MyComputer));
Assert.IsFalse (smc.Check (e), "Check (zone)");
Site s = new Site ("*.go-mono.com");
e.AddAssembly (s);
Assert.IsFalse (smc.Check (e), "Check (site-assembly)");
e.AddHost (s);
Assert.IsTrue (smc.Check (e), "Check (site-host)");
e = new Evidence ();
e.AddHost (new Site ("www.go-mono.com"));
Assert.IsTrue (smc.Check (e), "Check(+-)");
e = new Evidence ();
e.AddHost (new Site ("*.go-mono.org"));
Assert.IsFalse (smc.Check (e), "Check(-)");
}
[Test]
public void Equals ()
{
SiteMembershipCondition smc1 = new SiteMembershipCondition ("*.go-mono.com");
Assert.IsFalse (smc1.Equals (null), "Null");
SiteMembershipCondition smc2 = new SiteMembershipCondition ("*.Go-Mono.com");
Assert.IsTrue (smc1.Equals (smc2), "CaseSensitive");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void FromXml_Null ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("*.go-mono.com");
smc.FromXml (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromXml_InvalidTag ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("*.go-mono.com");
SecurityElement se = smc.ToXml ();
se.Tag = "IMonoship";
smc.FromXml (se);
}
[Test]
public void FromXml_InvalidClass ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("*.go-mono.com");
SecurityElement se = smc.ToXml ();
se.Attributes ["class"] = "Hello world";
smc.FromXml (se);
}
[Test]
public void FromXml_NoClass ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("*.go-mono.com");
SecurityElement se = smc.ToXml ();
SecurityElement w = new SecurityElement (se.Tag);
w.AddAttribute ("version", se.Attribute ("version"));
smc.FromXml (w);
// doesn't even care of the class attribute presence
}
[Test]
public void FromXml_InvalidVersion ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("*.go-mono.com");
SecurityElement se = smc.ToXml ();
se.Attributes ["version"] = "2";
smc.FromXml (se);
}
[Test]
public void FromXml_NoVersion ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("*.go-mono.com");
SecurityElement se = smc.ToXml ();
SecurityElement w = new SecurityElement (se.Tag);
w.AddAttribute ("class", se.Attribute ("class"));
smc.FromXml (w);
}
[Test]
public void FromXml_PolicyLevel ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("*.go-mono.com");
SecurityElement se = smc.ToXml ();
// is it accepted for all policy levels ?
IEnumerator e = SecurityManager.PolicyHierarchy ();
while (e.MoveNext ()) {
PolicyLevel pl = e.Current as PolicyLevel;
SiteMembershipCondition spl = new SiteMembershipCondition ("*");
spl.FromXml (se, pl);
Assert.IsTrue (spl.Equals (smc), "FromXml(PolicyLevel='" + pl.Label + "')");
}
// yes!
}
[Test]
public void ToXml_Null ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("*.go-mono.com");
// no ArgumentNullException here
SecurityElement se = smc.ToXml (null);
Assert.IsNotNull (se, "ToXml(null)");
}
[Test]
public void ToXml_PolicyLevel ()
{
SiteMembershipCondition smc = new SiteMembershipCondition ("*.go-mono.com");
SecurityElement se = smc.ToXml ();
string s = smc.ToXml ().ToString ();
// is it accepted for all policy levels ?
IEnumerator e = SecurityManager.PolicyHierarchy ();
while (e.MoveNext ()) {
PolicyLevel pl = e.Current as PolicyLevel;
SiteMembershipCondition spl = new SiteMembershipCondition ("*");
spl.FromXml (se, pl);
Assert.AreEqual (s, spl.ToXml (pl).ToString (), "ToXml(PolicyLevel='" + pl.Label + "')");
}
// yes!
}
[Test]
public void ToFromXmlRoundTrip ()
{
SiteMembershipCondition smc1 = new SiteMembershipCondition ("*.go-mono.com");
SecurityElement se = smc1.ToXml ();
SiteMembershipCondition smc2 = new SiteMembershipCondition ("*");
smc2.FromXml (se);
Assert.AreEqual (smc1.GetHashCode (), smc2.GetHashCode (), "ToFromXmlRoundTrip");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using Csla;
using Csla.Validation;
using CslaSrd.Properties;
using System.Text.RegularExpressions;
using System.Reflection;
namespace CslaSrd.Validation
{
/// <summary>
/// Implements common business rules.
/// </summary>
public static class StdRules
{
#region AOrBValue
/// <summary>
/// Implements a rule that only allows one field out of the specified set of fields to have a non-null value.
/// Example: A gentleman can record his girlfriend's name, or his wife's name, but not both.
/// </summary>
/// <param name="target"></param>
/// <param name="e"></param>
/// <returns></returns>
public static bool AOrBValue(object target, RuleArgs e)
{
AOrBValueRuleArgs ee = (AOrBValueRuleArgs)e;
int nonBlankCount = 0;
for (int i = 0; i < ee.PropertyList.Count; i++)
{
// Get object type of property.
// Check the value assigned to each property in a manner appropriate to its object type, and count
// how many have a non-blank value.
Object o = Utilities.CallByName(target, ee.PropertyList[i].ToString(), CallType.Get);
Type t = o.GetType();
// string
if (t.FullName == "System.String")
{
String s = (String)o;
if (!(s == null
|| s == String.Empty
)
)
{
nonBlankCount++;
}
}
// char
else if (t.FullName == "System.Char")
{
Char c = (Char)o;
if (!(c == ' '
)
)
{
nonBlankCount++;
}
}
// SmartDate
else if (t.FullName == "Csla.SmartDate")
{
SmartDate d = (SmartDate)o;
if (!(d == null
|| d.IsEmpty
)
)
{
nonBlankCount++;
}
}
// SmartField
else if (t.FullName == "CslaSrd.SmartInt16"
|| t.FullName == "CslaSrd.SmartInt32"
|| t.FullName == "CslaSrd.SmartInt64"
|| t.FullName == "CslaSrd.SmartFloat"
|| t.FullName == "CslaSrd.SmartDecimal"
|| t.FullName == "CslaSrd.SmartBool"
)
{
ISmartField f = (ISmartField)o;
if (!(f == null
|| f.HasNullValue()
)
)
{
nonBlankCount++;
}
}
// other - error.
else
{
}
}
if (nonBlankCount > 1)
{
String csvPropertyList = String.Empty;
for (int i = 0; i < ee.PropertyList.Count; i++)
{
csvPropertyList += "," + ee.PropertyList[i].ToString();
}
if (csvPropertyList.Length > 0)
{
csvPropertyList = csvPropertyList.Substring(1);
}
ee.Description = Resources.ruleAOrBValue.Replace("{propertyList}", csvPropertyList);
return false;
}
else
{
return true;
}
}
/// <summary>
/// Custom <see cref="RuleArgs" /> object required by the
/// <see cref="AOrB" /> rule method.
/// </summary>
public class AOrBValueRuleArgs : RuleArgs
{
private ArrayList _propertyList = new ArrayList();
/// <summary>
/// Get the names of the properties that are mutually exclusive with this one.
/// </summary>
public ArrayList PropertyList
{
get { return _propertyList; }
}
/// <summary>
/// Create a new custom rule arguments object.
/// </summary>
/// <param name="propertyName">The name of the property the rule is attached to.</param>
/// <param name="propertyList">A list of other properties affected by the rule.</param>
public AOrBValueRuleArgs(
string propertyName, ArrayList propertyList)
: base(propertyName)
{
_propertyList = propertyList;
}
/// <summary>
/// Return a string representation of the object.
/// </summary>
public override string ToString()
{
String csvPropertyList = String.Empty;
for (int i = 0; i < _propertyList.Count; i++)
{
csvPropertyList += "," + _propertyList[i].ToString();
}
if (csvPropertyList.Length > 0)
{
csvPropertyList = csvPropertyList.Substring(1);
}
return base.ToString() + "?propertyList=" + csvPropertyList;
}
}
#endregion
#region BIfAValue
/// <summary>
/// Implements a rule that only allows field B to have a value if the field A has one.
/// Example: Address Line 2 cannot be filled in unless Address Line 1 is filled in.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="target"></param>
/// <param name="e"></param>
/// <returns></returns>
//public static bool BIfAValue<T>(object target, RuleArgs e)
//{@TODO
//}
#endregion
#region AAndBValue
/// <summary>
/// Implements a rule that requires all specified fields to have a non-null value if any one of them does.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="target"></param>
/// <param name="e"></param>
/// <returns></returns>
//public static bool AAndBValue<T>(object target, RuleArgs e)
//{@TODO
//}
#endregion
#region SmartFieldRequired
/// <summary>
/// Rule ensuring a Smart... class value contains a non-null value.
/// </summary>
/// <param name="target">Object containing the data to validate</param>
/// <param name="e">Arguments parameter specifying the name of the SmartField
/// property to validate</param>
/// <returns><see langword="false" /> if the rule is broken</returns>
/// <remarks>
/// This implementation uses late binding, and will only work
/// against Smart... class property values. This will not work on the SmartDate class, as it
/// does not implement the ISmartField interface.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public static bool SmartFieldRequired(object target, RuleArgs e)
{
ISmartField value = (ISmartField)Utilities.CallByName(target, e.PropertyName, CallType.Get);
if (value.HasNullValue() == true)
{
e.Description = Resources.ruleSmartFieldRequired.Replace("{rulePropertyName}", e.PropertyName);
return false;
}
return true;
}
#endregion
#region SmartDateRequired
/// <summary>
/// Rule ensuring a SmartDate class value contains a non-null value.
/// </summary>
/// <param name="target">Object containing the data to validate</param>
/// <param name="e">Arguments parameter specifying the name of the SmartField
/// property to validate</param>
/// <returns><see langword="false" /> if the rule is broken</returns>
/// <remarks>
/// This implementation uses late binding, and will only work
/// against SmartDate class property values.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public static bool SmartDateRequired(object target, RuleArgs e)
{
SmartDate value = (SmartDate)Utilities.CallByName(target, e.PropertyName, CallType.Get);
if (value.IsEmpty == true)
{
e.Description = Resources.ruleSmartDateRequired.Replace("{rulePropertyName}", e.PropertyName);
return false;
}
return true;
}
#endregion
#region MinMax
/// <summary>
/// The first field must not be greater than the second field. Example: StartDate must not be greater than EndDate.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="target"></param>
/// <param name="e"></param>
/// <returns></returns>
public static bool MinMax<T>(object target, RuleArgs e) where T : IComparable
{
MinMaxRuleArgs ee = (MinMaxRuleArgs)e;
T minValue = (T)Utilities.CallByName(target, ee.MinPropertyName, CallType.Get);
T maxValue = (T)Utilities.CallByName(target, ee.MaxPropertyName, CallType.Get);
if (minValue.CompareTo(maxValue) == 1)
{
try
{
ee.Description = Resources.ruleMinMax.Replace("{rulePropertyName}", ee.PropertyName);
ee.Description = ee.Description.Replace("{minPropertyName}", ee.MinPropertyName);
ee.Description = ee.Description.Replace("{maxPropertyName}", ee.MaxPropertyName);
}
catch
{
ee.Description = Resources.ruleMinMax.ToString();
}
return false;
}
else
{
return true;
}
}
/// <summary>
/// Custom <see cref="RuleArgs" /> object required by the
/// <see cref="MinMax" /> rule method.
/// </summary>
public class MinMaxRuleArgs : RuleArgs
{
private string _minPropertyName;
private string _maxPropertyName;
/// <summary>
/// Get the name of the property that holds the min value.
/// </summary>
public string MinPropertyName
{
get { return _minPropertyName; }
}
/// <summary>
/// Get the name of the property that holds the max value.
/// </summary>
public string MaxPropertyName
{
get { return _maxPropertyName; }
}
/// <summary>
/// Create a new object.
/// </summary>
/// <param name="propertyName">Name of the property to validate.</param>
/// <param name="minPropertyName">Name of property containing min value to be checked.</param>
/// <param name="maxPropertyName">Name of property containing max value to be checked.</param>
public MinMaxRuleArgs(
string propertyName, string minPropertyName, string maxPropertyName)
: base(propertyName)
{
_minPropertyName = minPropertyName;
_maxPropertyName = maxPropertyName;
}
/// <summary>
/// Return a string representation of the object.
/// </summary>
public override string ToString()
{
return base.ToString() + "?minPropertyName=" + _minPropertyName + "&maxPropertyName=" + _maxPropertyName;
}
}
#endregion
#region StringRequired
/// <summary>
/// Rule ensuring a string value contains one or more
/// characters.
/// </summary>
/// <param name="target">Object containing the data to validate</param>
/// <param name="e">Arguments parameter specifying the name of the string
/// property to validate</param>
/// <returns><see langword="false" /> if the rule is broken</returns>
/// <remarks>
/// This implementation uses late binding, and will only work
/// against string property values.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public static bool StringRequired(object target, RuleArgs e)
{
string value = (string)Utilities.CallByName(
target, e.PropertyName, CallType.Get);
if (string.IsNullOrEmpty(value))
{
e.Description = Resources.ruleStringRequired.Replace("{rulePropertyName}", e.PropertyName);
return false;
}
return true;
}
#endregion
#region StringMaxLength
/// <summary>
/// Rule ensuring a string value doesn't exceed
/// a specified length.
/// </summary>
/// <param name="target">Object containing the data to validate</param>
/// <param name="e">Arguments parameter specifying the name of the string
/// property to validate</param>
/// <returns><see langword="false" /> if the rule is broken</returns>
/// <remarks>
/// This implementation uses late binding, and will only work
/// against string property values.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public static bool StringMaxLength(
object target, RuleArgs e)
{
int max = ((MaxLengthRuleArgs)e).MaxLength;
string value = (string)Utilities.CallByName(
target, e.PropertyName, CallType.Get);
if (!String.IsNullOrEmpty(value) && (value.Length > max))
{
e.Description = Resources.ruleStringMaxLength.Replace("{rulePropertyName}", e.PropertyName);
return false;
}
return true;
}
/// <summary>
/// Custom <see cref="RuleArgs" /> object required by the
/// <see cref="StringMaxLength" /> rule method.
/// </summary>
public class MaxLengthRuleArgs : RuleArgs
{
private int _maxLength;
/// <summary>
/// Get the max length for the string.
/// </summary>
public int MaxLength
{
get { return _maxLength; }
}
/// <summary>
/// Create a new object.
/// </summary>
/// <param name="propertyName">Name of the property to validate.</param>
/// <param name="maxLength">Max length of characters allowed.</param>
public MaxLengthRuleArgs(
string propertyName, int maxLength)
: base(propertyName)
{
_maxLength = maxLength;
}
/// <summary>
/// Return a string representation of the object.
/// </summary>
public override string ToString()
{
return base.ToString() + "?maxLength=" + _maxLength.ToString();
}
}
#endregion
#region IntegerMaxValue
/// <summary>
/// Rule ensuring an integer value doesn't exceed
/// a specified value.
/// </summary>
/// <param name="target">Object containing the data to validate.</param>
/// <param name="e">Arguments parameter specifying the name of the
/// property to validate.</param>
/// <returns><see langword="false"/> if the rule is broken.</returns>
public static bool IntegerMaxValue(object target, RuleArgs e)
{
int max = ((IntegerMaxValueRuleArgs)e).MaxValue;
int value = (int)Utilities.CallByName(target, e.PropertyName, CallType.Get);
if (value > max)
{
e.Description = Resources.ruleIntegerMaxValue.Replace("{rulePropertyName}", e.PropertyName);
return false;
}
return true;
}
/// <summary>
/// Custom <see cref="RuleArgs" /> object required by the
/// <see cref="IntegerMaxValue" /> rule method.
/// </summary>
public class IntegerMaxValueRuleArgs : RuleArgs
{
private int _maxValue;
/// <summary>
/// Get the max value for the property.
/// </summary>
public int MaxValue
{
get { return _maxValue; }
}
/// <summary>
/// Create a new object.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="maxValue">Maximum allowed value for the property.</param>
public IntegerMaxValueRuleArgs(string propertyName, int maxValue)
: base(propertyName)
{
_maxValue = maxValue;
}
/// <summary>
/// Return a string representation of the object.
/// </summary>
public override string ToString()
{
return base.ToString() + "?maxValue=" + _maxValue.ToString();
}
}
#endregion
#region IntegerMinValue
/// <summary>
/// Rule ensuring an integer value doesn't go below
/// a specified value.
/// </summary>
/// <param name="target">Object containing the data to validate.</param>
/// <param name="e">Arguments parameter specifying the name of the
/// property to validate.</param>
/// <returns><see langword="false"/> if the rule is broken.</returns>
public static bool IntegerMinValue(object target, RuleArgs e)
{
int min = ((IntegerMinValueRuleArgs)e).MinValue;
int value = (int)Utilities.CallByName(target, e.PropertyName, CallType.Get);
if (value < min)
{
e.Description = Resources.ruleMinMax.Replace("{rulePropertyName}", e.PropertyName);
return false;
}
return true;
}
/// <summary>
/// Custom <see cref="RuleArgs" /> object required by the
/// <see cref="IntegerMinValue" /> rule method.
/// </summary>
public class IntegerMinValueRuleArgs : RuleArgs
{
private int _minValue;
/// <summary>
/// Get the min value for the property.
/// </summary>
public int MinValue
{
get { return _minValue; }
}
/// <summary>
/// Create a new object.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="minValue">Minimum allowed value for the property.</param>
public IntegerMinValueRuleArgs(string propertyName, int minValue)
: base(propertyName)
{
_minValue = minValue;
}
/// <summary>
/// Return a string representation of the object.
/// </summary>
public override string ToString()
{
return base.ToString() + "?minValue=" + _minValue.ToString();
}
}
#endregion
#region MaxValue
/// <summary>
/// Rule ensuring that a numeric value
/// doesn't exceed a specified maximum.
/// </summary>
/// <typeparam name="T">Type of the property to validate.</typeparam>
/// <param name="target">Object containing value to validate.</param>
/// <param name="e">Arguments variable specifying the
/// name of the property to validate, along with the max
/// allowed value.</param>
public static bool MaxValue<T>(object target, RuleArgs e) where T : IComparable
{
PropertyInfo pi = target.GetType().GetProperty(e.PropertyName);
T value = (T)pi.GetValue(target, null);
T max = ((MaxValueRuleArgs<T>)e).MaxValue;
int result = value.CompareTo(max);
if (result >= 1)
{
e.Description = Resources.ruleMaxValue.Replace("{rulePropertyName}", e.PropertyName);
return false;
}
else
return true;
}
/// <summary>
/// Custom <see cref="RuleArgs" /> object required by the
/// <see cref="MaxValue" /> rule method.
/// </summary>
/// <typeparam name="T">Type of the property to validate.</typeparam>
public class MaxValueRuleArgs<T> : RuleArgs
{
T _maxValue = default(T);
/// <summary>
/// Get the max value for the property.
/// </summary>
public T MaxValue
{
get { return _maxValue; }
}
/// <summary>
/// Create a new object.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="maxValue">Maximum allowed value for the property.</param>
public MaxValueRuleArgs(string propertyName, T maxValue)
: base(propertyName)
{
_maxValue = maxValue;
}
/// <summary>
/// Returns a string representation of the object.
/// </summary>
public override string ToString()
{
return base.ToString() + "?maxValue=" + _maxValue.ToString();
}
}
#endregion
#region MinValue
/// <summary>
/// Rule ensuring that a numeric value
/// doesn't exceed a specified minimum.
/// </summary>
/// <typeparam name="T">Type of the property to validate.</typeparam>
/// <param name="target">Object containing value to validate.</param>
/// <param name="e">Arguments variable specifying the
/// name of the property to validate, along with the min
/// allowed value.</param>
public static bool MinValue<T>(object target, RuleArgs e) where T : IComparable
{
PropertyInfo pi = target.GetType().GetProperty(e.PropertyName);
T value = (T)pi.GetValue(target, null);
T min = ((MinValueRuleArgs<T>)e).MinValue;
int result = value.CompareTo(min);
if (result <= -1)
{
e.Description = Resources.ruleMinValue.Replace("{rulePropertyName}", e.PropertyName);
return false;
}
else
return true;
}
/// <summary>
/// Custom <see cref="RuleArgs" /> object required by the
/// <see cref="MinValue" /> rule method.
/// </summary>
/// <typeparam name="T">Type of the property to validate.</typeparam>
public class MinValueRuleArgs<T> : RuleArgs
{
T _minValue = default(T);
/// <summary>
/// Get the min value for the property.
/// </summary>
public T MinValue
{
get { return _minValue; }
}
/// <summary>
/// Create a new object.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="minValue">Minimum allowed value for the property.</param>
public MinValueRuleArgs(string propertyName, T minValue)
: base(propertyName)
{
_minValue = minValue;
}
/// <summary>
/// Returns a string representation of the object.
/// </summary>
public override string ToString()
{
return base.ToString() + "?minValue=" + _minValue.ToString();
}
}
#endregion
#region RegExMatch
/// <summary>
/// Rule that checks to make sure a value
/// matches a given regex pattern.
/// </summary>
/// <param name="target">Object containing the data to validate</param>
/// <param name="e">RegExRuleArgs parameter specifying the name of the
/// property to validate and the regex pattern.</param>
/// <returns>False if the rule is broken</returns>
/// <remarks>
/// This implementation uses late binding.
/// </remarks>
public static bool RegExMatch(object target, RuleArgs e)
{
Regex rx = ((RegExMatchRuleArgs)e).RegEx;
if (!rx.IsMatch(Utilities.CallByName(target, e.PropertyName, CallType.Get).ToString()))
{
e.Description = Resources.ruleRegExMatch.Replace("{rulePropertyName}", e.PropertyName);
return false;
}
else
return true;
}
/// <summary>
/// List of built-in regex patterns.
/// </summary>
public enum RegExPatterns
{
/// <summary>
/// US Social Security number pattern.
/// </summary>
SSN,
/// <summary>
/// Email address pattern.
/// </summary>
Email
}
/// <summary>
/// Custom <see cref="RuleArgs" /> object required by the
/// <see cref="RegExMatch" /> rule method.
/// </summary>
public class RegExMatchRuleArgs : RuleArgs
{
Regex _regEx;
/// <summary>
/// The <see cref="RegEx"/> object used to validate
/// the property.
/// </summary>
public Regex RegEx
{
get { return _regEx; }
}
/// <summary>
/// Creates a new object.
/// </summary>
/// <param name="propertyName">Name of the property to validate.</param>
/// <param name="pattern">Built-in regex pattern to use.</param>
public RegExMatchRuleArgs(string propertyName, RegExPatterns pattern)
:
base(propertyName)
{
_regEx = new Regex(GetPattern(pattern));
}
/// <summary>
/// Creates a new object.
/// </summary>
/// <param name="propertyName">Name of the property to validate.</param>
/// <param name="pattern">Custom regex pattern to use.</param>
public RegExMatchRuleArgs(string propertyName, string pattern)
:
base(propertyName)
{
_regEx = new Regex(pattern);
}
/// <summary>
/// Creates a new object.
/// </summary>
/// <param name="propertyName">Name of the property to validate.</param>
/// <param name="regEx"><see cref="RegEx"/> object to use.</param>
public RegExMatchRuleArgs(string propertyName, System.Text.RegularExpressions.Regex regEx)
:
base(propertyName)
{
_regEx = regEx;
}
/// <summary>f
/// Returns a string representation of the object.
/// </summary>
public override string ToString()
{
return base.ToString() + "?regex=" + _regEx.ToString();
}
/// <summary>
/// Returns the specified built-in regex pattern.
/// </summary>
/// <param name="pattern">Pattern to return.</param>
public static string GetPattern(RegExPatterns pattern)
{
switch (pattern)
{
case RegExPatterns.SSN:
return @"^\d{3}-\d{2}-\d{4}$";
case RegExPatterns.Email:
return @"^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$";
default:
return string.Empty;
}
}
}
#endregion
//#region IsEmailAddress
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
//public static bool IsEmailAddress(object target, RuleArgs e)
//{@TODO
// string addressToBeChecked = Utilities.CallByName(target, e.PropertyName, CallType.Get).ToString();
// string currentCharacter = string.Empty;
// int stringLength = addressToBeChecked.Length;
// int currentStringPosition = 0;
// int errorMessageLength = 0;
// int atSignCount = 0;
// bool hasPeriodAfterAtSign = false;
// bool hasNoForbiddenCharacters = true;
// Regex allowableCharacters = new Regex(@"[a-zA-z0-9!#$%&'*+-/=?^_`{|}~]");
// e.Description = "";
// if (stringLength > 0)
// {
// while (currentStringPosition < stringLength)
// {
// currentCharacter = addressToBeChecked.Substring(currentStringPosition, 1);
// System.Console.WriteLine("Current Character = " + currentCharacter);
// if (!allowableCharacters.IsMatch(currentCharacter) | currentCharacter == ".")
// {
// if (currentCharacter == "@")
// {
// atSignCount++;
// if (currentStringPosition == 0)
// {
// e.Description = e.Description + Resources.ruleIsEmailAddressStartAtSign + "\n";
// hasNoForbiddenCharacters = false;
// }
// if (currentStringPosition == stringLength - 1)
// {
// e.Description = e.Description + Resources.ruleIsEmailAddressEndAtSign + "\n";
// hasNoForbiddenCharacters = false;
// }
// if (atSignCount > 1)
// {
// e.Description = e.Description + Resources.ruleIsEmailAddressTwoAtSigns;
// hasNoForbiddenCharacters = false;
// }
// if (currentStringPosition > 0 && currentStringPosition < stringLength)
// {
// if (addressToBeChecked.Substring(currentStringPosition - 1, 1) == "."
// || addressToBeChecked.Substring(currentStringPosition + 1, 1) == "."
// )
// {
// e.Description = e.Description + Resources.ruleIsEmailAddressPeriodNextToAtSign + "\n";
// hasNoForbiddenCharacters = false;
// }
// }
// }
// else
// {
// if (currentCharacter == ".")
// {
// if (currentStringPosition == 0)
// {
// e.Description = e.Description + Resources.ruleIsEmailAddressStartPeriod + "\n";
// hasNoForbiddenCharacters = false;
// }
// if (currentStringPosition == stringLength - 1)
// {
// e.Description = e.Description + Resources.ruleIsEmailAddressEndPeriod + "\n";
// hasNoForbiddenCharacters = false;
// }
// if (currentStringPosition > 0 && currentStringPosition < stringLength)
// {
// if (addressToBeChecked.Substring(currentStringPosition - 1, 1) == "@"
// || addressToBeChecked.Substring(currentStringPosition + 1, 1) == "@"
// )
// {
// e.Description = e.Description + Resources.ruleIsEmailAddressPeriodNextToAtSign + "\n";
// hasNoForbiddenCharacters = false;
// }
// if (addressToBeChecked.Substring(currentStringPosition - 1, 1) == "."
// || addressToBeChecked.Substring(currentStringPosition + 1, 1) == "."
// )
// {
// e.Description = e.Description + Resources.ruleIsEmailAddressAdjacentPeriods + "\n";
// hasNoForbiddenCharacters = false;
// }
// }
// if (atSignCount > 0)
// {
// hasPeriodAfterAtSign = true;
// }
// }
// else
// {
// e.Description = e.Description + Resources.ruleIsEmailAddressForbiddenCharacter.Replace("{invalidCharacter}", currentCharacter) + "\n";
// hasNoForbiddenCharacters = false;
// }
// }
// }
// currentStringPosition++;
// }
// if (hasPeriodAfterAtSign == false)
// {
// e.Description = e.Description + Resources.ruleIsEmailAddressNoPeriodAfterAtSign + "\n";
// hasNoForbiddenCharacters = false;
// }
// if (atSignCount == 0)
// {
// e.Description = e.Description + Resources.ruleIsEmailAddressNoAtSign + "\n";
// hasNoForbiddenCharacters = false;
// }
// if (hasNoForbiddenCharacters == false)
// {
// e.Description = Resources.ruleIsEmailAddress.Replace("{rulePropertyName}",e.PropertyName) + "\n" + e.Description;
// errorMessageLength = e.Description.Length;
// e.Description = e.Description.Substring(0, errorMessageLength - 1);
// }
// }
// return hasNoForbiddenCharacters;
//}
//public class IsEmailAddressRuleArgs : RuleArgs
//{
// string _addressToBeChecked;
// public string AddressToBeChecked
// {
// get { return _addressToBeChecked; }
// }
//}
//#endregion
}
}
| |
// MIT License
//
// Copyright(c) 2022 ICARUS Consulting GmbH
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using Yaapii.Atoms.Enumerable;
using Yaapii.Atoms.Map;
namespace Yaapii.Atoms.Func
{
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public sealed class ActionSwitch<In> : IAction<string, In>
{
private readonly MapOf<Action<In>> map;
private readonly Action<string, In> fallback;
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(params IKvp<Action<In>>[] consequences) : this(
new ManyOf<IKvp<Action<In>>>(consequences)
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2
),
(unknown, input) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
IKvp<Action<In>> consequence3
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2,
consequence3
),
(unknown, input) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
IKvp<Action<In>> consequence3,
IKvp<Action<In>> consequence4
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2,
consequence3,
consequence4
),
(unknown, input) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
IKvp<Action<In>> consequence3,
IKvp<Action<In>> consequence4,
IKvp<Action<In>> consequence5
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5
),
(unknown, input) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
IKvp<Action<In>> consequence3,
IKvp<Action<In>> consequence4,
IKvp<Action<In>> consequence5,
IKvp<Action<In>> consequence6
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6
),
(unknown, input) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
IKvp<Action<In>> consequence3,
IKvp<Action<In>> consequence4,
IKvp<Action<In>> consequence5,
IKvp<Action<In>> consequence6,
IKvp<Action<In>> consequence7
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
consequence7
),
(unknown, input) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
IKvp<Action<In>> consequence3,
IKvp<Action<In>> consequence4,
IKvp<Action<In>> consequence5,
IKvp<Action<In>> consequence6,
IKvp<Action<In>> consequence7,
IKvp<Action<In>> consequence8
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
consequence7,
consequence8
),
(unknown, input) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
Action<string, In> fallback
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
IKvp<Action<In>> consequence3,
Action<string, In> fallback
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2,
consequence3
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
IKvp<Action<In>> consequence3,
IKvp<Action<In>> consequence4,
Action<string, In> fallback
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2,
consequence3,
consequence4
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
IKvp<Action<In>> consequence3,
IKvp<Action<In>> consequence4,
IKvp<Action<In>> consequence5,
Action<string, In> fallback
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
IKvp<Action<In>> consequence3,
IKvp<Action<In>> consequence4,
IKvp<Action<In>> consequence5,
IKvp<Action<In>> consequence6,
Action<string, In> fallback
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
IKvp<Action<In>> consequence3,
IKvp<Action<In>> consequence4,
IKvp<Action<In>> consequence5,
IKvp<Action<In>> consequence6,
IKvp<Action<In>> consequence7,
Action<string, In> fallback
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
consequence7
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In>> consequence1,
IKvp<Action<In>> consequence2,
IKvp<Action<In>> consequence3,
IKvp<Action<In>> consequence4,
IKvp<Action<In>> consequence5,
IKvp<Action<In>> consequence6,
IKvp<Action<In>> consequence7,
IKvp<Action<In>> consequence8,
Action<string, In> fallback
) : this(
new ManyOf<IKvp<Action<In>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
consequence7,
consequence8
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(IEnumerable<IKvp<Action<In>>> consequences) : this(
consequences,
(unknown, input) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(IEnumerable<IKvp<Action<In>>> consequences, Action<string, In> fallback)
{
this.map = new MapOf<Action<In>>(consequences);
this.fallback = fallback;
}
public void Invoke(string condition, In input)
{
if (!this.map.ContainsKey(condition))
{
this.fallback(condition, input);
}
else
{
this.map[condition].Invoke(input);
}
}
}
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public sealed class ActionSwitch<In1, In2> : IAction<string, In1, In2>
{
private readonly MapOf<Action<In1, In2>> map;
private readonly Action<string, In1, In2> fallback;
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2
),
(unknown, input1, input2) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2,
consequence3
),
(unknown, input1, input2) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2,
consequence3,
consequence4
),
(unknown, input1, input2) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5
),
(unknown, input1, input2) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
IKvp<Action<In1, In2>> consequence6
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6
),
(unknown, input1, input2) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
IKvp<Action<In1, In2>> consequence6,
IKvp<Action<In1, In2>> consequence7
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
consequence7
),
(unknown, input1, input2) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
IKvp<Action<In1, In2>> consequence6,
IKvp<Action<In1, In2>> consequence7,
IKvp<Action<In1, In2>> consequence8
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
consequence7,
consequence8
),
(unknown, input1, input2) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
Action<string, In1, In2> fallback
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
Action<string, In1, In2> fallback
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2,
consequence3
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
Action<string, In1, In2> fallback
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2,
consequence3,
consequence4
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
Action<string, In1, In2> fallback
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
IKvp<Action<In1, In2>> consequence6,
Action<string, In1, In2> fallback
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
IKvp<Action<In1, In2>> consequence6,
IKvp<Action<In1, In2>> consequence7,
Action<string, In1, In2> fallback
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
consequence7
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
IKvp<Action<In1, In2>> consequence6,
IKvp<Action<In1, In2>> consequence7,
IKvp<Action<In1, In2>> consequence8,
Action<string, In1, In2> fallback
) : this(
new ManyOf<IKvp<Action<In1, In2>>>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
consequence7,
consequence8
),
fallback
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(params IKvp<Action<In1, In2>>[] consequences) : this(
new ManyOf<IKvp<Action<In1, In2>>>(consequences)
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(IEnumerable<IKvp<Action<In1, In2>>> consequences) : this(
consequences,
(unknown, input1, input2) => throw new ArgumentException($"Cannot find action for '{unknown}'")
)
{ }
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public ActionSwitch(IEnumerable<IKvp<Action<In1, In2>>> consequences, Action<string, In1, In2> fallback)
{
this.map = new MapOf<Action<In1, In2>>(consequences);
this.fallback = fallback;
}
public void Invoke(string condition, In1 input1, In2 input2)
{
if (!this.map.ContainsKey(condition))
{
this.fallback(condition, input1, input2);
}
else
{
this.map[condition].Invoke(input1, input2);
}
}
}
public static class ActionSwitch
{
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2,
consequence3
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2,
consequence3,
consequence4
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
IKvp<Action<In1, In2>> consequence6
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
IKvp<Action<In1, In2>> consequence6,
IKvp<Action<In1, In2>> consequence7
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
consequence7
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
IKvp<Action<In1, In2>> consequence6,
IKvp<Action<In1, In2>> consequence7,
IKvp<Action<In1, In2>> consequence8
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
consequence7,
consequence8
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
Action<string, In1, In2> fallback
) => new ActionSwitch<In1, In2>(consequence1, consequence2, fallback);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
Action<string, In1, In2> fallback
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2,
consequence3,
fallback
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
Action<string, In1, In2> fallback
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2,
consequence3,
fallback
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
Action<string, In1, In2> fallback
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
fallback
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
IKvp<Action<In1, In2>> consequence6,
Action<string, In1, In2> fallback
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
fallback
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
IKvp<Action<In1, In2>> consequence6,
IKvp<Action<In1, In2>> consequence7,
Action<string, In1, In2> fallback
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
consequence7,
fallback
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(
IKvp<Action<In1, In2>> consequence1,
IKvp<Action<In1, In2>> consequence2,
IKvp<Action<In1, In2>> consequence3,
IKvp<Action<In1, In2>> consequence4,
IKvp<Action<In1, In2>> consequence5,
IKvp<Action<In1, In2>> consequence6,
IKvp<Action<In1, In2>> consequence7,
IKvp<Action<In1, In2>> consequence8,
Action<string, In1, In2> fallback
) => new ActionSwitch<In1, In2>(
consequence1,
consequence2,
consequence3,
consequence4,
consequence5,
consequence6,
consequence7,
consequence8,
fallback
);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(params IKvp<Action<In1, In2>>[] consequences) =>
new ActionSwitch<In1, In2>(consequences);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(IEnumerable<IKvp<Action<In1, In2>>> consequences) =>
new ActionSwitch<In1, In2>(consequences);
/// <summary>
/// An action fork that is dependant on a named condition.
/// </summary>
public static IAction<string, In1, In2> New<In1, In2>(IEnumerable<IKvp<Action<In1, In2>>> consequences, Action<string, In1, In2> fallback) =>
new ActionSwitch<In1, In2>(consequences);
}
}
| |
// <copyright file="UserControlUnitTests.cs" company="DevAge, Vestris Inc. & Contributors">
// Copyright (c) DevAge, Vestris Inc. & Contributors.
// </copyright>
namespace dotNetInstallerUnitTests
{
using System;
using System.IO;
using dotNetUnitTestsRunner;
using InstallerLib;
using NUnit.Framework;
[TestFixture]
public class UserControlUnitTests
{
[Test]
public void TestUserControlCheckbox()
{
Console.WriteLine("TestUserControlCheckbox");
// a configuration with a checkbox control
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
// a checkbox that changes the return value
ControlCheckBox checkbox = new ControlCheckBox();
checkbox.UncheckedValue = "3";
checkbox.CheckedValue = "4";
checkbox.Checked = true;
checkbox.Id = "checkbox1";
setupConfiguration.Children.Add(checkbox);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [checkbox1]";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
Assert.AreEqual(4, dotNetInstallerExeUtils.Run(configFilename));
checkbox.Checked = false;
configFile.SaveAs(configFilename);
Assert.AreEqual(3, dotNetInstallerExeUtils.Run(configFilename));
checkbox.Checked = true;
checkbox.CheckedValue = "0";
configFile.SaveAs(configFilename);
Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlCheckboxInstallCheck()
{
Console.WriteLine("TestUserControlCheckboxInstallCheck");
// a configuration with a checkbox control which has an installed check that disables it
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
// a checkbox that changes are return value
ControlCheckBox checkbox = new ControlCheckBox();
checkbox.UncheckedValue = "3";
checkbox.CheckedValue = "4";
checkbox.Checked = true;
checkbox.Id = "checkbox1";
setupConfiguration.Children.Add(checkbox);
// an installed check that is always false
InstalledCheckRegistry check = new InstalledCheckRegistry();
check.path = @"SOFTWARE\KeyDoesntExist";
check.comparison = installcheckregistry_comparison.exists;
checkbox.Children.Add(check);
// command that depends on the value of checkbox1
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [checkbox1]5";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller, this checkbox is disabled, so all runs ignore checkbox1 value
Assert.AreEqual(5, dotNetInstallerExeUtils.Run(configFilename));
checkbox.Checked = false;
configFile.SaveAs(configFilename);
Assert.AreEqual(5, dotNetInstallerExeUtils.Run(configFilename));
checkbox.Checked = true;
checkbox.CheckedValue = "0";
configFile.SaveAs(configFilename);
Assert.AreEqual(5, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlEdit()
{
Console.WriteLine("TestUserControlEdit");
// a configuration with a checkbox control
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlEdit edit = new ControlEdit();
edit.Text = "4";
edit.Id = "edit1";
setupConfiguration.Children.Add(edit);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [edit1]";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
Assert.AreEqual(4, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlEditInstalledCheckBoth()
{
Console.WriteLine("TestUserControlEditInstalledCheckBoth");
// a configuration with a checkbox control
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlEdit edit = new ControlEdit();
edit.Text = "4";
edit.Id = "edit1";
edit.Check = ControlCheckType.both;
setupConfiguration.Children.Add(edit);
// an installed check that is always false
InstalledCheckRegistry check = new InstalledCheckRegistry();
check.path = @"SOFTWARE\KeyDoesntExist";
check.comparison = installcheckregistry_comparison.exists;
edit.Children.Add(check);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [edit1]5";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
Assert.AreEqual(5, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlEditInstalledCheckHasValueDisabled()
{
Console.WriteLine("TestUserControlEditInstalledCheckHasValueDisabled");
// a configuration with a checkbox control
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlEdit edit = new ControlEdit();
edit.Text = "4";
edit.Id = "edit1";
edit.Check = ControlCheckType.enabled; // control will be disabled, but has a value when disabled
edit.HasValueDisabled = true;
setupConfiguration.Children.Add(edit);
// an installed check that is always false
InstalledCheckRegistry check = new InstalledCheckRegistry();
check.path = @"SOFTWARE\KeyDoesntExist";
check.comparison = installcheckregistry_comparison.exists;
edit.Children.Add(check);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [edit1]5";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
Assert.AreEqual(45, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlEditInstalledCheckHasNoValueDisabled()
{
Console.WriteLine("TestUserControlEditInstalledCheckHasNoValueDisabled");
// a configuration with a checkbox control
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlEdit edit = new ControlEdit();
edit.Text = "4";
edit.Id = "edit1";
edit.Check = ControlCheckType.enabled; // control will be disabled, but has a value when disabled
edit.HasValueDisabled = false;
setupConfiguration.Children.Add(edit);
// an installed check that is always false
InstalledCheckRegistry check = new InstalledCheckRegistry();
check.path = @"SOFTWARE\KeyDoesntExist";
check.comparison = installcheckregistry_comparison.exists;
edit.Children.Add(check);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [edit1]5";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
Assert.AreEqual(5, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlEditInstalledCheckDisplay()
{
Console.WriteLine("TestUserControlEditInstalledCheckDisplay");
// a configuration with a checkbox control
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlEdit edit = new ControlEdit();
edit.Text = "4";
edit.Id = "edit1";
edit.Check = ControlCheckType.display;
setupConfiguration.Children.Add(edit);
// an installed check that is always false
InstalledCheckRegistry check = new InstalledCheckRegistry();
check.path = @"SOFTWARE\KeyDoesntExist";
check.comparison = installcheckregistry_comparison.exists;
edit.Children.Add(check);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [edit1]5";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
Assert.AreEqual(5, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlHyperlink()
{
Console.WriteLine("TestUserControlHyperlink");
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlHyperlink hyperlink = new ControlHyperlink();
hyperlink.Text = "url";
hyperlink.Uri = "http://dotnetinstaller.codeplex.com";
setupConfiguration.Children.Add(hyperlink);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b 0";
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlBrowse()
{
Console.WriteLine("TestUserControlBrowse");
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlBrowse browse = new ControlBrowse();
browse.Text = "4";
browse.Id = "browse1";
setupConfiguration.Children.Add(browse);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [browse1]";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
Assert.AreEqual(4, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlBrowseBackslashStripped()
{
Console.WriteLine("TestUserControlBrowseBackslashStripped");
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlBrowse browse = new ControlBrowse();
browse.Text = @"42\";
browse.Id = "browse1";
setupConfiguration.Children.Add(browse);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C if \"[browse1]\"==\"42\" ( exit /b 0 ) else ( exit /b 1 )";
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlBrowseDrive()
{
Console.WriteLine("TestUserControlBrowseDrive");
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlBrowse browse = new ControlBrowse();
browse.Text = @"C:\";
browse.Id = "browse1";
setupConfiguration.Children.Add(browse);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C if \"[browse1]\"==\"C:\\\" ( exit /b 0 ) else ( exit /b 1 )";
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlImage()
{
Console.WriteLine("TestUserControlImage");
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlImage image = new ControlImage();
image.ResourceId = "RES_BANNER_DOESNTEXIST";
setupConfiguration.Children.Add(image);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b 0";
setupConfiguration.Children.Add(cmd);
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
Assert.AreEqual(-1, dotNetInstallerExeUtils.Run(configFilename));
image.ResourceId = "RES_BANNER";
configFile.SaveAs(configFilename);
Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlLicense()
{
Console.WriteLine("TestUserControlLicense");
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
// a configuration with a license agreement control
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlLicense license = new ControlLicense();
license.Accepted = true;
license.ResourceId = "MY_RES_LICENSE";
license.LicenseFile = configFilename;
setupConfiguration.Children.Add(license);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [MY_RES_LICENSE]";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// create a setup with the license file
InstallerLinkerArguments args = new InstallerLinkerArguments();
args.config = configFilename;
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
args.template = dotNetInstallerExeUtils.Executable;
Console.WriteLine("Linking '{0}'", args.output);
InstallerLinkerExeUtils.CreateInstaller(args);
Assert.IsTrue(File.Exists(args.output));
// execute dotNetInstaller
Assert.AreEqual(1, dotNetInstallerExeUtils.Run(args.output, "/q"));
File.Delete(args.config);
File.Delete(args.output);
}
[Test]
public void TestNoUserControl()
{
Console.WriteLine("TestNoUserControl");
// a configuration wthout a user control, value is blank
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [doesntexist]5[doesntexist]";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
Assert.AreEqual(5, dotNetInstallerExeUtils.Run(configFilename));
File.Delete(configFilename);
}
[Test]
public void TestUserControlCheckboxControlArgs()
{
Console.WriteLine("TestUserControlCheckboxControlArgs");
// a configuration with a checkbox control
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
// a checkbox that changes are return value
ControlCheckBox checkbox = new ControlCheckBox();
checkbox.UncheckedValue = "3";
checkbox.CheckedValue = "4";
checkbox.Checked = true;
checkbox.Id = "checkbox1";
setupConfiguration.Children.Add(checkbox);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [checkbox1]";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
dotNetInstallerExeUtils.RunOptions options = new dotNetInstallerExeUtils.RunOptions();
options.configFile = configFilename;
// unchecked value
options.args = "/controlArgs checkbox1:3";
Assert.AreEqual(3, dotNetInstallerExeUtils.Run(options));
// checked value
options.args = "/controlArgs checkbox1:4";
Assert.AreEqual(4, dotNetInstallerExeUtils.Run(options));
// invalid value
options.args = "/controlArgs checkbox1:5";
Assert.AreEqual(-1, dotNetInstallerExeUtils.Run(options));
File.Delete(configFilename);
}
[Test]
public void TestUserControlEditControlArgs()
{
Console.WriteLine("TestUserControlEditControlArgs");
// a configuration with a checkbox control
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlEdit edit = new ControlEdit();
edit.Text = "4";
edit.Id = "edit1";
setupConfiguration.Children.Add(edit);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [edit1]";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
dotNetInstallerExeUtils.RunOptions options = new dotNetInstallerExeUtils.RunOptions();
options.configFile = configFilename;
// edit value
options.args = "/controlArgs edit1:4";
Assert.AreEqual(4, dotNetInstallerExeUtils.Run(options));
File.Delete(configFilename);
}
[Test]
public void TestUserControlEditHtmlValues()
{
Console.WriteLine("TestUserControlEditHtmlValues");
bool usingHtmlInstaller = dotNetInstallerExeUtils.Executable.EndsWith("htmlInstaller.exe");
if (!usingHtmlInstaller)
{
return;
}
// a configuration with a checkbox control
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
setupConfiguration.auto_start = true;
setupConfiguration.failed_exec_command_continue = string.Empty;
setupConfiguration.auto_close_on_error = true;
configFile.Children.Add(setupConfiguration);
ControlEdit edit = new ControlEdit();
edit.Text = "3";
edit.Id = "edit1";
setupConfiguration.Children.Add(edit);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [edit1]1";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
InstallerLinkerArguments args = new InstallerLinkerArguments();
args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", args.config);
configFile.SaveAs(args.config);
// create HTML directory
string htmlPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(htmlPath);
string htmlIndexFilename = Path.Combine(htmlPath, "index.html");
File.WriteAllText(
htmlIndexFilename,
@"<html><head><title></title></head><body>
<input type=""text"" id=""edit1"" value=""4"" />
<input id=""button_install"" type=""button"" value=""Install"" />
</body></html>");
// link the install executable
args.htmlFiles = new string[] { htmlPath };
args.embed = true;
args.apppath = Path.GetTempPath();
args.embedFiles = new string[] { Path.GetFileName(args.config) };
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
args.template = dotNetInstallerExeUtils.Executable;
Console.WriteLine("Linking '{0}'", args.output);
InstallerLinkerExeUtils.CreateInstaller(args);
Assert.IsTrue(File.Exists(args.output));
// execute dotNetInstaller
dotNetInstallerExeUtils.RunOptions runOptions = new dotNetInstallerExeUtils.RunOptions();
runOptions.autostart = true;
runOptions.quiet = false;
Assert.AreEqual(41, dotNetInstallerExeUtils.Run(args.output, runOptions.CommandLineArgs));
File.Delete(args.config);
Directory.Delete(args.htmlFiles[0], true);
}
[Test]
public void TestUserControlRadioButtonHtmlValues()
{
Console.WriteLine("TestUserControlRadioButtonHtmlValues");
bool usingHtmlInstaller = dotNetInstallerExeUtils.Executable.EndsWith("htmlInstaller.exe");
if (!usingHtmlInstaller)
{
return;
}
// a configuration with a checkbox control
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
setupConfiguration.auto_start = true;
setupConfiguration.failed_exec_command_continue = string.Empty;
setupConfiguration.auto_close_on_error = true;
configFile.Children.Add(setupConfiguration);
ControlEdit edit = new ControlEdit();
edit.Text = "3";
edit.Id = "edit1";
setupConfiguration.Children.Add(edit);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [edit1]1";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
InstallerLinkerArguments args = new InstallerLinkerArguments();
args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", args.config);
configFile.SaveAs(args.config);
// create HTML directory
string htmlPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(htmlPath);
string htmlIndexFilename = Path.Combine(htmlPath, "index.html");
File.WriteAllText(
htmlIndexFilename,
@"<html><head><title></title></head><body>
<input type=""radio"" id=""edit1"" name=""edit1"" value=""4"" checked=""checked"" />
<input type=""radio"" id=""edit1"" name=""edit1"" value=""2"" />
<input id=""button_install"" type=""button"" value=""Install"" />
</body></html>");
// link the install executable
args.htmlFiles = new string[] { htmlPath };
args.embed = true;
args.apppath = Path.GetTempPath();
args.embedFiles = new string[] { Path.GetFileName(args.config) };
args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
args.template = dotNetInstallerExeUtils.Executable;
Console.WriteLine("Linking '{0}'", args.output);
InstallerLinkerExeUtils.CreateInstaller(args);
Assert.IsTrue(File.Exists(args.output));
// execute dotNetInstaller
dotNetInstallerExeUtils.RunOptions runOptions = new dotNetInstallerExeUtils.RunOptions();
runOptions.autostart = true;
runOptions.quiet = false;
Assert.AreEqual(41, dotNetInstallerExeUtils.Run(args.output, runOptions.CommandLineArgs));
File.Delete(args.config);
Directory.Delete(args.htmlFiles[0], true);
}
[Test]
public void TestUserControlBrowseControlArgs()
{
Console.WriteLine("TestUserControlBrowseControlArgs");
// a configuration with a checkbox control
ConfigFile configFile = new ConfigFile();
SetupConfiguration setupConfiguration = new SetupConfiguration();
configFile.Children.Add(setupConfiguration);
ControlBrowse browse = new ControlBrowse();
browse.Text = "4";
browse.Id = "browse1";
setupConfiguration.Children.Add(browse);
ComponentCmd cmd = new ComponentCmd();
cmd.command = "cmd.exe /C exit /b [browse1]";
cmd.required_install = true;
setupConfiguration.Children.Add(cmd);
// save config file
string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
Console.WriteLine("Writing '{0}'", configFilename);
configFile.SaveAs(configFilename);
// execute dotNetInstaller
dotNetInstallerExeUtils.RunOptions options = new dotNetInstallerExeUtils.RunOptions();
options.configFile = configFilename;
options.args = "/controlArgs browse1:4";
Assert.AreEqual(4, dotNetInstallerExeUtils.Run(options));
File.Delete(configFilename);
}
}
}
| |
// 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 CompareLessThanSByte()
{
var test = new SimpleBinaryOpTest__CompareLessThanSByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// 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();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareLessThanSByte
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(SByte);
private static SByte[] _data1 = new SByte[ElementCount];
private static SByte[] _data2 = new SByte[ElementCount];
private static Vector128<SByte> _clsVar1;
private static Vector128<SByte> _clsVar2;
private Vector128<SByte> _fld1;
private Vector128<SByte> _fld2;
private SimpleBinaryOpTest__DataTable<SByte> _dataTable;
static SimpleBinaryOpTest__CompareLessThanSByte()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareLessThanSByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<SByte>(_data1, _data2, new SByte[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.CompareLessThan(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.CompareLessThan(
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.CompareLessThan(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareLessThan), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareLessThan), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareLessThan), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.CompareLessThan(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareLessThan(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareLessThan(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareLessThan(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareLessThanSByte();
var result = Sse2.CompareLessThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.CompareLessThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<SByte> left, Vector128<SByte> right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[ElementCount];
SByte[] inArray2 = new SByte[ElementCount];
SByte[] outArray = new SByte[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[ElementCount];
SByte[] inArray2 = new SByte[ElementCount];
SByte[] outArray = new SByte[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
if (result[0] != ((left[0] < right[0]) ? unchecked((sbyte)(-1)) : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (result[i] != ((left[i] < right[i]) ? unchecked((sbyte)(-1)) : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareLessThan)}<SByte>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// 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 gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>AdGroupAdLabel</c> resource.</summary>
public sealed partial class AdGroupAdLabelName : gax::IResourceName, sys::IEquatable<AdGroupAdLabelName>
{
/// <summary>The possible contents of <see cref="AdGroupAdLabelName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>
/// .
/// </summary>
CustomerAdGroupAdLabel = 1,
}
private static gax::PathTemplate s_customerAdGroupAdLabel = new gax::PathTemplate("customers/{customer_id}/adGroupAdLabels/{ad_group_id_ad_id_label_id}");
/// <summary>Creates a <see cref="AdGroupAdLabelName"/> 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="AdGroupAdLabelName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AdGroupAdLabelName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AdGroupAdLabelName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AdGroupAdLabelName"/> with the pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AdGroupAdLabelName"/> constructed from the provided ids.</returns>
public static AdGroupAdLabelName FromCustomerAdGroupAdLabel(string customerId, string adGroupId, string adId, string labelId) =>
new AdGroupAdLabelName(ResourceNameType.CustomerAdGroupAdLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), adId: gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupAdLabelName"/> with pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdGroupAdLabelName"/> with pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </returns>
public static string Format(string customerId, string adGroupId, string adId, string labelId) =>
FormatCustomerAdGroupAdLabel(customerId, adGroupId, adId, labelId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupAdLabelName"/> with pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdGroupAdLabelName"/> with pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>.
/// </returns>
public static string FormatCustomerAdGroupAdLabel(string customerId, string adGroupId, string adId, string labelId) =>
s_customerAdGroupAdLabel.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="AdGroupAdLabelName"/> 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}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adGroupAdLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AdGroupAdLabelName"/> if successful.</returns>
public static AdGroupAdLabelName Parse(string adGroupAdLabelName) => Parse(adGroupAdLabelName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AdGroupAdLabelName"/> 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}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupAdLabelName">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="AdGroupAdLabelName"/> if successful.</returns>
public static AdGroupAdLabelName Parse(string adGroupAdLabelName, bool allowUnparsed) =>
TryParse(adGroupAdLabelName, allowUnparsed, out AdGroupAdLabelName 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="AdGroupAdLabelName"/> 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}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adGroupAdLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdGroupAdLabelName"/>, 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 adGroupAdLabelName, out AdGroupAdLabelName result) =>
TryParse(adGroupAdLabelName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdGroupAdLabelName"/> 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}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupAdLabelName">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="AdGroupAdLabelName"/>, 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 adGroupAdLabelName, bool allowUnparsed, out AdGroupAdLabelName result)
{
gax::GaxPreconditions.CheckNotNull(adGroupAdLabelName, nameof(adGroupAdLabelName));
gax::TemplatedResourceName resourceName;
if (s_customerAdGroupAdLabel.TryParseName(adGroupAdLabelName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerAdGroupAdLabel(resourceName[0], split1[0], split1[1], split1[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(adGroupAdLabelName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private AdGroupAdLabelName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adId = null, string adGroupId = null, string customerId = null, string labelId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AdId = adId;
AdGroupId = adGroupId;
CustomerId = customerId;
LabelId = labelId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AdGroupAdLabelName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/adGroupAdLabels/{ad_group_id}~{ad_id}~{label_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
public AdGroupAdLabelName(string customerId, string adGroupId, string adId, string labelId) : this(ResourceNameType.CustomerAdGroupAdLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), adId: gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)))
{
}
/// <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>Ad</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdId { get; }
/// <summary>
/// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdGroupId { 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>
/// The <c>Label</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LabelId { 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.CustomerAdGroupAdLabel: return s_customerAdGroupAdLabel.Expand(CustomerId, $"{AdGroupId}~{AdId}~{LabelId}");
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 AdGroupAdLabelName);
/// <inheritdoc/>
public bool Equals(AdGroupAdLabelName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AdGroupAdLabelName a, AdGroupAdLabelName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AdGroupAdLabelName a, AdGroupAdLabelName b) => !(a == b);
}
public partial class AdGroupAdLabel
{
/// <summary>
/// <see cref="AdGroupAdLabelName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal AdGroupAdLabelName ResourceNameAsAdGroupAdLabelName
{
get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupAdLabelName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupAdName"/>-typed view over the <see cref="AdGroupAd"/> resource name property.
/// </summary>
internal AdGroupAdName AdGroupAdAsAdGroupAdName
{
get => string.IsNullOrEmpty(AdGroupAd) ? null : AdGroupAdName.Parse(AdGroupAd, allowUnparsed: true);
set => AdGroupAd = value?.ToString() ?? "";
}
/// <summary><see cref="LabelName"/>-typed view over the <see cref="Label"/> resource name property.</summary>
internal LabelName LabelAsLabelName
{
get => string.IsNullOrEmpty(Label) ? null : LabelName.Parse(Label, allowUnparsed: true);
set => Label = value?.ToString() ?? "";
}
}
}
| |
namespace EFRelationshipSample.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class V0 : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Cities",
c => new
{
Id = c.String(nullable: false, maxLength: 128,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Id")
},
}),
Name = c.String(),
CountryId = c.String(nullable: false, maxLength: 128),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion",
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Version")
},
}),
CreatedAt = c.DateTimeOffset(nullable: false, precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "CreatedAt")
},
}),
UpdatedAt = c.DateTimeOffset(precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "UpdatedAt")
},
}),
Deleted = c.Boolean(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Deleted")
},
}),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Countries", t => t.CountryId, cascadeDelete: true)
.Index(t => t.CountryId)
.Index(t => t.CreatedAt, clustered: true);
CreateTable(
"dbo.Countries",
c => new
{
Id = c.String(nullable: false, maxLength: 128,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Id")
},
}),
Name = c.String(),
IsoCode = c.String(),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion",
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Version")
},
}),
CreatedAt = c.DateTimeOffset(nullable: false, precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "CreatedAt")
},
}),
UpdatedAt = c.DateTimeOffset(precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "UpdatedAt")
},
}),
Deleted = c.Boolean(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Deleted")
},
}),
})
.PrimaryKey(t => t.Id)
.Index(t => t.CreatedAt, clustered: true);
CreateTable(
"dbo.Events",
c => new
{
Id = c.String(nullable: false, maxLength: 128,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Id")
},
}),
Title = c.String(),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion",
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Version")
},
}),
CreatedAt = c.DateTimeOffset(nullable: false, precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "CreatedAt")
},
}),
UpdatedAt = c.DateTimeOffset(precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "UpdatedAt")
},
}),
Deleted = c.Boolean(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Deleted")
},
}),
})
.PrimaryKey(t => t.Id)
.Index(t => t.CreatedAt, clustered: true);
CreateTable(
"dbo.Speakers",
c => new
{
Id = c.String(nullable: false, maxLength: 128,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Id")
},
}),
Name = c.String(),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion",
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Version")
},
}),
CreatedAt = c.DateTimeOffset(nullable: false, precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "CreatedAt")
},
}),
UpdatedAt = c.DateTimeOffset(precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "UpdatedAt")
},
}),
Deleted = c.Boolean(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Deleted")
},
}),
})
.PrimaryKey(t => t.Id)
.Index(t => t.CreatedAt, clustered: true);
CreateTable(
"dbo.Users",
c => new
{
Id = c.String(nullable: false, maxLength: 128,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Id")
},
}),
Name = c.String(),
MyPropertyForDbOnly = c.String(),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion",
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Version")
},
}),
CreatedAt = c.DateTimeOffset(nullable: false, precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "CreatedAt")
},
}),
UpdatedAt = c.DateTimeOffset(precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "UpdatedAt")
},
}),
Deleted = c.Boolean(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Deleted")
},
}),
})
.PrimaryKey(t => t.Id)
.Index(t => t.CreatedAt, clustered: true);
CreateTable(
"dbo.Talks",
c => new
{
EventId = c.String(nullable: false, maxLength: 128),
SpeakerId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.EventId, t.SpeakerId })
.ForeignKey("dbo.Events", t => t.EventId, cascadeDelete: true)
.ForeignKey("dbo.Speakers", t => t.SpeakerId, cascadeDelete: true)
.Index(t => t.EventId)
.Index(t => t.SpeakerId);
CreateTable(
"dbo.Friends",
c => new
{
User_Id = c.String(nullable: false, maxLength: 128),
User_Id1 = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.User_Id, t.User_Id1 })
.ForeignKey("dbo.Users", t => t.User_Id)
.ForeignKey("dbo.Users", t => t.User_Id1)
.Index(t => t.User_Id)
.Index(t => t.User_Id1);
CreateTable(
"dbo.UnFriends",
c => new
{
User_Id = c.String(nullable: false, maxLength: 128),
User_Id1 = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.User_Id, t.User_Id1 })
.ForeignKey("dbo.Users", t => t.User_Id)
.ForeignKey("dbo.Users", t => t.User_Id1)
.Index(t => t.User_Id)
.Index(t => t.User_Id1);
}
public override void Down()
{
DropForeignKey("dbo.UnFriends", "User_Id1", "dbo.Users");
DropForeignKey("dbo.UnFriends", "User_Id", "dbo.Users");
DropForeignKey("dbo.Friends", "User_Id1", "dbo.Users");
DropForeignKey("dbo.Friends", "User_Id", "dbo.Users");
DropForeignKey("dbo.Talks", "SpeakerId", "dbo.Speakers");
DropForeignKey("dbo.Talks", "EventId", "dbo.Events");
DropForeignKey("dbo.Cities", "CountryId", "dbo.Countries");
DropIndex("dbo.UnFriends", new[] { "User_Id1" });
DropIndex("dbo.UnFriends", new[] { "User_Id" });
DropIndex("dbo.Friends", new[] { "User_Id1" });
DropIndex("dbo.Friends", new[] { "User_Id" });
DropIndex("dbo.Talks", new[] { "SpeakerId" });
DropIndex("dbo.Talks", new[] { "EventId" });
DropIndex("dbo.Users", new[] { "CreatedAt" });
DropIndex("dbo.Speakers", new[] { "CreatedAt" });
DropIndex("dbo.Events", new[] { "CreatedAt" });
DropIndex("dbo.Countries", new[] { "CreatedAt" });
DropIndex("dbo.Cities", new[] { "CreatedAt" });
DropIndex("dbo.Cities", new[] { "CountryId" });
DropTable("dbo.UnFriends");
DropTable("dbo.Friends");
DropTable("dbo.Talks");
DropTable("dbo.Users",
removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
{
{
"CreatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "CreatedAt" },
}
},
{
"Deleted",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Deleted" },
}
},
{
"Id",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Id" },
}
},
{
"UpdatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "UpdatedAt" },
}
},
{
"Version",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Version" },
}
},
});
DropTable("dbo.Speakers",
removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
{
{
"CreatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "CreatedAt" },
}
},
{
"Deleted",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Deleted" },
}
},
{
"Id",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Id" },
}
},
{
"UpdatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "UpdatedAt" },
}
},
{
"Version",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Version" },
}
},
});
DropTable("dbo.Events",
removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
{
{
"CreatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "CreatedAt" },
}
},
{
"Deleted",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Deleted" },
}
},
{
"Id",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Id" },
}
},
{
"UpdatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "UpdatedAt" },
}
},
{
"Version",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Version" },
}
},
});
DropTable("dbo.Countries",
removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
{
{
"CreatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "CreatedAt" },
}
},
{
"Deleted",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Deleted" },
}
},
{
"Id",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Id" },
}
},
{
"UpdatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "UpdatedAt" },
}
},
{
"Version",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Version" },
}
},
});
DropTable("dbo.Cities",
removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
{
{
"CreatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "CreatedAt" },
}
},
{
"Deleted",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Deleted" },
}
},
{
"Id",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Id" },
}
},
{
"UpdatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "UpdatedAt" },
}
},
{
"Version",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Version" },
}
},
});
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Authorization
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
/// <summary>
/// Extension methods for RoleAssignmentsOperations.
/// </summary>
public static partial class RoleAssignmentsOperationsExtensions
{
/// <summary>
/// Gets role assignments for a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider.
/// </param>
/// <param name='parentResourcePath'>
/// The parent resource identity.
/// </param>
/// <param name='resourceType'>
/// The resource type of the resource.
/// </param>
/// <param name='resourceName'>
/// The name of the resource to get role assignments for.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<RoleAssignment> ListForResource(this IRoleAssignmentsOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>))
{
return ((IRoleAssignmentsOperations)operations).ListForResourceAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments for a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider.
/// </param>
/// <param name='parentResourcePath'>
/// The parent resource identity.
/// </param>
/// <param name='resourceType'>
/// The resource type of the resource.
/// </param>
/// <param name='resourceName'>
/// The name of the resource to get role assignments for.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListForResourceAsync(this IRoleAssignmentsOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForResourceWithHttpMessagesAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets role assignments for a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<RoleAssignment> ListForResourceGroup(this IRoleAssignmentsOperations operations, string resourceGroupName, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>))
{
return ((IRoleAssignmentsOperations)operations).ListForResourceGroupAsync(resourceGroupName, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments for a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListForResourceGroupAsync(this IRoleAssignmentsOperations operations, string resourceGroupName, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForResourceGroupWithHttpMessagesAsync(resourceGroupName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role assignment to delete.
/// </param>
/// <param name='roleAssignmentName'>
/// The name of the role assignment to delete.
/// </param>
public static RoleAssignment Delete(this IRoleAssignmentsOperations operations, string scope, string roleAssignmentName)
{
return operations.DeleteAsync(scope, roleAssignmentName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role assignment to delete.
/// </param>
/// <param name='roleAssignmentName'>
/// The name of the role assignment to delete.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleAssignment> DeleteAsync(this IRoleAssignmentsOperations operations, string scope, string roleAssignmentName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(scope, roleAssignmentName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role assignment to create. The scope can be any REST
/// resource instance. For example, use '/subscriptions/{subscription-id}/' for
/// a subscription,
/// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for
/// a resource group, and
/// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}'
/// for a resource.
/// </param>
/// <param name='roleAssignmentName'>
/// The name of the role assignment to create. It can be any valid GUID.
/// </param>
/// <param name='properties'>
/// Role assignment properties.
/// </param>
public static RoleAssignment Create(this IRoleAssignmentsOperations operations, string scope, string roleAssignmentName, RoleAssignmentProperties properties = default(RoleAssignmentProperties))
{
return operations.CreateAsync(scope, roleAssignmentName, properties).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role assignment to create. The scope can be any REST
/// resource instance. For example, use '/subscriptions/{subscription-id}/' for
/// a subscription,
/// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for
/// a resource group, and
/// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name}'
/// for a resource.
/// </param>
/// <param name='roleAssignmentName'>
/// The name of the role assignment to create. It can be any valid GUID.
/// </param>
/// <param name='properties'>
/// Role assignment properties.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleAssignment> CreateAsync(this IRoleAssignmentsOperations operations, string scope, string roleAssignmentName, RoleAssignmentProperties properties = default(RoleAssignmentProperties), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(scope, roleAssignmentName, properties, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get the specified role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role assignment.
/// </param>
/// <param name='roleAssignmentName'>
/// The name of the role assignment to get.
/// </param>
public static RoleAssignment Get(this IRoleAssignmentsOperations operations, string scope, string roleAssignmentName)
{
return operations.GetAsync(scope, roleAssignmentName).GetAwaiter().GetResult();
}
/// <summary>
/// Get the specified role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role assignment.
/// </param>
/// <param name='roleAssignmentName'>
/// The name of the role assignment to get.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleAssignment> GetAsync( this IRoleAssignmentsOperations operations, string scope, string roleAssignmentName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(scope, roleAssignmentName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleAssignmentId'>
/// The ID of the role assignment to delete.
/// </param>
public static RoleAssignment DeleteById(this IRoleAssignmentsOperations operations, string roleAssignmentId)
{
return operations.DeleteByIdAsync(roleAssignmentId).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleAssignmentId'>
/// The ID of the role assignment to delete.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleAssignment> DeleteByIdAsync( this IRoleAssignmentsOperations operations, string roleAssignmentId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteByIdWithHttpMessagesAsync(roleAssignmentId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a role assignment by ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleAssignmentId'>
/// The ID of the role assignment to create.
/// </param>
/// <param name='properties'>
/// Role assignment properties.
/// </param>
public static RoleAssignment CreateById(this IRoleAssignmentsOperations operations, string roleAssignmentId, RoleAssignmentProperties properties = default(RoleAssignmentProperties))
{
return operations.CreateByIdAsync(roleAssignmentId, properties).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a role assignment by ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleAssignmentId'>
/// The ID of the role assignment to create.
/// </param>
/// <param name='properties'>
/// Role assignment properties.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleAssignment> CreateByIdAsync(this IRoleAssignmentsOperations operations, string roleAssignmentId, RoleAssignmentProperties properties = default(RoleAssignmentProperties), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateByIdWithHttpMessagesAsync(roleAssignmentId, properties, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a role assignment by ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleAssignmentId'>
/// The ID of the role assignment to get.
/// </param>
public static RoleAssignment GetById(this IRoleAssignmentsOperations operations, string roleAssignmentId)
{
return operations.GetByIdAsync(roleAssignmentId).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a role assignment by ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleAssignmentId'>
/// The ID of the role assignment to get.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleAssignment> GetByIdAsync( this IRoleAssignmentsOperations operations, string roleAssignmentId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetByIdWithHttpMessagesAsync(roleAssignmentId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all role assignments for the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<RoleAssignment> List(this IRoleAssignmentsOperations operations, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>))
{
return ((IRoleAssignmentsOperations)operations).ListAsync(odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all role assignments for the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListAsync(this IRoleAssignmentsOperations operations, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets role assignments for a scope.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role assignments.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<RoleAssignment> ListForScope(this IRoleAssignmentsOperations operations, string scope, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>))
{
return operations.ListForScopeAsync(scope, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments for a scope.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role assignments.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListForScopeAsync(this IRoleAssignmentsOperations operations, string scope, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForScopeWithHttpMessagesAsync(scope, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets role assignments for a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RoleAssignment> ListForResourceNext(this IRoleAssignmentsOperations operations, string nextPageLink)
{
return operations.ListForResourceNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments for a resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListForResourceNextAsync(this IRoleAssignmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForResourceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets role assignments for a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RoleAssignment> ListForResourceGroupNext(this IRoleAssignmentsOperations operations, string nextPageLink)
{
return operations.ListForResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments for a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListForResourceGroupNextAsync(this IRoleAssignmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all role assignments for the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RoleAssignment> ListNext(this IRoleAssignmentsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all role assignments for the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListNextAsync(this IRoleAssignmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets role assignments for a scope.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RoleAssignment> ListForScopeNext(this IRoleAssignmentsOperations operations, string nextPageLink)
{
return operations.ListForScopeNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments for a scope.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListForScopeNextAsync(this IRoleAssignmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForScopeNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// 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 Internal.Metadata.NativeFormat.Writer;
using Cts = Internal.TypeSystem;
using Ecma = System.Reflection.Metadata;
using CallingConventions = System.Reflection.CallingConventions;
using Debug = System.Diagnostics.Debug;
using MethodAttributes = System.Reflection.MethodAttributes;
using MethodImplAttributes = System.Reflection.MethodImplAttributes;
namespace ILCompiler.Metadata
{
partial class Transform<TPolicy>
{
internal EntityMap<Cts.MethodDesc, MetadataRecord> _methods
= new EntityMap<Cts.MethodDesc, MetadataRecord>(EqualityComparer<Cts.MethodDesc>.Default);
private Action<Cts.MethodDesc, Method> _initMethodDef;
private Action<Cts.MethodDesc, MemberReference> _initMethodRef;
private Action<Cts.MethodDesc, MethodInstantiation> _initMethodInst;
public override MetadataRecord HandleQualifiedMethod(Cts.MethodDesc method)
{
MetadataRecord rec;
if (method is Cts.InstantiatedMethod)
{
rec = HandleMethodInstantiation(method);
}
else if (method.IsTypicalMethodDefinition && _policy.GeneratesMetadata(method))
{
rec = new QualifiedMethod
{
EnclosingType = (TypeDefinition)HandleType(method.OwningType),
Method = HandleMethodDefinition(method),
};
}
else
{
rec = HandleMethodReference(method);
}
Debug.Assert(rec is QualifiedMethod || rec is MemberReference || rec is MethodInstantiation);
return rec;
}
private Method HandleMethodDefinition(Cts.MethodDesc method)
{
Debug.Assert(method.IsTypicalMethodDefinition);
Debug.Assert(_policy.GeneratesMetadata(method));
return (Method)_methods.GetOrCreate(method, _initMethodDef ?? (_initMethodDef = InitializeMethodDefinition));
}
private void InitializeMethodDefinition(Cts.MethodDesc entity, Method record)
{
record.Name = HandleString(entity.Name);
record.Signature = HandleMethodSignature(entity.Signature);
if (entity.HasInstantiation)
{
record.GenericParameters.Capacity = entity.Instantiation.Length;
foreach (var p in entity.Instantiation)
record.GenericParameters.Add(HandleGenericParameter((Cts.GenericParameterDesc)p));
}
var ecmaEntity = entity as Cts.Ecma.EcmaMethod;
if (ecmaEntity != null)
{
Ecma.MetadataReader reader = ecmaEntity.MetadataReader;
Ecma.MethodDefinition methodDef = reader.GetMethodDefinition(ecmaEntity.Handle);
Ecma.ParameterHandleCollection paramHandles = methodDef.GetParameters();
record.Parameters.Capacity = paramHandles.Count;
foreach (var paramHandle in paramHandles)
{
Ecma.Parameter param = reader.GetParameter(paramHandle);
Parameter paramRecord = new Parameter
{
Flags = param.Attributes,
Name = HandleString(reader.GetString(param.Name)),
Sequence = checked((ushort)param.SequenceNumber)
};
Ecma.ConstantHandle defaultValue = param.GetDefaultValue();
if (!defaultValue.IsNil)
{
paramRecord.DefaultValue = HandleConstant(ecmaEntity.Module, defaultValue);
}
Ecma.CustomAttributeHandleCollection paramAttributes = param.GetCustomAttributes();
if (paramAttributes.Count > 0)
{
paramRecord.CustomAttributes = HandleCustomAttributes(ecmaEntity.Module, paramAttributes);
}
record.Parameters.Add(paramRecord);
}
Ecma.CustomAttributeHandleCollection attributes = methodDef.GetCustomAttributes();
if (attributes.Count > 0)
{
record.CustomAttributes = HandleCustomAttributes(ecmaEntity.Module, attributes);
}
}
else
{
throw new NotImplementedException();
}
record.Flags = GetMethodAttributes(entity);
record.ImplFlags = GetMethodImplAttributes(entity);
//TODO: RVA
}
private MemberReference HandleMethodReference(Cts.MethodDesc method)
{
Debug.Assert(method.IsMethodDefinition);
return (MemberReference)_methods.GetOrCreate(method, _initMethodRef ?? (_initMethodRef = InitializeMethodReference));
}
private void InitializeMethodReference(Cts.MethodDesc entity, MemberReference record)
{
record.Name = HandleString(entity.Name);
record.Parent = HandleType(entity.OwningType);
record.Signature = HandleMethodSignature(entity.GetTypicalMethodDefinition().Signature);
}
private MethodInstantiation HandleMethodInstantiation(Cts.MethodDesc method)
{
return (MethodInstantiation)_methods.GetOrCreate(method, _initMethodInst ?? (_initMethodInst = InitializeMethodInstantiation));
}
private void InitializeMethodInstantiation(Cts.MethodDesc entity, MethodInstantiation record)
{
Cts.InstantiatedMethod instantiation = (Cts.InstantiatedMethod)entity;
record.Method = HandleQualifiedMethod(instantiation.GetMethodDefinition());
record.GenericTypeArguments.Capacity = instantiation.Instantiation.Length;
foreach (Cts.TypeDesc typeArgument in instantiation.Instantiation)
{
record.GenericTypeArguments.Add(HandleType(typeArgument));
}
}
public override MethodSignature HandleMethodSignature(Cts.MethodSignature signature)
{
// TODO: if Cts.MethodSignature implements Equals/GetHashCode, we could enable pooling here.
var result = new MethodSignature
{
CallingConvention = GetSignatureCallingConvention(signature),
GenericParameterCount = signature.GenericParameterCount,
ReturnType = HandleType(signature.ReturnType),
// TODO-NICE: VarArgParameters
};
result.Parameters.Capacity = signature.Length;
for (int i = 0; i < signature.Length; i++)
{
result.Parameters.Add(HandleType(signature[i]));
}
return result;
}
private MethodAttributes GetMethodAttributes(Cts.MethodDesc method)
{
var ecmaMethod = method as Cts.Ecma.EcmaMethod;
if (ecmaMethod != null)
{
Ecma.MetadataReader reader = ecmaMethod.MetadataReader;
Ecma.MethodDefinition methodDef = reader.GetMethodDefinition(ecmaMethod.Handle);
return methodDef.Attributes;
}
else
throw new NotImplementedException();
}
private MethodImplAttributes GetMethodImplAttributes(Cts.MethodDesc method)
{
var ecmaMethod = method as Cts.Ecma.EcmaMethod;
if (ecmaMethod != null)
{
Ecma.MetadataReader reader = ecmaMethod.MetadataReader;
Ecma.MethodDefinition methodDef = reader.GetMethodDefinition(ecmaMethod.Handle);
return methodDef.ImplAttributes;
}
else
throw new NotImplementedException();
}
private CallingConventions GetSignatureCallingConvention(Cts.MethodSignature signature)
{
CallingConventions callingConvention = CallingConventions.Standard;
if ((signature.Flags & Cts.MethodSignatureFlags.Static) == 0)
{
callingConvention = CallingConventions.HasThis;
}
// TODO: additional calling convention flags like stdcall / cdecl etc.
return callingConvention;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace GeneratorBase.MVC.Models
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
using System.Runtime.Serialization;
namespace System.Drawing
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public sealed partial class Bitmap : Image
{
private static readonly Color s_defaultTransparentColor = Color.LightGray;
private Bitmap() { }
internal Bitmap(IntPtr ptr) => SetNativeImage(ptr);
public Bitmap(string filename) : this(filename, useIcm: false) { }
public Bitmap(string filename, bool useIcm)
{
// GDI+ will read this file multiple times. Get the fully qualified path
// so if the app's default directory changes we won't get an error.
filename = Path.GetFullPath(filename);
IntPtr bitmap = IntPtr.Zero;
int status;
if (useIcm)
{
status = Gdip.GdipCreateBitmapFromFileICM(filename, out bitmap);
}
else
{
status = Gdip.GdipCreateBitmapFromFile(filename, out bitmap);
}
Gdip.CheckStatus(status);
ValidateImage(bitmap);
SetNativeImage(bitmap);
EnsureSave(this, filename, null);
}
public Bitmap(Stream stream) : this(stream, false) { }
public Bitmap(int width, int height) : this(width, height, PixelFormat.Format32bppArgb)
{
}
public Bitmap(int width, int height, Graphics g)
{
if (g == null)
{
throw new ArgumentNullException(nameof(g));
}
IntPtr bitmap = IntPtr.Zero;
int status = Gdip.GdipCreateBitmapFromGraphics(width, height, new HandleRef(g, g.NativeGraphics), out bitmap);
Gdip.CheckStatus(status);
SetNativeImage(bitmap);
}
public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0)
{
IntPtr bitmap = IntPtr.Zero;
int status = Gdip.GdipCreateBitmapFromScan0(width, height, stride, unchecked((int)format), scan0, out bitmap);
Gdip.CheckStatus(status);
SetNativeImage(bitmap);
}
public Bitmap(int width, int height, PixelFormat format)
{
IntPtr bitmap = IntPtr.Zero;
int status = Gdip.GdipCreateBitmapFromScan0(width, height, 0, unchecked((int)format), IntPtr.Zero, out bitmap);
Gdip.CheckStatus(status);
SetNativeImage(bitmap);
}
public Bitmap(Image original) : this(original, original.Width, original.Height)
{
}
public Bitmap(Image original, Size newSize) : this(original, newSize.Width, newSize.Height)
{
}
public Bitmap(Image original, int width, int height) : this(width, height, PixelFormat.Format32bppArgb)
{
if (original == null)
throw new ArgumentNullException(nameof(original));
using (Graphics g = Graphics.FromImage(this))
{
g.Clear(Color.Transparent);
g.DrawImage(original, 0, 0, width, height);
}
}
private Bitmap(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public static Bitmap FromHicon(IntPtr hicon)
{
Gdip.CheckStatus(Gdip.GdipCreateBitmapFromHICON(hicon, out IntPtr bitmap));
return new Bitmap(bitmap);
}
public static Bitmap FromResource(IntPtr hinstance, string bitmapName)
{
IntPtr name = Marshal.StringToHGlobalUni(bitmapName);
try
{
Gdip.CheckStatus(Gdip.GdipCreateBitmapFromResource(hinstance, name, out IntPtr bitmap));
return new Bitmap(bitmap);
}
finally
{
Marshal.FreeHGlobal(name);
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public IntPtr GetHbitmap() => GetHbitmap(Color.LightGray);
[EditorBrowsable(EditorBrowsableState.Advanced)]
public IntPtr GetHbitmap(Color background)
{
IntPtr hBitmap = IntPtr.Zero;
int status = Gdip.GdipCreateHBITMAPFromBitmap(new HandleRef(this, nativeImage), out hBitmap,
ColorTranslator.ToWin32(background));
if (status == 2 /* invalid parameter*/ && (Width >= short.MaxValue || Height >= short.MaxValue))
{
throw new ArgumentException(SR.GdiplusInvalidSize);
}
Gdip.CheckStatus(status);
return hBitmap;
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public IntPtr GetHicon()
{
IntPtr hIcon = IntPtr.Zero;
int status = Gdip.GdipCreateHICONFromBitmap(new HandleRef(this, nativeImage), out hIcon);
Gdip.CheckStatus(status);
return hIcon;
}
public Bitmap Clone(RectangleF rect, PixelFormat format)
{
if (rect.Width == 0 || rect.Height == 0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
IntPtr dstHandle = IntPtr.Zero;
int status = Gdip.GdipCloneBitmapArea(
rect.X,
rect.Y,
rect.Width,
rect.Height,
unchecked((int)format),
new HandleRef(this, nativeImage),
out dstHandle);
if (status != Gdip.Ok || dstHandle == IntPtr.Zero)
throw Gdip.StatusException(status);
return new Bitmap(dstHandle);
}
public void MakeTransparent()
{
Color transparent = s_defaultTransparentColor;
if (Height > 0 && Width > 0)
{
transparent = GetPixel(0, Size.Height - 1);
}
if (transparent.A < 255)
{
// It's already transparent, and if we proceeded, we will do something
// unintended like making black transparent
return;
}
MakeTransparent(transparent);
}
public void MakeTransparent(Color transparentColor)
{
if (RawFormat.Guid == ImageFormat.Icon.Guid)
{
throw new InvalidOperationException(SR.CantMakeIconTransparent);
}
Size size = Size;
// The new bitmap must be in 32bppARGB format, because that's the only
// thing that supports alpha. (And that's what the image is initialized to -- transparent)
using (var result = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb))
using (Graphics graphics = Graphics.FromImage(result))
{
graphics.Clear(Color.Transparent);
Rectangle rectangle = new Rectangle(0, 0, size.Width, size.Height);
using (var attributes = new ImageAttributes())
{
attributes.SetColorKey(transparentColor, transparentColor);
graphics.DrawImage(this, rectangle,
0, 0, size.Width, size.Height,
GraphicsUnit.Pixel, attributes, null, IntPtr.Zero);
}
// Swap nativeImage pointers to make it look like we modified the image in place
IntPtr temp = nativeImage;
nativeImage = result.nativeImage;
result.nativeImage = temp;
}
}
public BitmapData LockBits(Rectangle rect, ImageLockMode flags, PixelFormat format)
{
return LockBits(rect, flags, format, new BitmapData());
}
public BitmapData LockBits(Rectangle rect, ImageLockMode flags, PixelFormat format, BitmapData bitmapData)
{
int status = Gdip.GdipBitmapLockBits(
new HandleRef(this, nativeImage), ref rect, flags, format, bitmapData);
// libgdiplus has the wrong error code mapping for this state.
if (status == 7)
{
status = 8;
}
Gdip.CheckStatus(status);
return bitmapData;
}
public void UnlockBits(BitmapData bitmapdata)
{
int status = Gdip.GdipBitmapUnlockBits(new HandleRef(this, nativeImage), bitmapdata);
Gdip.CheckStatus(status);
}
public Color GetPixel(int x, int y)
{
if (x < 0 || x >= Width)
{
throw new ArgumentOutOfRangeException(nameof(x), SR.ValidRangeX);
}
if (y < 0 || y >= Height)
{
throw new ArgumentOutOfRangeException(nameof(y), SR.ValidRangeY);
}
int color = 0;
int status = Gdip.GdipBitmapGetPixel(new HandleRef(this, nativeImage), x, y, out color);
Gdip.CheckStatus(status);
return Color.FromArgb(color);
}
public void SetPixel(int x, int y, Color color)
{
if ((PixelFormat & PixelFormat.Indexed) != 0)
{
throw new InvalidOperationException(SR.GdiplusCannotSetPixelFromIndexedPixelFormat);
}
if (x < 0 || x >= Width)
{
throw new ArgumentOutOfRangeException(nameof(x), SR.ValidRangeX);
}
if (y < 0 || y >= Height)
{
throw new ArgumentOutOfRangeException(nameof(y), SR.ValidRangeY);
}
int status = Gdip.GdipBitmapSetPixel(new HandleRef(this, nativeImage), x, y, color.ToArgb());
Gdip.CheckStatus(status);
}
public void SetResolution(float xDpi, float yDpi)
{
int status = Gdip.GdipBitmapSetResolution(new HandleRef(this, nativeImage), xDpi, yDpi);
Gdip.CheckStatus(status);
}
public Bitmap Clone(Rectangle rect, PixelFormat format)
{
if (rect.Width == 0 || rect.Height == 0)
{
throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString()));
}
IntPtr dstHandle = IntPtr.Zero;
int status = Gdip.GdipCloneBitmapAreaI(
rect.X,
rect.Y,
rect.Width,
rect.Height,
unchecked((int)format),
new HandleRef(this, nativeImage),
out dstHandle);
if (status != Gdip.Ok || dstHandle == IntPtr.Zero)
throw Gdip.StatusException(status);
return new Bitmap(dstHandle);
}
}
}
| |
#region Foreign-License
// .Net40 Kludge
#endregion
#if NET35
using System.Threading;
using System.Diagnostics;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace System
{
/// <summary>
/// Lazy
/// </summary>
/// <typeparam name="T"></typeparam>
[Serializable, DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}"), DebuggerTypeProxy(typeof(System_LazyDebugView<>)), ComVisible(false), HostProtection(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
public class Lazy<T>
{
private volatile object _boxed;
[NonSerialized]
private readonly object _threadSafeObj;
[NonSerialized]
private Func<T> m_valueFactory;
private static Func<T> PUBLICATION_ONLY_OR_ALREADY_INITIALIZED = (() => default(T));
static Lazy() { }
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
/// <summary>
/// Initializes a new instance of the <see cref="Lazy<T>"/> class.
/// </summary>
public Lazy()
: this(LazyThreadSafetyMode.ExecutionAndPublication) { }
/// <summary>
/// Initializes a new instance of the <see cref="Lazy<T>"/> class.
/// </summary>
/// <param name="isThreadSafe">if set to <c>true</c> [is thread safe].</param>
public Lazy(bool isThreadSafe)
: this(isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) { }
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
/// <summary>
/// Initializes a new instance of the <see cref="Lazy<T>"/> class.
/// </summary>
/// <param name="valueFactory">The value factory.</param>
public Lazy(Func<T> valueFactory)
: this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication) { }
/// <summary>
/// Initializes a new instance of the <see cref="Lazy<T>"/> class.
/// </summary>
/// <param name="mode">The mode.</param>
public Lazy(LazyThreadSafetyMode mode)
{
_threadSafeObj = GetObjectFromMode(mode);
}
/// <summary>
/// Initializes a new instance of the <see cref="Lazy<T>"/> class.
/// </summary>
/// <param name="valueFactory">The value factory.</param>
/// <param name="isThreadSafe">if set to <c>true</c> [is thread safe].</param>
public Lazy(Func<T> valueFactory, bool isThreadSafe)
: this(valueFactory, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) { }
/// <summary>
/// Initializes a new instance of the <see cref="Lazy<T>"/> class.
/// </summary>
/// <param name="valueFactory">The value factory.</param>
/// <param name="mode">The mode.</param>
public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode)
{
if (valueFactory == null)
throw new ArgumentNullException("valueFactory");
_threadSafeObj = GetObjectFromMode(mode);
m_valueFactory = valueFactory;
}
private Boxed CreateValue()
{
Boxed boxed = null;
LazyThreadSafetyMode mode = Mode;
if (m_valueFactory != null)
{
try
{
if ((mode != LazyThreadSafetyMode.PublicationOnly) && (m_valueFactory == PUBLICATION_ONLY_OR_ALREADY_INITIALIZED))
throw new InvalidOperationException("Lazy_Value_RecursiveCallsToValue");
var valueFactory = m_valueFactory;
if (mode != LazyThreadSafetyMode.PublicationOnly)
m_valueFactory = PUBLICATION_ONLY_OR_ALREADY_INITIALIZED;
return new Boxed(valueFactory());
}
catch (Exception exception)
{
if (mode != LazyThreadSafetyMode.PublicationOnly)
_boxed = new LazyInternalExceptionHolder(exception.PrepareForRethrow());
throw;
}
}
try { boxed = new Boxed((T)Activator.CreateInstance(typeof(T))); }
catch (MissingMethodException)
{
Exception ex = new MissingMemberException("Lazy_CreateValue_NoParameterlessCtorForT");
if (mode != LazyThreadSafetyMode.PublicationOnly)
_boxed = new LazyInternalExceptionHolder(ex);
throw ex;
}
return boxed;
}
private static object GetObjectFromMode(LazyThreadSafetyMode mode)
{
if (mode == LazyThreadSafetyMode.ExecutionAndPublication)
return new object();
if (mode == LazyThreadSafetyMode.PublicationOnly)
return PUBLICATION_ONLY_OR_ALREADY_INITIALIZED;
if (mode != LazyThreadSafetyMode.None)
throw new ArgumentOutOfRangeException("mode", "Lazy_ctor_ModeInvalid");
return null;
}
private T LazyInitValue()
{
Boxed boxed = null;
switch (Mode)
{
case LazyThreadSafetyMode.None:
boxed = CreateValue();
_boxed = boxed;
break;
case LazyThreadSafetyMode.PublicationOnly:
boxed = CreateValue();
#pragma warning disable 420
if (Interlocked.CompareExchange(ref _boxed, boxed, null) != null)
boxed = (Boxed)_boxed;
#pragma warning restore 420
break;
default:
lock (_threadSafeObj)
{
if (_boxed == null)
{
boxed = CreateValue();
_boxed = boxed;
}
else
{
boxed = (_boxed as Boxed);
if (boxed == null)
{
var holder = (_boxed as LazyInternalExceptionHolder);
throw holder._exception;
}
}
}
break;
}
return boxed._value;
}
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
T local1 = Value;
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
if (!IsValueCreated)
return "Lazy_ToString_ValueNotCreated";
return this.Value.ToString();
}
/// <summary>
/// Gets a value indicating whether this instance is value created.
/// </summary>
/// <value>
/// <c>true</c> if this instance is value created; otherwise, <c>false</c>.
/// </value>
public bool IsValueCreated
{
//[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
get { return (_boxed != null && _boxed is Boxed); }
}
internal bool IsValueFaulted
{
get { return (_boxed is LazyInternalExceptionHolder); }
}
internal LazyThreadSafetyMode Mode
{
get
{
if (_threadSafeObj == null)
return LazyThreadSafetyMode.None;
if (_threadSafeObj == (object)PUBLICATION_ONLY_OR_ALREADY_INITIALIZED)
return LazyThreadSafetyMode.PublicationOnly;
return LazyThreadSafetyMode.ExecutionAndPublication;
}
}
/// <summary>
/// Gets the value.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Value
{
get
{
Boxed boxed = null;
if (_boxed != null)
{
boxed = (_boxed as Boxed);
if (boxed != null)
return boxed._value;
var holder = (_boxed as LazyInternalExceptionHolder);
throw holder._exception;
}
//Debugger.NotifyOfCrossThreadDependency();
return LazyInitValue();
}
}
internal T ValueForDebugDisplay
{
get
{
if (!this.IsValueCreated)
return default(T);
return ((Boxed)_boxed)._value;
}
}
[Serializable]
private class Boxed
{
internal T _value;
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal Boxed(T value)
{
_value = value;
}
}
private class LazyInternalExceptionHolder
{
internal Exception _exception;
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal LazyInternalExceptionHolder(Exception ex)
{
_exception = ex;
}
}
}
}
#endif
| |
// 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.Linq;
using System.Reflection;
using Microsoft.Build.UnitTests;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using EscapingUtilities = Microsoft.Build.Shared.EscapingUtilities;
using FileUtilities = Microsoft.Build.Shared.FileUtilities;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using ResourceUtilities = Microsoft.Build.Shared.ResourceUtilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Build.UnitTests.EscapingInProjects_Tests
{
/// <summary>
/// Test task that just logs the parameters it receives.
/// </summary>
public class MyTestTask : Task
{
private ITaskItem _taskItemParam;
public ITaskItem TaskItemParam
{
get
{
return _taskItemParam;
}
set
{
_taskItemParam = value;
}
}
override public bool Execute()
{
if (TaskItemParam != null)
{
Log.LogMessageFromText("Received TaskItemParam: " + TaskItemParam.ItemSpec, MessageImportance.High);
}
return true;
}
}
public class SimpleScenarios : IDisposable
{
/// <summary>
/// Since we create a project with the same name in many of these tests, and two projects with
/// the same name cannot be loaded in a ProjectCollection at the same time, we should unload the
/// GlobalProjectCollection (into which all of these projects are placed by default) after each test.
/// </summary>
public void Dispose()
{
ProjectCollection.GlobalProjectCollection.UnloadAllProjects();
}
/// <summary>
/// Make sure I can define a property with escaped characters and pass it into
/// a string parameter of a task, in this case the Message task.
/// </summary>
[Fact]
public void SemicolonInPropertyPassedIntoStringParam()
{
MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<PropertyGroup>
<MyPropertyWithSemicolons>abc %3b def %3b ghi</MyPropertyWithSemicolons>
</PropertyGroup>
<Target Name=`Build`>
<Message Text=`Property value is '$(MyPropertyWithSemicolons)'` />
</Target>
</Project>
");
logger.AssertLogContains("Property value is 'abc ; def ; ghi'");
}
#if FEATURE_TASKHOST
/// <summary>
/// Make sure I can define a property with escaped characters and pass it into
/// a string parameter of a task, in this case the Message task.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void SemicolonInPropertyPassedIntoStringParam_UsingTaskHost()
{
MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<UsingTask TaskName=`Message` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` TaskFactory=`TaskHostFactory` />
<PropertyGroup>
<MyPropertyWithSemicolons>abc %3b def %3b ghi</MyPropertyWithSemicolons>
</PropertyGroup>
<Target Name=`Build`>
<Message Text=`Property value is '$(MyPropertyWithSemicolons)'` />
</Target>
</Project>
");
logger.AssertLogContains("Property value is 'abc ; def ; ghi'");
}
#endif
#if FEATURE_ASSEMBLY_LOCATION
/// <summary>
/// Make sure I can define a property with escaped characters and pass it into
/// an ITaskItem[] task parameter.
/// </summary>
[Fact]
public void SemicolonInPropertyPassedIntoITaskItemParam()
{
MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(String.Format(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<UsingTask TaskName=`Microsoft.Build.UnitTests.EscapingInProjects_Tests.MyTestTask` AssemblyFile=`{0}` />
<PropertyGroup>
<MyPropertyWithSemicolons>abc %3b def %3b ghi</MyPropertyWithSemicolons>
</PropertyGroup>
<Target Name=`Build`>
<MyTestTask TaskItemParam=`123 $(MyPropertyWithSemicolons) 789` />
</Target>
</Project>
", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath));
logger.AssertLogContains("Received TaskItemParam: 123 abc ; def ; ghi 789");
}
/// <summary>
/// Make sure I can define a property with escaped characters and pass it into
/// an ITaskItem[] task parameter.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void SemicolonInPropertyPassedIntoITaskItemParam_UsingTaskHost()
{
MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(String.Format(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<UsingTask TaskName=`Microsoft.Build.UnitTests.EscapingInProjects_Tests.MyTestTask` AssemblyFile=`{0}` TaskFactory=`TaskHostFactory` />
<PropertyGroup>
<MyPropertyWithSemicolons>abc %3b def %3b ghi</MyPropertyWithSemicolons>
</PropertyGroup>
<Target Name=`Build`>
<MyTestTask TaskItemParam=`123 $(MyPropertyWithSemicolons) 789` />
</Target>
</Project>
", new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath));
logger.AssertLogContains("Received TaskItemParam: 123 abc ; def ; ghi 789");
}
#endif
/// <summary>
/// If I try to add a new item to a project, and my new item's Include has an unescaped semicolon
/// in it, then we shouldn't try to match it up against any existing wildcards. This is a really
/// bizarre scenario ... the caller probably meant to escape the semicolon.
/// </summary>
[Fact]
public void AddNewItemWithSemicolon()
{
// ************************************
// BEFORE
// ************************************
string projectOriginalContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<MyWildCard Include=`*.weirdo`/>
</ItemGroup>
</Project>
";
// ************************************
// AFTER
// ************************************
string projectNewExpectedContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<MyWildCard Include=`*.weirdo`/>
<MyWildCard Include=`foo;bar.weirdo`/>
</ItemGroup>
</Project>
";
Project project = ObjectModelHelpers.CreateInMemoryProject(projectOriginalContents);
project.AddItem("MyWildCard", "foo;bar.weirdo");
Helpers.CompareProjectXml(projectNewExpectedContents, project.Xml.RawXml);
}
/// <summary>
/// If I try to add a new item to a project, and my new item's Include has a property that
/// contains an unescaped semicolon in it, then we shouldn't try to match it up against any existing
/// wildcards.
/// </summary>
[Fact]
public void AddNewItemWithPropertyContainingSemicolon()
{
// ************************************
// BEFORE
// ************************************
string projectOriginalContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<PropertyGroup>
<FilenameWithSemicolon>foo;bar</FilenameWithSemicolon>
</PropertyGroup>
<ItemGroup>
<MyWildCard Include=`*.weirdo`/>
</ItemGroup>
</Project>
";
// ************************************
// AFTER
// ************************************
string projectNewExpectedContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<PropertyGroup>
<FilenameWithSemicolon>foo;bar</FilenameWithSemicolon>
</PropertyGroup>
<ItemGroup>
<MyWildCard Include=`$(FilenameWithSemicolon).weirdo`/>
<MyWildCard Include=`*.weirdo`/>
</ItemGroup>
</Project>
";
Project project = ObjectModelHelpers.CreateInMemoryProject(projectOriginalContents);
project.AddItem("MyWildCard", "$(FilenameWithSemicolon).weirdo");
Helpers.CompareProjectXml(projectNewExpectedContents, project.Xml.RawXml);
}
/// <summary>
/// If I try to modify an item in a project, and my new item's Include has an unescaped semicolon
/// in it, then we shouldn't try to match it up against any existing wildcards. This is a really
/// bizarre scenario ... the caller probably meant to escape the semicolon.
/// </summary>
[Fact]
public void ModifyItemIncludeSemicolon()
{
// ************************************
// BEFORE
// ************************************
string projectOriginalContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<MyWildcard Include=`*.weirdo` />
</ItemGroup>
</Project>
";
// ************************************
// AFTER
// ************************************
string projectNewExpectedContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<MyWildcard Include=`a.weirdo` />
<MyWildcard Include=`foo;bar.weirdo` />
<MyWildcard Include=`c.weirdo` />
</ItemGroup>
</Project>
";
try
{
// Populate the project directory with three physical files on disk -- a.weirdo, b.weirdo, c.weirdo.
EscapingInProjectsHelper.CreateThreeWeirdoFiles();
Project project = ObjectModelHelpers.CreateInMemoryProject(projectOriginalContents);
EscapingInProjectsHelper.ModifyItemOfTypeInProject(project, "MyWildcard", "b.weirdo", "foo;bar.weirdo");
Helpers.CompareProjectXml(projectNewExpectedContents, project.Xml.RawXml);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
/// <summary>
/// If I try to modify an item in a project, and my new item's Include has an escaped semicolon
/// in it, and it matches the existing wildcard, then we shouldn't need to modify the project file.
/// </summary>
[Fact]
public void ModifyItemIncludeEscapedSemicolon()
{
// ************************************
// BEFORE
// ************************************
string projectOriginalContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<MyWildcard Include=`*.weirdo` />
</ItemGroup>
</Project>
";
// ************************************
// AFTER
// ************************************
string projectNewExpectedContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<MyWildcard Include=`*.weirdo` />
</ItemGroup>
</Project>
";
try
{
// Populate the project directory with three physical files on disk -- a.weirdo, b.weirdo, c.weirdo.
EscapingInProjectsHelper.CreateThreeWeirdoFiles();
Project project = ObjectModelHelpers.CreateInMemoryProject(projectOriginalContents);
IEnumerable<ProjectItem> newItems = EscapingInProjectsHelper.ModifyItemOfTypeInProject(project, "MyWildcard", "b.weirdo", "foo%253Bbar.weirdo");
Assert.Single(newItems);
Assert.Equal("*.weirdo", newItems.First().UnevaluatedInclude);
Assert.Equal("foo%3Bbar.weirdo", newItems.First().EvaluatedInclude);
Assert.Equal("foo%253Bbar.weirdo", Project.GetEvaluatedItemIncludeEscaped(newItems.First()));
Helpers.CompareProjectXml(projectNewExpectedContents, project.Xml.RawXml);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
/// <summary>
/// If I try to modify an item in a project, and my new item's Include has a property that
/// contains an unescaped semicolon in it, then we shouldn't try to match it up against any existing
/// wildcards.
/// </summary>
[Fact]
public void ModifyItemAddPropertyContainingSemicolon()
{
// ************************************
// BEFORE
// ************************************
string projectOriginalContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<PropertyGroup>
<FilenameWithSemicolon>foo;bar</FilenameWithSemicolon>
</PropertyGroup>
<ItemGroup>
<MyWildcard Include=`*.weirdo` />
</ItemGroup>
</Project>
";
// ************************************
// AFTER
// ************************************
string projectNewExpectedContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<PropertyGroup>
<FilenameWithSemicolon>foo;bar</FilenameWithSemicolon>
</PropertyGroup>
<ItemGroup>
<MyWildcard Include=`a.weirdo` />
<MyWildcard Include=`$(FilenameWithSemicolon).weirdo` />
<MyWildcard Include=`c.weirdo` />
</ItemGroup>
</Project>
";
try
{
// Populate the project directory with three physical files on disk -- a.weirdo, b.weirdo, c.weirdo.
EscapingInProjectsHelper.CreateThreeWeirdoFiles();
Project project = ObjectModelHelpers.CreateInMemoryProject(projectOriginalContents);
EscapingInProjectsHelper.ModifyItemOfTypeInProject(project, "MyWildcard", "b.weirdo", "$(FilenameWithSemicolon).weirdo");
Helpers.CompareProjectXml(projectNewExpectedContents, project.Xml.RawXml);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
/// <summary>
/// Make sure that character escaping works as expected when adding a new item that matches
/// an existing wildcarded item in the project file.
/// </summary>
[Fact]
public void AddNewItemThatMatchesWildcard1()
{
// ************************************
// BEFORE
// ************************************
string projectOriginalContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<MyWildCard Include=`*.weirdo`/>
</ItemGroup>
</Project>
";
// ************************************
// AFTER
// ************************************
string projectNewExpectedContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<MyWildCard Include=`*.weirdo`/>
</ItemGroup>
</Project>
";
Project project = ObjectModelHelpers.CreateInMemoryProject(projectOriginalContents);
IEnumerable<ProjectItem> newItems = project.AddItem("MyWildCard", "foo%253bbar.weirdo");
Helpers.CompareProjectXml(projectNewExpectedContents, project.Xml.RawXml);
Assert.Single(newItems);
Assert.Equal("MyWildCard", newItems.First().ItemType); // "Newly added item should have correct ItemType"
Assert.Equal("*.weirdo", newItems.First().UnevaluatedInclude); // "Newly added item should have correct UnevaluatedInclude"
Assert.Equal("foo%253bbar.weirdo", Project.GetEvaluatedItemIncludeEscaped(newItems.First())); // "Newly added item should have correct EvaluatedIncludeEscaped"
Assert.Equal("foo%3bbar.weirdo", newItems.First().EvaluatedInclude); // "Newly added item should have correct EvaluatedInclude"
}
/// <summary>
/// Make sure that character escaping works as expected when adding a new item that matches
/// an existing wildcarded item in the project file.
/// </summary>
[Fact]
public void AddNewItemThatMatchesWildcard2()
{
// ************************************
// BEFORE
// ************************************
string projectOriginalContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<MyWildCard Include=`*.AAA%253bBBB`/>
</ItemGroup>
</Project>
";
// ************************************
// AFTER
// ************************************
string projectNewExpectedContents = @"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<MyWildCard Include=`*.AAA%253bBBB`/>
</ItemGroup>
</Project>
";
Project project = ObjectModelHelpers.CreateInMemoryProject(projectOriginalContents);
IEnumerable<ProjectItem> newItems = project.AddItem("MyWildCard", "foo.AAA%253bBBB");
Helpers.CompareProjectXml(projectNewExpectedContents, project.Xml.RawXml);
Assert.Single(newItems);
Assert.Equal("MyWildCard", newItems.First().ItemType); // "Newly added item should have correct ItemType"
Assert.Equal("*.AAA%253bBBB", newItems.First().UnevaluatedInclude); // "Newly added item should have correct UnevaluatedInclude"
Assert.Equal("foo.AAA%253bBBB", Project.GetEvaluatedItemIncludeEscaped(newItems.First())); // "Newly added item should have correct EvaluatedIncludeEscaped"
Assert.Equal("foo.AAA%3bBBB", newItems.First().EvaluatedInclude); // "Newly added item should have correct EvaluatedInclude"
}
/// <summary>
/// Make sure that all inferred task outputs (those that are determined without actually
/// executing the task) are left escaped when they become real items in the engine, and
/// they only get unescaped when fed into a subsequent task.
/// </summary>
[Fact]
public void InferEscapedOutputsFromTask()
{
string inputFile = null;
string outputFile = null;
try
{
inputFile = FileUtilities.GetTemporaryFile();
outputFile = FileUtilities.GetTemporaryFile();
MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(String.Format(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Target Name=`GenerateResources` Inputs=`{0}` Outputs=`{1}`>
<NonExistentTask OutputResources=`aaa%253bbbb.resx; ccc%253bddd.resx`>
<Output ItemName=`Resource` TaskParameter=`OutputResources`/>
</NonExistentTask>
</Target>
<Target Name=`Build` DependsOnTargets=`GenerateResources`>
<Message Text=`Resources = @(Resource)`/>
</Target>
</Project>
", inputFile, outputFile));
logger.AssertLogContains("Resources = aaa%3bbbb.resx;ccc%3bddd.resx");
}
finally
{
if (inputFile != null) File.Delete(inputFile);
if (outputFile != null) File.Delete(outputFile);
}
}
/// <summary>
/// Do an item transform, where the transform expression contains an unescaped semicolon as well
/// as an escaped percent sign.
/// </summary>
[Fact]
public void ItemTransformContainingSemicolon()
{
MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<TextFile Include=`X.txt`/>
<TextFile Include=`Y.txt`/>
<TextFile Include=`Z.txt`/>
</ItemGroup>
<Target Name=`Build`>
<Message Text=`Transformed item list: '@(TextFile->'%(FileName);%(FileName)%253b%(FileName)%(Extension)',' ')'` />
</Target>
</Project>
");
logger.AssertLogContains("Transformed item list: 'X;X%3bX.txt Y;Y%3bY.txt Z;Z%3bZ.txt'");
}
#if FEATURE_TASKHOST
/// <summary>
/// Do an item transform, where the transform expression contains an unescaped semicolon as well
/// as an escaped percent sign.
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void ItemTransformContainingSemicolon_InTaskHost()
{
MockLogger logger = Helpers.BuildProjectWithNewOMExpectSuccess(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<UsingTask TaskName=`Message` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` TaskFactory=`TaskHostFactory` />
<ItemGroup>
<TextFile Include=`X.txt`/>
<TextFile Include=`Y.txt`/>
<TextFile Include=`Z.txt`/>
</ItemGroup>
<Target Name=`Build`>
<Message Text=`Transformed item list: '@(TextFile->'%(FileName);%(FileName)%253b%(FileName)%(Extension)',' ')'` />
</Target>
</Project>
");
logger.AssertLogContains("Transformed item list: 'X;X%3bX.txt Y;Y%3bY.txt Z;Z%3bZ.txt'");
}
#endif
/// <summary>
/// Tests that when we add an item and are in a directory with characters in need of escaping, and the
/// item's FullPath metadata is retrieved, that a properly un-escaped version of the path is returned
/// </summary>
[Fact]
public void FullPathMetadataOnItemUnescaped()
{
string projectName = "foo.proj";
string projectRelativePath = "(jay's parens test)";
string path = Path.Combine(Path.GetTempPath(), projectRelativePath);
string projectAbsolutePath = Path.Combine(path, projectName);
try
{
Directory.CreateDirectory(path);
ProjectRootElement projectElement = ProjectRootElement.Create(projectAbsolutePath);
ProjectItemGroupElement itemgroup = projectElement.AddItemGroup();
itemgroup.AddItem("ProjectFile", projectName);
Project project = new Project(projectElement, null, null, new ProjectCollection());
ProjectInstance projectInstance = project.CreateProjectInstance();
IEnumerable<ProjectItemInstance> items = projectInstance.GetItems("ProjectFile");
Assert.Equal(projectAbsolutePath, items.First().GetMetadataValue("FullPath"));
}
finally
{
if (File.Exists(projectAbsolutePath)) File.Delete(projectAbsolutePath);
if (Directory.Exists(path)) FileUtilities.DeleteWithoutTrailingBackslash(path);
}
}
/// <summary>
/// Test that we can pass in global properties containing escaped characters and they
/// won't be unescaped.
/// </summary>
[Fact]
public void GlobalPropertyWithEscapedCharacters()
{
MockLogger logger = new MockLogger();
Project project = ObjectModelHelpers.CreateInMemoryProject(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Target Name=`Build`>
<Message Text=`MyGlobalProperty = '$(MyGlobalProperty)'` />
</Target>
</Project>
");
project.SetGlobalProperty("MyGlobalProperty", "foo%253bbar");
bool success = project.Build(logger);
Assert.True(success); // "Build failed. See test output (Attachments in Azure Pipelines) for details"
logger.AssertLogContains("MyGlobalProperty = 'foo%3bbar'");
}
/// <summary>
/// If %2A (escaped '*') or %3F (escaped '?') is in an item's Include, it should be treated
/// literally, not as a wildcard
/// </summary>
[Fact]
public void EscapedWildcardsShouldNotBeExpanded()
{
MockLogger logger = new MockLogger();
try
{
// Populate the project directory with three physical files on disk -- a.weirdo, b.weirdo, c.weirdo.
EscapingInProjectsHelper.CreateThreeWeirdoFiles();
Project project = ObjectModelHelpers.CreateInMemoryProject(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Target Name=`t`>
<ItemGroup>
<type Include=`%2A` Exclude=``/>
</ItemGroup>
<Message Text=`[@(type)]`/>
</Target>
</Project>
");
bool success = project.Build(logger);
Assert.True(success); // "Build failed. See test output (Attachments in Azure Pipelines) for details"
logger.AssertLogContains("[*]");
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
#if FEATURE_TASKHOST
/// <summary>
/// If %2A (escaped '*') or %3F (escaped '?') is in an item's Include, it should be treated
/// literally, not as a wildcard
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void EscapedWildcardsShouldNotBeExpanded_InTaskHost()
{
MockLogger logger = new MockLogger();
try
{
// Populate the project directory with three physical files on disk -- a.weirdo, b.weirdo, c.weirdo.
EscapingInProjectsHelper.CreateThreeWeirdoFiles();
Project project = ObjectModelHelpers.CreateInMemoryProject(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<UsingTask TaskName=`Message` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` TaskFactory=`TaskHostFactory` />
<Target Name=`t`>
<ItemGroup>
<type Include=`%2A` Exclude=``/>
</ItemGroup>
<Message Text=`[@(type)]`/>
</Target>
</Project>
");
bool success = project.Build(logger);
Assert.True(success); // "Build failed. See test output (Attachments in Azure Pipelines) for details"
logger.AssertLogContains("[*]");
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
#endif
/// <summary>
/// Parity with Orcas: Target names are always unescaped, and in fact, if there are two targets,
/// one the escaped version of the other, the second will override the first as though they had the
/// same name.
/// </summary>
[Fact]
public void TargetNamesAlwaysUnescaped()
{
bool exceptionCaught = false;
try
{
ObjectModelHelpers.CreateInMemoryProject(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Target Name=`%24` />
</Project>
");
}
catch (InvalidProjectFileException ex)
{
string expectedErrorMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("NameInvalid", "$", "$");
Assert.Equal(expectedErrorMessage, ex.Message); // "Wrong error message"
exceptionCaught = true;
}
Assert.True(exceptionCaught); // "Expected an InvalidProjectFileException"
}
/// <summary>
/// Parity with Orcas: Target names are always unescaped, and in fact, if there are two targets,
/// one the escaped version of the other, the second will override the first as though they had the
/// same name.
/// </summary>
[Fact]
public void TargetNamesAlwaysUnescaped_Override()
{
Project project = ObjectModelHelpers.CreateInMemoryProject(@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Target Name=`%3B`>
<Message Text=`[WRONG]` />
</Target>
<Target Name=`;`>
<Message Text=`[OVERRIDE]` />
</Target>
</Project>
");
MockLogger logger = new MockLogger();
bool success = project.Build(logger);
Assert.True(success); // "Build failed. See test output (Attachments in Azure Pipelines) for details"
logger.AssertLogContains("[OVERRIDE]");
}
/// <summary>
/// Tests that when we set metadata through the evaluation model, we do the right thing
/// </summary>
[Fact]
public void SpecialCharactersInMetadataValueConstruction()
{
string projectString = @"
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<ItemGroup>
<None Include='MetadataTests'>
<EscapedSemicolon>%3B</EscapedSemicolon>
<EscapedDollarSign>%24</EscapedDollarSign>
</None>
</ItemGroup>
</Project>";
System.Xml.XmlReader reader = new System.Xml.XmlTextReader(new StringReader(projectString));
Project project = new Project(reader);
ProjectItem item = project.GetItems("None").Single();
EscapingInProjectsHelper.SpecialCharactersInMetadataValueTests(item);
}
/// <summary>
/// Tests that when we set metadata through the evaluation model, we do the right thing
/// </summary>
[Fact]
public void SpecialCharactersInMetadataValueEvaluation()
{
Project project = new Project();
ProjectItem item = project.AddItem("None", "MetadataTests", new Dictionary<string, string> {
{"EscapedSemicolon", "%3B"}, //Microsoft.Build.Evaluation.ProjectCollection.Escape(";")
{"EscapedDollarSign", "%24"}, //Microsoft.Build.Evaluation.ProjectCollection.Escape("$")
}).Single();
EscapingInProjectsHelper.SpecialCharactersInMetadataValueTests(item);
project.ReevaluateIfNecessary();
EscapingInProjectsHelper.SpecialCharactersInMetadataValueTests(item);
}
/// <summary>
/// Say you have a scenario where a user is allowed to specify an arbitrary set of files (or
/// any sort of items) and expects to be able to get them back out as they were sent in. In addition,
/// the user can specify a macro (property) that can resolve to yet another arbitrary set of items.
/// We want to make sure that we do the right thing (assuming that the user escaped the information
/// correctly coming in) and don't mess up their set of items
/// </summary>
[Fact]
public void CanGetCorrectListOfItemsWithSemicolonsInThem()
{
string projectString = @"
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<PropertyGroup>
<MyUserMacro>foo%3bbar</MyUserMacro>
</PropertyGroup>
<ItemGroup>
<CrazyList Include=""a"" />
<CrazyList Include=""b%3bc"" />
<CrazyList Include=""$(MyUserMacro)"" />
</ItemGroup>
</Project>";
System.Xml.XmlReader reader = new System.Xml.XmlTextReader(new StringReader(projectString));
Project project = new Project(reader);
IEnumerable<ProjectItem> items = project.GetItems("CrazyList");
Assert.Equal(3, items.Count());
Assert.Equal("a", items.ElementAt(0).EvaluatedInclude);
Assert.Equal("b;c", items.ElementAt(1).EvaluatedInclude);
Assert.Equal("foo;bar", items.ElementAt(2).EvaluatedInclude);
}
/// <summary>
/// Say you have a scenario where a user is allowed to specify an arbitrary set of files (or
/// any sort of items) and expects to be able to get them back out as they were sent in. In addition,
/// the user can specify a macro (property) that can resolve to yet another arbitrary set of items.
/// We want to make sure that we do the right thing (assuming that the user escaped the information
/// correctly coming in) and don't mess up their set of items
/// </summary>
[Fact]
public void CanGetCorrectListOfItemsWithSemicolonsInThem2()
{
string projectString = @"
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<PropertyGroup>
<MyUserMacro>foo;bar</MyUserMacro>
</PropertyGroup>
<ItemGroup>
<CrazyList Include=""a"" />
<CrazyList Include=""b%3bc"" />
<CrazyList Include=""$(MyUserMacro)"" />
</ItemGroup>
</Project>";
System.Xml.XmlReader reader = new System.Xml.XmlTextReader(new StringReader(projectString));
Project project = new Project(reader);
IEnumerable<ProjectItem> items = project.GetItems("CrazyList");
Assert.Equal(4, items.Count());
Assert.Equal("a", items.ElementAt(0).EvaluatedInclude);
Assert.Equal("b;c", items.ElementAt(1).EvaluatedInclude);
Assert.Equal("foo", items.ElementAt(2).EvaluatedInclude);
Assert.Equal("bar", items.ElementAt(3).EvaluatedInclude);
}
}
#if FEATURE_COMPILE_IN_TESTS
public class FullProjectsUsingMicrosoftCommonTargets
{
private readonly ITestOutputHelper _testOutput;
public FullProjectsUsingMicrosoftCommonTargets(ITestOutputHelper output)
{
_testOutput = output;
}
private const string SolutionFileContentsWithUnusualCharacters = @"Microsoft Visual Studio Solution File, Format Version 11.00
Project(`{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}`) = `Cons.ole;!@(foo)'^(Application1`, `Console;!@(foo)'^(Application1\Cons.ole;!@(foo)'^(Application1.csproj`, `{770F2381-8C39-49E9-8C96-0538FA4349A7}`
EndProject
Project(`{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}`) = `Class;!@(foo)'^(Library1`, `Class;!@(foo)'^(Library1\Class;!@(foo)'^(Library1.csproj`, `{0B4B78CC-C752-43C2-BE9A-319D20216129}`
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{770F2381-8C39-49E9-8C96-0538FA4349A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{770F2381-8C39-49E9-8C96-0538FA4349A7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{770F2381-8C39-49E9-8C96-0538FA4349A7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{770F2381-8C39-49E9-8C96-0538FA4349A7}.Release|Any CPU.Build.0 = Release|Any CPU
{0B4B78CC-C752-43C2-BE9A-319D20216129}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0B4B78CC-C752-43C2-BE9A-319D20216129}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0B4B78CC-C752-43C2-BE9A-319D20216129}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0B4B78CC-C752-43C2-BE9A-319D20216129}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
/// <summary>
/// ESCAPING: Escaping in conditionals is broken.
/// </summary>
[Fact]
public void SemicolonInConfiguration()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
// ---------------------
// Foo.csproj
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("foo.csproj", @"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Import Project=`$(MSBuildBinPath)\Microsoft.Common.props` />
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<OutputType>Library</OutputType>
<AssemblyName>ClassLibrary16</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'a%3bb%27c|AnyCPU' `>
<OutputPath>bin\a%3bb%27c\</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Compile Include=`Class1.cs` />
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// ---------------------
// Class1.cs
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("Class1.cs", @"
namespace ClassLibrary16
{
public class Class1
{
}
}
");
// Create a logger.
MockLogger logger = new MockLogger();
Project project = ObjectModelHelpers.LoadProjectFileInTempProjectDirectory("foo.csproj");
// Build the default targets using the Configuration "a;b'c".
project.SetGlobalProperty("Configuration", EscapingUtilities.Escape("a;b'c"));
bool success = project.Build(logger);
Assert.True(success); // "Build failed. See test output (Attachments in Azure Pipelines) for details"
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\a;b'c\ClassLibrary16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bin\a;b'c\ClassLibrary16.dll");
logger.AssertLogContains(String.Format("foo -> {0}", Path.Combine(ObjectModelHelpers.TempProjectDir, @"bin\a;b'c\ClassLibrary16.dll")));
}
#if FEATURE_TASKHOST
/// <summary>
/// ESCAPING: Escaping in conditionals is broken.
/// </summary>
[Fact]
public void SemicolonInConfiguration_UsingTaskHost()
{
string originalOverrideTaskHostVariable = Environment.GetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC");
try
{
Environment.SetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC", "1");
ObjectModelHelpers.DeleteTempProjectDirectory();
// ---------------------
// Foo.csproj
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("foo.csproj", @"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Import Project=`$(MSBuildBinPath)\Microsoft.Common.props` />
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<OutputType>Library</OutputType>
<AssemblyName>ClassLibrary16</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'a%3bb%27c|AnyCPU' `>
<OutputPath>bin\a%3bb%27c\</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Compile Include=`Class1.cs` />
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// ---------------------
// Class1.cs
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("Class1.cs", @"
namespace ClassLibrary16
{
public class Class1
{
}
}
");
// Create a logger.
MockLogger logger = new MockLogger();
Project project = ObjectModelHelpers.LoadProjectFileInTempProjectDirectory("foo.csproj");
// Build the default targets using the Configuration "a;b'c".
project.SetGlobalProperty("Configuration", EscapingUtilities.Escape("a;b'c"));
bool success = project.Build(logger);
Assert.True(success); // "Build failed. See test output (Attachments in Azure Pipelines) for details"
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\a;b'c\ClassLibrary16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bin\a;b'c\ClassLibrary16.dll");
logger.AssertLogContains(String.Format("foo -> {0}", Path.Combine(ObjectModelHelpers.TempProjectDir, @"bin\a;b'c\ClassLibrary16.dll")));
}
finally
{
Environment.SetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC", originalOverrideTaskHostVariable);
}
}
#endif
/// <summary>
/// ESCAPING: CopyBuildTarget target fails if the output assembly name contains a semicolon or single-quote
/// </summary>
[Fact]
public void SemicolonInAssemblyName()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
// ---------------------
// Foo.csproj
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("foo.csproj", @"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Import Project=`$(MSBuildBinPath)\Microsoft.Common.props` />
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<OutputType>Library</OutputType>
<AssemblyName>Class%3bLibrary16</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' `>
<OutputPath>bin\Debug\</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Compile Include=`Class1.cs` />
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// ---------------------
// Class1.cs
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("Class1.cs", @"
namespace ClassLibrary16
{
public class Class1
{
}
}
");
MockLogger log = new MockLogger(_testOutput);
ObjectModelHelpers.BuildTempProjectFileExpectSuccess("foo.csproj", log);
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\Class;Library16.dll", @"Did not find expected file obj\debug\Class;Library16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\Class;Library16.pdb", @"Did not find expected file obj\debug\Class;Library16.pdb");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bin\debug\Class;Library16.dll", @"Did not find expected file bin\debug\Class;Library16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\Class;Library16.pdb", @"Did not find expected file obj\debug\Class;Library16.pdb");
log.AssertLogContains(String.Format("foo -> {0}", Path.Combine(ObjectModelHelpers.TempProjectDir, @"bin\Debug\Class;Library16.dll")));
}
#if FEATURE_TASKHOST
/// <summary>
/// ESCAPING: CopyBuildTarget target fails if the output assembly name contains a semicolon or single-quote
/// </summary>
[Fact]
public void SemicolonInAssemblyName_UsingTaskHost()
{
string originalOverrideTaskHostVariable = Environment.GetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC");
try
{
Environment.SetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC", "1");
ObjectModelHelpers.DeleteTempProjectDirectory();
// ---------------------
// Foo.csproj
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("foo.csproj", @"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Import Project=`$(MSBuildBinPath)\Microsoft.Common.props` />
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<OutputType>Library</OutputType>
<AssemblyName>Class%3bLibrary16</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' `>
<OutputPath>bin\Debug\</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Compile Include=`Class1.cs` />
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// ---------------------
// Class1.cs
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("Class1.cs", @"
namespace ClassLibrary16
{
public class Class1
{
}
}
");
MockLogger log = new MockLogger(_testOutput);
ObjectModelHelpers.BuildTempProjectFileExpectSuccess("foo.csproj", log);
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\Class;Library16.dll", @"Did not find expected file obj\debug\Class;Library16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\Class;Library16.pdb", @"Did not find expected file obj\debug\Class;Library16.pdb");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bin\debug\Class;Library16.dll", @"Did not find expected file bin\debug\Class;Library16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\Class;Library16.pdb", @"Did not find expected file obj\debug\Class;Library16.pdb");
log.AssertLogContains(String.Format("foo -> {0}", Path.Combine(ObjectModelHelpers.TempProjectDir, @"bin\Debug\Class;Library16.dll")));
}
finally
{
Environment.SetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC", originalOverrideTaskHostVariable);
}
}
#endif
/// <summary>
/// ESCAPING: Conversion Issue: Properties with $(xxx) as literals are not being converted correctly
/// </summary>
[Fact]
public void DollarSignInAssemblyName()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
// ---------------------
// Foo.csproj
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("foo.csproj", @"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Import Project=`$(MSBuildBinPath)\Microsoft.Common.props` />
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<OutputType>Library</OutputType>
<AssemblyName>Class%24%28prop%29Library16</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' `>
<OutputPath>bin\Debug\</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Compile Include=`Class1.cs` />
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// ---------------------
// Class1.cs
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("Class1.cs", @"
namespace ClassLibrary16
{
public class Class1
{
}
}
");
MockLogger log = new MockLogger(_testOutput);
ObjectModelHelpers.BuildTempProjectFileExpectSuccess("foo.csproj", log);
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\Class$(prop)Library16.dll", @"Did not find expected file obj\debug\Class$(prop)Library16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\Class$(prop)Library16.pdb", @"Did not find expected file obj\debug\Class$(prop)Library16.pdb");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bin\debug\Class$(prop)Library16.dll", @"Did not find expected file bin\debug\Class$(prop)Library16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bin\debug\Class$(prop)Library16.pdb", @"Did not find expected file bin\debug\Class$(prop)Library16.pdb");
log.AssertLogContains(String.Format("foo -> {0}", Path.Combine(ObjectModelHelpers.TempProjectDir, @"bin\Debug\Class$(prop)Library16.dll")));
}
#if FEATURE_TASKHOST
/// <summary>
/// ESCAPING: Conversion Issue: Properties with $(xxx) as literals are not being converted correctly
/// </summary>
[Fact]
public void DollarSignInAssemblyName_UsingTaskHost()
{
string originalOverrideTaskHostVariable = Environment.GetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC");
try
{
Environment.SetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC", "1");
ObjectModelHelpers.DeleteTempProjectDirectory();
// ---------------------
// Foo.csproj
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("foo.csproj", @"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Import Project=`$(MSBuildBinPath)\Microsoft.Common.props` />
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<OutputType>Library</OutputType>
<AssemblyName>Class%24%28prop%29Library16</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' `>
<OutputPath>bin\Debug\</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Compile Include=`Class1.cs` />
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// ---------------------
// Class1.cs
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("Class1.cs", @"
namespace ClassLibrary16
{
public class Class1
{
}
}
");
MockLogger log = new MockLogger(_testOutput);
ObjectModelHelpers.BuildTempProjectFileExpectSuccess("foo.csproj", log);
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\Class$(prop)Library16.dll", @"Did not find expected file obj\debug\Class$(prop)Library16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\Class$(prop)Library16.pdb", @"Did not find expected file obj\debug\Class$(prop)Library16.pdb");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bin\debug\Class$(prop)Library16.dll", @"Did not find expected file bin\debug\Class$(prop)Library16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bin\debug\Class$(prop)Library16.pdb", @"Did not find expected file bin\debug\Class$(prop)Library16.pdb");
log.AssertLogContains(String.Format("foo -> {0}", Path.Combine(ObjectModelHelpers.TempProjectDir, @"bin\Debug\Class$(prop)Library16.dll")));
}
finally
{
Environment.SetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC", originalOverrideTaskHostVariable);
}
}
#endif
/// <summary>
/// This is the case when one of the source code files in the project has a filename containing a semicolon.
/// </summary>
[Fact]
public void SemicolonInSourceCodeFilename()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
// ---------------------
// Foo.csproj
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("foo.csproj", @"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Import Project=`$(MSBuildBinPath)\Microsoft.Common.props` />
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<OutputType>Library</OutputType>
<AssemblyName>ClassLibrary16</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' `>
<OutputPath>bin\Debug\</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Compile Include=`Class%3b1.cs` />
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// ---------------------
// Class1.cs
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("Class;1.cs", @"
namespace ClassLibrary16
{
public class Class1
{
}
}
");
MockLogger log = new MockLogger(_testOutput);
ObjectModelHelpers.BuildTempProjectFileExpectSuccess("foo.csproj", log);
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\ClassLibrary16.dll", @"Did not find expected file obj\debug\ClassLibrary16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\ClassLibrary16.pdb", @"Did not find expected file obj\debug\ClassLibrary16.pdb");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bin\debug\ClassLibrary16.dll", @"Did not find expected file bin\debug\ClassLibrary16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bin\debug\ClassLibrary16.pdb", @"Did not find expected file bin\debug\ClassLibrary16.pdb");
log.AssertLogContains(String.Format("foo -> {0}", Path.Combine(ObjectModelHelpers.TempProjectDir, @"bin\Debug\ClassLibrary16.dll")));
}
#if FEATURE_TASKHOST
/// <summary>
/// This is the case when one of the source code files in the project has a filename containing a semicolon.
/// </summary>
[Fact]
public void SemicolonInSourceCodeFilename_UsingTaskHost()
{
string originalOverrideTaskHostVariable = Environment.GetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC");
try
{
Environment.SetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC", "1");
ObjectModelHelpers.DeleteTempProjectDirectory();
// ---------------------
// Foo.csproj
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("foo.csproj", @"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Import Project=`$(MSBuildBinPath)\Microsoft.Common.props` />
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<OutputType>Library</OutputType>
<AssemblyName>ClassLibrary16</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' `>
<OutputPath>bin\Debug\</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Compile Include=`Class%3b1.cs` />
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// ---------------------
// Class1.cs
// ---------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory("Class;1.cs", @"
namespace ClassLibrary16
{
public class Class1
{
}
}
");
MockLogger log = new MockLogger(_testOutput);
ObjectModelHelpers.BuildTempProjectFileExpectSuccess("foo.csproj", log);
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\ClassLibrary16.dll", @"Did not find expected file obj\debug\ClassLibrary16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"obj\debug\ClassLibrary16.pdb", @"Did not find expected file obj\debug\ClassLibrary16.pdb");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bin\debug\ClassLibrary16.dll", @"Did not find expected file bin\debug\ClassLibrary16.dll");
ObjectModelHelpers.AssertFileExistsInTempProjectDirectory(@"bin\debug\ClassLibrary16.pdb", @"Did not find expected file bin\debug\ClassLibrary16.pdb");
log.AssertLogContains(String.Format("foo -> {0}", Path.Combine(ObjectModelHelpers.TempProjectDir, @"bin\Debug\ClassLibrary16.dll")));
}
finally
{
Environment.SetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC", originalOverrideTaskHostVariable);
}
}
#endif
/// <summary>
/// Build a .SLN file using MSBuild. The .SLN and the projects contained within
/// have all sorts of crazy characters in their name. There
/// is even a P2P reference between the two projects in the .SLN.
/// </summary>
[Fact(Skip = "This is a known issue in Roslyn. This test should be enabled if Roslyn is updated for this scenario.")]
public void SolutionWithLotsaCrazyCharacters()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
// ---------------------------------------------------------------------
// Console;!@(foo)'^(Application1.sln
// ---------------------------------------------------------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"SLN;!@(foo)'^1\Console;!@(foo)'^(Application1.sln",
SolutionFileContentsWithUnusualCharacters);
// ---------------------------------------------------------------------
// Console;!@(foo)'^(Application1.csproj
// ---------------------------------------------------------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"SLN;!@(foo)'^1\Console;!@(foo)'^(Application1\Cons.ole;!@(foo)'^(Application1.csproj",
@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<ProductVersion>8.0.50510</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{770F2381-8C39-49E9-8C96-0538FA4349A7}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Console____foo____Application1</RootNamespace>
<AssemblyName>Console%3b!%40%28foo%29%27^%28Application1</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' `>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Release|AnyCPU' `>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Reference Include=`System.Data` />
<Reference Include=`System.Xml` />
</ItemGroup>
<ItemGroup>
<Compile Include=`Program.cs` />
</ItemGroup>
<ItemGroup>
<ProjectReference Include=`..\Class%3b!%40%28foo%29%27^%28Library1\Class%3b!%40%28foo%29%27^%28Library1.csproj`>
<Project>{0B4B78CC-C752-43C2-BE9A-319D20216129}</Project>
<Name>Class%3b!%40%28foo%29%27^%28Library1</Name>
</ProjectReference>
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// ---------------------------------------------------------------------
// Program.cs
// ---------------------------------------------------------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"SLN;!@(foo)'^1\Console;!@(foo)'^(Application1\Program.cs",
@"
using System;
using System.Collections.Generic;
using System.Text;
namespace Console____foo____Application1
{
class Program
{
static void Main(string[] args)
{
Class____foo____Library1.Class1 foo = new Class____foo____Library1.Class1();
}
}
}
");
// ---------------------------------------------------------------------
// Class;!@(foo)'^(Library1.csproj
// ---------------------------------------------------------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"SLN;!@(foo)'^1\Class;!@(foo)'^(Library1\Class;!@(foo)'^(Library1.csproj",
@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<ProductVersion>8.0.50510</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{0B4B78CC-C752-43C2-BE9A-319D20216129}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Class____foo____Library1</RootNamespace>
<AssemblyName>Class%3b!%40%28foo%29%27^%28Library1</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' `>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Release|AnyCPU' `>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Reference Include=`System.Data` />
<Reference Include=`System.Xml` />
</ItemGroup>
<ItemGroup>
<Compile Include=`Class1.cs` />
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// ---------------------------------------------------------------------
// Class1.cs
// ---------------------------------------------------------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"SLN;!@(foo)'^1\Class;!@(foo)'^(Library1\Class1.cs",
@"
namespace Class____foo____Library1
{
public class Class1
{
}
}
");
// Cons.ole;!@(foo)'^(Application1
string targetForFirstProject = "Cons_ole_!__foo__^_Application1";
MockLogger log = new MockLogger(_testOutput);
ObjectModelHelpers.BuildTempProjectFileWithTargetsExpectSuccess(@"SLN;!@(foo)'^1\Console;!@(foo)'^(Application1.sln", new string[] { targetForFirstProject }, null, log);
Assert.True(File.Exists(Path.Combine(ObjectModelHelpers.TempProjectDir, @"SLN;!@(foo)'^1\Console;!@(foo)'^(Application1\bin\debug\Console;!@(foo)'^(Application1.exe"))); // @"Did not find expected file Console;!@(foo)'^(Application1.exe"
}
#if FEATURE_TASKHOST
/// <summary>
/// Build a .SLN file using MSBuild. The .SLN and the projects contained within
/// have all sorts of crazy characters in their name. There
/// is even a P2P reference between the two projects in the .SLN.
/// </summary>
[Fact(Skip = "This is a known issue in Roslyn. This test should be enabled if Roslyn is updated for this scenario.")]
public void SolutionWithLotsaCrazyCharacters_UsingTaskHost()
{
string originalOverrideTaskHostVariable = Environment.GetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC");
try
{
Environment.SetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC", "1");
ObjectModelHelpers.DeleteTempProjectDirectory();
// ---------------------------------------------------------------------
// Console;!@(foo)'^(Application1.sln
// ---------------------------------------------------------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"SLN;!@(foo)'^1\Console;!@(foo)'^(Application1.sln",
SolutionFileContentsWithUnusualCharacters);
// ---------------------------------------------------------------------
// Console;!@(foo)'^(Application1.csproj
// ---------------------------------------------------------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"SLN;!@(foo)'^1\Console;!@(foo)'^(Application1\Cons.ole;!@(foo)'^(Application1.csproj",
@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<ProductVersion>8.0.50510</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{770F2381-8C39-49E9-8C96-0538FA4349A7}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Console____foo____Application1</RootNamespace>
<AssemblyName>Console%3b!%40%28foo%29%27^%28Application1</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' `>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Release|AnyCPU' `>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Reference Include=`System.Data` />
<Reference Include=`System.Xml` />
</ItemGroup>
<ItemGroup>
<Compile Include=`Program.cs` />
</ItemGroup>
<ItemGroup>
<ProjectReference Include=`..\Class%3b!%40%28foo%29%27^%28Library1\Class%3b!%40%28foo%29%27^%28Library1.csproj`>
<Project>{0B4B78CC-C752-43C2-BE9A-319D20216129}</Project>
<Name>Class%3b!%40%28foo%29%27^%28Library1</Name>
</ProjectReference>
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// ---------------------------------------------------------------------
// Program.cs
// ---------------------------------------------------------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"SLN;!@(foo)'^1\Console;!@(foo)'^(Application1\Program.cs",
@"
using System;
using System.Collections.Generic;
using System.Text;
namespace Console____foo____Application1
{
class Program
{
static void Main(string[] args)
{
Class____foo____Library1.Class1 foo = new Class____foo____Library1.Class1();
}
}
}
");
// ---------------------------------------------------------------------
// Class;!@(foo)'^(Library1.csproj
// ---------------------------------------------------------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"SLN;!@(foo)'^1\Class;!@(foo)'^(Library1\Class;!@(foo)'^(Library1.csproj",
@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<PropertyGroup>
<Configuration Condition=` '$(Configuration)' == '' `>Debug</Configuration>
<Platform Condition=` '$(Platform)' == '' `>AnyCPU</Platform>
<ProductVersion>8.0.50510</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{0B4B78CC-C752-43C2-BE9A-319D20216129}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Class____foo____Library1</RootNamespace>
<AssemblyName>Class%3b!%40%28foo%29%27^%28Library1</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' `>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=` '$(Configuration)|$(Platform)' == 'Release|AnyCPU' `>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include=`System` />
<Reference Include=`System.Data` />
<Reference Include=`System.Xml` />
</ItemGroup>
<ItemGroup>
<Compile Include=`Class1.cs` />
</ItemGroup>
<Import Project=`$(MSBuildBinPath)\Microsoft.CSharp.targets` />
</Project>
");
// ---------------------------------------------------------------------
// Class1.cs
// ---------------------------------------------------------------------
ObjectModelHelpers.CreateFileInTempProjectDirectory(
@"SLN;!@(foo)'^1\Class;!@(foo)'^(Library1\Class1.cs",
@"
namespace Class____foo____Library1
{
public class Class1
{
}
}
");
// Cons.ole;!@(foo)'^(Application1
string targetForFirstProject = "Cons_ole_!__foo__^_Application1";
MockLogger log = new MockLogger(_testOutput);
ObjectModelHelpers.BuildTempProjectFileWithTargetsExpectSuccess(@"SLN;!@(foo)'^1\Console;!@(foo)'^(Application1.sln", new string[] { targetForFirstProject }, null, log);
Assert.True(File.Exists(Path.Combine(ObjectModelHelpers.TempProjectDir, @"SLN;!@(foo)'^1\Console;!@(foo)'^(Application1\bin\debug\Console;!@(foo)'^(Application1.exe"))); // @"Did not find expected file Console;!@(foo)'^(Application1.exe"
}
finally
{
Environment.SetEnvironmentVariable("MSBUILDFORCEALLTASKSOUTOFPROC", originalOverrideTaskHostVariable);
}
}
#endif
}
#endif
internal class EscapingInProjectsHelper
{
/// <summary>
/// Deletes all *.weirdo files from the temp path, and dumps 3 files there --
/// a.weirdo, b.weirdo, c.weirdo. This is so that we can exercise our wildcard
/// matching a little bit without having to plumb mock objects all the way through
/// the engine.
/// </summary>
internal static void CreateThreeWeirdoFiles()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
// Create 3 files in the temp path -- a.weirdo, b.weirdo, and c.weirdo.
File.WriteAllText(Path.Combine(ObjectModelHelpers.TempProjectDir, "a.weirdo"), String.Empty);
File.WriteAllText(Path.Combine(ObjectModelHelpers.TempProjectDir, "b.weirdo"), String.Empty);
File.WriteAllText(Path.Combine(ObjectModelHelpers.TempProjectDir, "c.weirdo"), String.Empty);
}
/// <summary>
/// Given a project and an item type, gets the items of that type, and renames an item
/// with the old evaluated include to have the new evaluated include instead.
/// </summary>
/// <param name="project"></param>
/// <param name="itemType"></param>
/// <param name="oldEvaluatedInclude"></param>
/// <param name="newEvaluatedInclude"></param>
internal static IEnumerable<ProjectItem> ModifyItemOfTypeInProject(Project project, string itemType, string oldEvaluatedInclude, string newEvaluatedInclude)
{
IEnumerable<ProjectItem> itemsToMatch = project.GetItems(itemType);
List<ProjectItem> matchingItems = new List<ProjectItem>();
foreach (ProjectItem item in itemsToMatch)
{
if (String.Equals(item.EvaluatedInclude, oldEvaluatedInclude, StringComparison.OrdinalIgnoreCase))
{
matchingItems.Add(item);
}
}
for (int i = 0; i < matchingItems.Count; i++)
{
matchingItems[i].Rename(newEvaluatedInclude);
}
return matchingItems;
}
/// <summary>
/// Helper for SpecialCharactersInMetadataValue tests
/// </summary>
internal static void SpecialCharactersInMetadataValueTests(ProjectItem item)
{
Assert.Equal("%3B", item.GetMetadata("EscapedSemicolon").UnevaluatedValue);
Assert.Equal("%3B", item.GetMetadata("EscapedSemicolon").EvaluatedValueEscaped);
Assert.Equal(";", item.GetMetadata("EscapedSemicolon").EvaluatedValue);
Assert.Equal("%3B", Project.GetMetadataValueEscaped(item, "EscapedSemicolon"));
Assert.Equal(";", item.GetMetadataValue("EscapedSemicolon"));
Assert.Equal("%24", item.GetMetadata("EscapedDollarSign").UnevaluatedValue);
Assert.Equal("%24", item.GetMetadata("EscapedDollarSign").EvaluatedValueEscaped);
Assert.Equal("$", item.GetMetadata("EscapedDollarSign").EvaluatedValue);
Assert.Equal("%24", Project.GetMetadataValueEscaped(item, "EscapedDollarSign"));
Assert.Equal("$", item.GetMetadataValue("EscapedDollarSign"));
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace OAuthDemoAppWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using log4net.Core;
using log4net.Util;
namespace Umbraco.Core.Logging
{
/// <summary>
/// An asynchronous appender based on <see cref="BlockingCollection{T}"/>
/// </summary>
/// <remarks>
/// Based on https://github.com/cjbhaines/Log4Net.Async
/// </remarks>
public class ParallelForwardingAppender : AsyncForwardingAppenderBase, IDisposable
{
#region Private Members
private const int DefaultBufferSize = 1000;
private BlockingCollection<LoggingEventContext> _loggingEvents;
private CancellationTokenSource _loggingCancelationTokenSource;
private CancellationToken _loggingCancelationToken;
private Task _loggingTask;
private Double _shutdownFlushTimeout = 1;
private TimeSpan _shutdownFlushTimespan = TimeSpan.FromSeconds(1);
private static readonly Type ThisType = typeof(ParallelForwardingAppender);
private volatile bool _shutDownRequested;
private int? _bufferSize = DefaultBufferSize;
#endregion Private Members
#region Properties
/// <summary>
/// Gets or sets the number of LoggingEvents that will be buffered. Set to null for unlimited.
/// </summary>
public override int? BufferSize
{
get { return _bufferSize; }
set { _bufferSize = value; }
}
public int BufferEntryCount
{
get
{
if (_loggingEvents == null) return 0;
return _loggingEvents.Count;
}
}
/// <summary>
/// Gets or sets the time period in which the system will wait for appenders to flush before canceling the background task.
/// </summary>
public Double ShutdownFlushTimeout
{
get
{
return _shutdownFlushTimeout;
}
set
{
_shutdownFlushTimeout = value;
}
}
protected override string InternalLoggerName
{
get { return "ParallelForwardingAppender"; }
}
#endregion Properties
#region Startup
public override void ActivateOptions()
{
base.ActivateOptions();
_shutdownFlushTimespan = TimeSpan.FromSeconds(_shutdownFlushTimeout);
StartForwarding();
}
private void StartForwarding()
{
if (_shutDownRequested)
{
return;
}
//Create a collection which will block the thread and wait for new entries
//if the collection is empty
if (BufferSize.HasValue && BufferSize > 0)
{
_loggingEvents = new BlockingCollection<LoggingEventContext>(BufferSize.Value);
}
else
{
//No limit on the number of events.
_loggingEvents = new BlockingCollection<LoggingEventContext>();
}
//The cancellation token is used to cancel a running task gracefully.
_loggingCancelationTokenSource = new CancellationTokenSource();
_loggingCancelationToken = _loggingCancelationTokenSource.Token;
_loggingTask = new Task(SubscriberLoop, _loggingCancelationToken);
_loggingTask.Start();
}
#endregion Startup
#region Shutdown
private void CompleteSubscriberTask()
{
_shutDownRequested = true;
if (_loggingEvents == null || _loggingEvents.IsAddingCompleted)
{
return;
}
//Don't allow more entries to be added.
_loggingEvents.CompleteAdding();
//Allow some time to flush
Thread.Sleep(_shutdownFlushTimespan);
if (!_loggingTask.IsCompleted && !_loggingCancelationToken.IsCancellationRequested)
{
_loggingCancelationTokenSource.Cancel();
//Wait here so that the error logging messages do not get into a random order.
//Don't pass the cancellation token because we are not interested
//in catching the OperationCanceledException that results.
_loggingTask.Wait();
}
if (!_loggingEvents.IsCompleted)
{
ForwardInternalError("The buffer was not able to be flushed before timeout occurred.", null, ThisType);
}
}
protected override void OnClose()
{
CompleteSubscriberTask();
base.OnClose();
}
#endregion Shutdown
#region Appending
protected override void Append(LoggingEvent loggingEvent)
{
if (_loggingEvents == null || _loggingEvents.IsAddingCompleted || loggingEvent == null)
{
return;
}
loggingEvent.Fix = Fix;
//In the case where blocking on a full collection, and the task is subsequently completed, the cancellation token
//will prevent the entry from attempting to add to the completed collection which would result in an exception.
_loggingEvents.Add(new LoggingEventContext(loggingEvent), _loggingCancelationToken);
}
protected override void Append(LoggingEvent[] loggingEvents)
{
if (_loggingEvents == null || _loggingEvents.IsAddingCompleted || loggingEvents == null)
{
return;
}
foreach (var loggingEvent in loggingEvents)
{
Append(loggingEvent);
}
}
#endregion Appending
#region Forwarding
/// <summary>
/// Iterates over a BlockingCollection containing LoggingEvents.
/// </summary>
private void SubscriberLoop()
{
Thread.CurrentThread.Name = String.Format("{0} ParallelForwardingAppender Subscriber Task", Name);
//The task will continue in a blocking loop until
//the queue is marked as adding completed, or the task is canceled.
try
{
//This call blocks until an item is available or until adding is completed
foreach (var entry in _loggingEvents.GetConsumingEnumerable(_loggingCancelationToken))
{
ForwardLoggingEvent(entry.LoggingEvent, ThisType);
}
}
catch (OperationCanceledException ex)
{
//The thread was canceled before all entries could be forwarded and the collection completed.
ForwardInternalError("Subscriber task was canceled before completion.", ex, ThisType);
//Cancellation is called in the CompleteSubscriberTask so don't call that again.
}
catch (ThreadAbortException ex)
{
//Thread abort may occur on domain unload.
ForwardInternalError("Subscriber task was aborted.", ex, ThisType);
//Cannot recover from a thread abort so complete the task.
CompleteSubscriberTask();
//The exception is swallowed because we don't want the client application
//to halt due to a logging issue.
}
catch (Exception ex)
{
//On exception, try to log the exception
ForwardInternalError("Subscriber task error in forwarding loop.", ex, ThisType);
//Any error in the loop is going to be some sort of extenuating circumstance from which we
//probably cannot recover anyway. Complete subscribing.
CompleteSubscriberTask();
}
}
#endregion Forwarding
#region IDisposable Implementation
private bool _disposed = false;
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_loggingTask != null)
{
if (!(_loggingTask.IsCanceled || _loggingTask.IsCompleted || _loggingTask.IsFaulted))
{
try
{
CompleteSubscriberTask();
}
catch (Exception ex)
{
LogLog.Error(ThisType, "Exception Completing Subscriber Task in Dispose Method", ex);
}
}
try
{
_loggingTask.Dispose();
}
catch (Exception ex)
{
LogLog.Error(ThisType, "Exception Disposing Logging Task", ex);
}
finally
{
_loggingTask = null;
}
}
if (_loggingEvents != null)
{
try
{
_loggingEvents.Dispose();
}
catch (Exception ex)
{
LogLog.Error(ThisType, "Exception Disposing BlockingCollection", ex);
}
finally
{
_loggingEvents = null;
}
}
if (_loggingCancelationTokenSource != null)
{
try
{
_loggingCancelationTokenSource.Dispose();
}
catch (Exception ex)
{
LogLog.Error(ThisType, "Exception Disposing CancellationTokenSource", ex);
}
finally
{
_loggingCancelationTokenSource = null;
}
}
}
_disposed = true;
}
}
// Use C# destructor syntax for finalization code.
~ParallelForwardingAppender()
{
// Simply call Dispose(false).
Dispose(false);
}
#endregion IDisposable Implementation
}
}
| |
/*
* 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 Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Physics.POSPlugin
{
public class POSCharacter : PhysicsActor
{
private Vector3 _position;
public Vector3 _velocity;
public Vector3 _target_velocity = Vector3.Zero;
public Vector3 _size = Vector3.Zero;
private Vector3 _acceleration;
private Vector3 m_rotationalVelocity = Vector3.Zero;
private bool flying;
private bool isColliding;
public POSCharacter()
{
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Agent; }
set { return; }
}
public override Vector3 RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override uint LocalID
{
set { return; }
}
public override bool Grabbed
{
set { return; }
}
public override bool Selected
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool Flying
{
get { return flying; }
set { flying = value; }
}
public override bool IsColliding
{
get { return isColliding; }
set { isColliding = value; }
}
public override bool CollidingGround
{
get { return false; }
set { return; }
}
public override bool CollidingObj
{
get { return false; }
set { return; }
}
public override bool Stopped
{
get { return false; }
}
public override Vector3 Position
{
get { return _position; }
set { _position = value; }
}
public override Vector3 Size
{
get { return _size; }
set
{
_size = value;
_size.Z = _size.Z / 2.0f;
}
}
public override float Mass
{
get { return 0f; }
}
public override Vector3 Force
{
get { return Vector3.Zero; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, Vector3 value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void SetVolumeDetect(int param)
{
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 GeometricCenter
{
get { return Vector3.Zero; }
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override Vector3 Velocity
{
get { return _velocity; }
set { _target_velocity = value; }
}
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set { }
}
public override Vector3 Acceleration
{
get { return _acceleration; }
}
public override bool Kinematic
{
get { return true; }
set { }
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(Vector3 axis)
{
}
public void SetAcceleration(Vector3 accel)
{
_acceleration = accel;
}
public override void AddForce(Vector3 force, bool pushforce)
{
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
public override void SetMomentum(Vector3 momentum)
{
}
public override void CrossingFailure()
{
}
public override Vector3 PIDTarget
{
set { return; }
}
public override bool PIDActive
{
set { return; }
}
public override float PIDTau
{
set { return; }
}
public override float PIDHoverHeight
{
set { return; }
}
public override bool PIDHoverActive
{
set { return; }
}
public override PIDHoverType PIDHoverType
{
set { return; }
}
public override float PIDHoverTau
{
set { return; }
}
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
}
}
| |
// Copyright(c) 2017 Takahiro Miyaura
// Released under the MIT license
// http://opensource.org/licenses/mit-license.php
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Com.Reseul.Apis.Services.CognitiveService.Translators.UWP.Entities;
using Windows.Data.Json;
namespace Com.Reseul.Apis.Services.CognitiveService.Translators.UWP.Services
{
/// <summary>
/// Class providing real time translation function using Translator that cognitive Service API provided.
/// </summary>
public class CognitiveTranslatorService
{
#region TokenService
/// <summary>
/// Request a token to the service.
/// </summary>
/// <returns>Access token.</returns>
private async Task<string> RequestToken()
{
if (string.IsNullOrEmpty(_subscriptionKey))
throw new ArgumentNullException("SubscriptionKey");
var query = new StringBuilder();
query.Append("Subscription-Key=").Append(_subscriptionKey);
var httpClient = new HttpClient();
var stringContent = new StringContent("");
using (var httpResponseMessage = await httpClient.PostAsync(TokenUrl + query, stringContent))
{
using (var stream = await httpResponseMessage.Content.ReadAsStreamAsync())
{
if (stream != null)
using (var reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
{
return reader.ReadToEnd();
}
}
}
return string.Empty;
}
#endregion
#region private Field
/// <summary>
/// Translator WebSocket Url
/// </summary>
private const string SpeechTranslateUrl = @"wss://dev.microsofttranslator.com/speech/translate?";
/// <summary>
/// Translator Language Info Service Url
/// </summary>
private const string LanguageUrl = "https://dev.microsofttranslator.com/languages?";
/// <summary>
/// Cognitive Service API Token Service Url
/// </summary>
private const string TokenUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken?";
/// <summary>
/// Cognitive Service API version.
/// </summary>
private const string API_VERSION = "1.0";
/// <summary>
/// Connect to Cognitive Service API at regular intervals.
/// </summary>
private Timer _connectionTimer;
/// <summary>
/// Proxy server address.
/// </summary>
private static Uri _proxyAddress;
/// <summary>
/// Proxy server username
/// </summary>
private static string _proxyUserName;
/// <summary>
/// Proxy server user password.
/// </summary>
private static string _proxyPassword;
/// <summary>
/// Cognitive Service API - Translator API subscription key.
/// </summary>
private readonly string _subscriptionKey;
/// <summary>
/// number of the wave audio channels.
/// </summary>
private readonly short _channels;
/// <summary>
/// number of the wave audio sample rate.
/// </summary>
private readonly int _sampleRate;
/// <summary>
/// number of the wave audio bit per sample.
/// </summary>
private readonly short _bitsPerSample;
/// <summary>
/// Toekn of Cognitive Service API
/// </summary>
private string _token;
/// <summary>
/// a thread to periodically send data to the cognitive service API.
/// </summary>
private Task _dataStreamingSendThread;
/// <summary>
/// Clear buffer data of Sppech.
/// </summary>
private bool _ClearBuffer;
/// <summary>
/// When Service initialize is true,websocket initialize.
/// </summary>
private bool _isInitializing;
/// <summary>
/// interval milliseconds of re-connection.
/// </summary>
private readonly double _connectionInterval = 9 * 60 * 1000;
#endregion
#region Event
/// <summary>
/// Occurs when the Cpgnitive Service API receives a message.
/// </summary>
public EventHandler<MessageWebSocketMessageReceivedEventArgs> OnRootMessage;
/// <summary>
/// Occurs when the Cpgnitive Service API receives a message of translated text.
/// </summary>
public EventHandler<MessageWebSocketMessageReceivedEventArgs> OnTextMessage;
/// <summary>
/// Occurs when the Cpgnitive Service API receives a message of translated voice data(wave).
/// </summary>
public EventHandler<MessageWebSocketMessageReceivedEventArgs> OnVoiceMessage;
/// <summary>
/// WebSockect object.
/// </summary>
private MessageWebSocket webSocket;
/// <summary>
/// Buffered send data.
/// </summary>
private DataWriter dataWriter;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CognitiveTranslatorService" /> class to the value indicated by a
/// subscription key of Translator Speech API,and a proxy server information,and wave audio parameters.
/// </summary>
/// <param name="subscriptionKey">Subscription Key of Translator Speech API</param>
/// <param name="proxyUserName">Proxy User Name.(If the proxy server requires)</param>
/// <param name="proxyPassword">Proxy User Password.(If the proxy server requires)</param>
/// <param name="channels">number of the wave audio channels.</param>
/// <param name="samplerate">number of the wave audio sample rate.</param>
/// <param name="bitsPerSample">number of the wave audio bit per sample.</param>
public CognitiveTranslatorService(string subscriptionKey, string proxyUserName,
string proxyPassword, short channels, int samplerate, short bitsPerSample)
{
_subscriptionKey = subscriptionKey;
_proxyUserName = proxyUserName;
_proxyPassword = proxyPassword;
_channels = channels;
_sampleRate = samplerate;
_bitsPerSample = bitsPerSample;
if (!string.IsNullOrEmpty(_proxyUserName) && !string.IsNullOrEmpty(_proxyPassword))
WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(_proxyUserName, _proxyPassword);
}
/// <summary>
/// Initializes a new instance of the <see cref="CognitiveTranslatorService" /> class to the value indicated by a
/// subscription key of Translator Speech API,and streaming parameters.
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="CognitiveTranslatorService" /> class to the value indicated by a
/// subscription key of Translator Speech API,and streaming parameters.
/// WebSocket execute no proxy.
/// </remarks>
/// <param name="subscriptionKey">Subscription Key of Translator Speech API</param>
/// <param name="channels">number of the wave audio channels.</param>
/// <param name="samplerate">number of the wave audio sample rate.</param>
/// <param name="bitsPerSample">number of the wave audio bit per sample.</param>
public CognitiveTranslatorService(string subscriptionKey, short channels, int samplerate, short bitsPerSample)
: this(subscriptionKey, null, null, channels, samplerate, bitsPerSample)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CognitiveTranslatorService" /> class to the value indicated by a
/// subscription key of Translator Speech API
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="CognitiveTranslatorService" /> class to the value indicated by a
/// subscription key of Translator Speech API,and streaming parameters.
/// WebSocket execute no proxy,and rate of wave audio is 1channel,16Khz,16bit.
/// </remarks>
/// <param name="subscriptionKey">Subscription Key of Translator Speech API</param>
public CognitiveTranslatorService(string subscriptionKey)
: this(subscriptionKey, null, null, 1, 16000, 16)
{
}
#endregion
#region WebSocket
/// <summary>
/// Connect to the server before sending audio
/// It will get the authentication credentials and add it to the header
/// </summary>
/// <param name="from">sets the launguage of source.(<see cref="SpeechLanguageInfo.Language" />)</param>
/// <param name="to">sets the launguage of translated results.(<see cref="SpeechLanguageInfo.Language" />)</param>
/// <param name="voice">if you get to speech of translated result, sets the value of <see cref="SpeechTtsInfo.Id" />. </param>
public async Task Connect(string from, string to, string voice)
{
if (to == null) throw new ArgumentNullException("to");
if (from == null) throw new ArgumentNullException("from");
if (webSocket != null)
{
webSocket.Dispose();
webSocket = null;
}
if (_connectionTimer != null)
{
_connectionTimer.Dispose();
_connectionTimer = null;
}
webSocket = new MessageWebSocket();
// Get Azure authentication token
var bearerToken = await RequestToken();
webSocket.SetRequestHeader("Authorization", "Bearer " + bearerToken);
var query = new StringBuilder();
query.Append("from=").Append(from);
query.Append("&to=").Append(to);
if (!string.IsNullOrEmpty(voice))
query.Append("&features=texttospeech&voice=").Append(voice);
query.Append("&api-version=").Append(API_VERSION);
webSocket.MessageReceived += WebSocket_MessageReceived;
// setup the data writer
dataWriter = new DataWriter(webSocket.OutputStream);
dataWriter.ByteOrder = ByteOrder.LittleEndian;
dataWriter.WriteBytes(GetWaveHeader());
// connect to the service
await webSocket.ConnectAsync(new Uri(SpeechTranslateUrl + query));
//// flush the dataWriter periodically
_connectionTimer = new Timer(async s =>
{
if (dataWriter.UnstoredBufferLength > 0)
{
await dataWriter.StoreAsync();
}
// reset the timer
_connectionTimer.Change(TimeSpan.FromMilliseconds(250), Timeout.InfiniteTimeSpan);
},
null, TimeSpan.FromMilliseconds(250), Timeout.InfiniteTimeSpan);
}
/// <summary>
/// An event that indicates that a message was received on the MessageWebSocket object.
/// </summary>
/// <param name="sender">The event source.</param>
/// <param name="args">The event data. If there is no event data, this parameter will be null.</param>
private void WebSocket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
{
if (OnRootMessage != null)
OnRootMessage(sender, args);
if (args.MessageType == SocketMessageType.Binary)
{
if (OnVoiceMessage != null)
OnVoiceMessage(sender, args);
}
else
{
if (OnTextMessage != null)
OnTextMessage(sender, args);
}
}
/// <summary>
/// add wave sampling data.
/// </summary>
/// <param name="buffer">The buffer to write data from. </param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing data from the current stream.</param>
/// <param name="count">The maximum number of bytes to read. </param>
public void AddSamplingData(byte[] buffer, int offset, int count)
{
dataWriter.WriteBytes(buffer);
}
#endregion
#region Languages
/// <summary>
/// Gets speech informations that Cognitive Service API can provide.
/// </summary>
/// <returns><see cref="SpeechLanguageInfo" /> object list.</returns>
public static async Task<ReadOnlyCollection<SpeechLanguageInfo>> GetSpeechLanguageInfo()
{
IEnumerable<SpeechLanguageInfo> speechLanguageInfos = null;
var query = new StringBuilder();
query.Append("api-version=").Append(API_VERSION);
query.Append("&scope=").Append("speech");
var httpClient = new HttpClient();
using (var httpResponseMessage = await httpClient.GetAsync(LanguageUrl + query))
{
using (var stream = await httpResponseMessage.Content.ReadAsStreamAsync())
{
if (stream != null)
using (var reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
{
var json = reader.ReadToEnd();
var jsonObject = JsonObject.Parse(json);
speechLanguageInfos = jsonObject["speech"].GetObject().Select(
x => new SpeechLanguageInfo()
{
LocaleId = x.Key,
Language = x.Value.GetObject()["language"].GetString(),
Name = x.Value.GetObject()["name"].GetString()
});
}
}
}
return new ReadOnlyCollection<SpeechLanguageInfo>(speechLanguageInfos.ToArray());
}
/// <summary>
/// Gets tts informations that Cognitive Service API can provide.
/// </summary>
/// <returns><see cref="SpeechTtsInfo" /> object list.</returns>
public static async Task<ReadOnlyCollection<SpeechTtsInfo>> GetSpeechTtsInfo()
{
IEnumerable<SpeechTtsInfo> speechTtsInfos = null;
var query = new StringBuilder();
query.Append("api-version=").Append(API_VERSION);
query.Append("&scope=").Append("tts");
var httpClient = new HttpClient();
using (var httpResponseMessage = await httpClient.GetAsync(LanguageUrl + query))
{
using (var stream = await httpResponseMessage.Content.ReadAsStreamAsync())
{
if (stream != null)
using (var reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
{
var json = reader.ReadToEnd();
var jsonObject = JsonObject.Parse(json);
speechTtsInfos = jsonObject["tts"].GetObject().Select(
x => new SpeechTtsInfo()
{
Id = x.Key,
Gender = x.Value.GetObject()["gender"].GetString(),
Locale = x.Value.GetObject()["locale"].GetString(),
LanguageName = x.Value.GetObject()["languageName"].GetString(),
DisplayName = x.Value.GetObject()["displayName"].GetString(),
RegionName = x.Value.GetObject()["regionName"].GetString(),
Language = x.Value.GetObject()["language"].GetString()
});
}
}
}
return new ReadOnlyCollection<SpeechTtsInfo>(speechTtsInfos.ToArray());
}
/// <summary>
/// Gets speech text informations that Cognitive Service API can provide.
/// </summary>
/// <returns><see cref="SpeechTextInfo" /> object list.</returns>
public static async Task<ReadOnlyCollection<SpeechTextInfo>> GetSpeechTextInfo()
{
IEnumerable<SpeechTextInfo> speechTextInfos = null;
var query = new StringBuilder();
query.Append("api-version=").Append(API_VERSION);
query.Append("&scope=").Append("text");
var httpClient = new HttpClient();
using (var httpResponseMessage = await httpClient.GetAsync(LanguageUrl + query))
{
using (var stream = await httpResponseMessage.Content.ReadAsStreamAsync())
{
if (stream != null)
using (var reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
{
var json = reader.ReadToEnd();
var jsonObject = JsonObject.Parse(json);
speechTextInfos = jsonObject["text"].GetObject().Select(
x => new SpeechTextInfo()
{
Id = x.Key,
Dir = x.Value.GetObject()["dir"].GetString(),
Locale = x.Value.GetObject()["name"].GetString(),
});
}
}
}
return new ReadOnlyCollection<SpeechTextInfo>(speechTextInfos.ToArray());
}
#endregion
#region Commons
/// <summary>
/// Create a RIFF Wave Header for PCM 16bit 16kHz Mono
/// </summary>
/// <returns></returns>
private byte[] GetWaveHeader()
{
var extraSize = 0;
var blockAlign = (short) (_channels * (_bitsPerSample / 8));
var averageBytesPerSecond = _sampleRate * blockAlign;
using (var stream = new MemoryStream())
{
var writer = new BinaryWriter(stream, Encoding.UTF8);
writer.Write(Encoding.UTF8.GetBytes("RIFF"));
writer.Write(0);
writer.Write(Encoding.UTF8.GetBytes("WAVE"));
writer.Write(Encoding.UTF8.GetBytes("fmt "));
writer.Write(18 + extraSize);
writer.Write((short) 1);
writer.Write(_channels);
writer.Write(_sampleRate);
writer.Write(averageBytesPerSecond);
writer.Write(blockAlign);
writer.Write(_bitsPerSample);
writer.Write((short) extraSize);
writer.Write(Encoding.UTF8.GetBytes("data"));
writer.Write(0);
stream.Position = 0;
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
return buffer;
}
}
#endregion
}
}
| |
// ---------------------------------------------------------------------------
// Copyright (C) 2006 Microsoft Corporation All Rights Reserved
// ---------------------------------------------------------------------------
#define CODE_ANALYSIS
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace System.Workflow.Activities.Rules.Design
{
#region class RuleSetDialog
public partial class RuleSetDialog : Form
{
#region members and constructors
private RuleSet dialogRuleSet;
//private IServiceProvider serviceProvider = null;//will always be null
private Parser ruleParser;
private const int numCols = 4;
private bool[] sortOrder = new bool[numCols] { false, false, false, false };
public RuleSetDialog(Type activityType, RuleSet ruleSet, string[] assemblyPaths = null)
{
if (activityType == null)
throw (new ArgumentNullException("activityType"));
InitializeDialog(ruleSet);
RuleValidation validation = new RuleValidation(activityType);
this.ruleParser = new Parser(validation, assemblyPaths);
}
private void InitializeDialog(RuleSet ruleSet)
{
InitializeComponent();
this.conditionTextBox.PopulateAutoCompleteList += new EventHandler<AutoCompletionEventArgs>(PopulateAutoCompleteList);
this.thenTextBox.PopulateAutoCompleteList += new EventHandler<AutoCompletionEventArgs>(PopulateAutoCompleteList);
this.elseTextBox.PopulateAutoCompleteList += new EventHandler<AutoCompletionEventArgs>(PopulateAutoCompleteList);
this.conditionTextBox.PopulateToolTipList += new EventHandler<AutoCompletionEventArgs>(PopulateAutoCompleteList);
this.thenTextBox.PopulateToolTipList += new EventHandler<AutoCompletionEventArgs>(PopulateAutoCompleteList);
this.elseTextBox.PopulateToolTipList += new EventHandler<AutoCompletionEventArgs>(PopulateAutoCompleteList);
this.reevaluationComboBox.Items.Add(Messages.ReevaluationNever);
this.reevaluationComboBox.Items.Add(Messages.ReevaluationAlways);
this.chainingBehaviourComboBox.Items.Add(Messages.Sequential);
this.chainingBehaviourComboBox.Items.Add(Messages.ExplicitUpdateOnly);
this.chainingBehaviourComboBox.Items.Add(Messages.FullChaining);
this.HelpRequested += new HelpEventHandler(OnHelpRequested);
this.HelpButtonClicked += new CancelEventHandler(OnHelpClicked);
if (ruleSet != null)
this.dialogRuleSet = ruleSet.Clone();
else
this.dialogRuleSet = new RuleSet();
this.chainingBehaviourComboBox.SelectedIndex = (int)this.dialogRuleSet.ChainingBehavior;
this.rulesListView.Select();
foreach (Rule rule in this.dialogRuleSet.Rules)
this.AddNewItem(rule);
if (this.rulesListView.Items.Count > 0)
this.rulesListView.Items[0].Selected = true;
else
RulesListView_SelectedIndexChanged(this, new EventArgs());
}
#endregion
#region public members
public RuleSet RuleSet
{
get
{
return this.dialogRuleSet;
}
}
#endregion
#region event handlers
private void PopulateAutoCompleteList(object sender, AutoCompletionEventArgs e)
{
e.AutoCompleteValues = this.ruleParser.GetExpressionCompletions(e.Prefix);
}
private void RulesListView_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.rulesListView.SelectedItems.Count > 0)
{
Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule;
this.nameTextBox.Enabled = true;
this.activeCheckBox.Enabled = true;
this.reevaluationComboBox.Enabled = true;
this.priorityTextBox.Enabled = true;
this.conditionTextBox.Enabled = true;
this.thenTextBox.Enabled = true;
this.elseTextBox.Enabled = true;
this.nameTextBox.Text = rule.Name;
this.activeCheckBox.Checked = rule.Active;
this.reevaluationComboBox.SelectedIndex = (int)rule.ReevaluationBehavior;
this.priorityTextBox.Text = rule.Priority.ToString(CultureInfo.CurrentCulture);
//Condition
this.conditionTextBox.Text = rule.Condition != null ? rule.Condition.ToString().Replace("\n", "\r\n") : string.Empty;
try
{
this.ruleParser.ParseCondition(this.conditionTextBox.Text);
conditionErrorProvider.SetError(this.conditionTextBox, string.Empty);
}
catch (RuleSyntaxException ex)
{
conditionErrorProvider.SetError(this.conditionTextBox, ex.Message);
}
//Then
this.thenTextBox.Text = GetActionsString(rule.ThenActions);
try
{
this.ruleParser.ParseStatementList(this.thenTextBox.Text);
thenErrorProvider.SetError(this.thenTextBox, string.Empty);
}
catch (RuleSyntaxException ex)
{
thenErrorProvider.SetError(this.thenTextBox, ex.Message);
}
//Else
this.elseTextBox.Text = GetActionsString(rule.ElseActions);
try
{
this.ruleParser.ParseStatementList(this.elseTextBox.Text);
elseErrorProvider.SetError(this.elseTextBox, string.Empty);
}
catch (RuleSyntaxException ex)
{
elseErrorProvider.SetError(this.elseTextBox, ex.Message);
}
this.deleteToolStripButton.Enabled = true;
}
else
{
this.nameTextBox.Text = string.Empty;
this.activeCheckBox.Checked = false;
this.reevaluationComboBox.Text = string.Empty;
this.priorityTextBox.Text = string.Empty;
this.conditionTextBox.Text = string.Empty;
this.thenTextBox.Text = string.Empty;
this.elseTextBox.Text = string.Empty;
this.nameTextBox.Enabled = false;
this.activeCheckBox.Enabled = false;
this.reevaluationComboBox.Enabled = false;
this.priorityTextBox.Enabled = false;
this.conditionTextBox.Enabled = false;
this.thenTextBox.Enabled = false;
this.elseTextBox.Enabled = false;
conditionErrorProvider.SetError(this.conditionTextBox, string.Empty);
thenErrorProvider.SetError(this.thenTextBox, string.Empty);
elseErrorProvider.SetError(this.elseTextBox, string.Empty);
this.deleteToolStripButton.Enabled = false;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ConditionTextBox_Validating(object sender, CancelEventArgs e)
{
if (this.rulesListView.SelectedItems.Count == 0)
return;
try
{
Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule;
RuleCondition ruleCondition = this.ruleParser.ParseCondition(this.conditionTextBox.Text);
rule.Condition = ruleCondition;
if (!string.IsNullOrEmpty(this.conditionTextBox.Text))
this.conditionTextBox.Text = ruleCondition.ToString().Replace("\n", "\r\n");
UpdateItem(this.rulesListView.SelectedItems[0], rule);
conditionErrorProvider.SetError(this.conditionTextBox, string.Empty);
}
catch (Exception ex)
{
conditionErrorProvider.SetError(this.conditionTextBox, ex.Message);
DesignerHelpers.DisplayError(Messages.Error_ConditionParser + "\n" + ex.Message, this.Text);
e.Cancel = true;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ThenTextBox_Validating(object sender, CancelEventArgs e)
{
if (this.rulesListView.SelectedItems.Count == 0)
return;
try
{
Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule;
List<RuleAction> ruleThenActions = this.ruleParser.ParseStatementList(this.thenTextBox.Text);
this.thenTextBox.Text = GetActionsString(ruleThenActions);
rule.ThenActions.Clear();
foreach (RuleAction ruleAction in ruleThenActions)
rule.ThenActions.Add(ruleAction);
UpdateItem(this.rulesListView.SelectedItems[0], rule);
thenErrorProvider.SetError(this.thenTextBox, string.Empty);
}
catch (Exception ex)
{
thenErrorProvider.SetError(this.thenTextBox, ex.Message);
DesignerHelpers.DisplayError(Messages.Error_ActionsParser + "\n" + ex.Message, this.Text);
e.Cancel = true;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ElseTextBox_Validating(object sender, CancelEventArgs e)
{
if (this.rulesListView.SelectedItems.Count == 0)
return;
try
{
Rule rule = (Rule)this.rulesListView.SelectedItems[0].Tag;
List<RuleAction> ruleElseActions = this.ruleParser.ParseStatementList(this.elseTextBox.Text);
this.elseTextBox.Text = GetActionsString(ruleElseActions);
rule.ElseActions.Clear();
foreach (RuleAction ruleAction in ruleElseActions)
rule.ElseActions.Add(ruleAction);
UpdateItem(this.rulesListView.SelectedItems[0], rule);
elseErrorProvider.SetError(this.elseTextBox, string.Empty);
}
catch (Exception ex)
{
elseErrorProvider.SetError(this.elseTextBox, ex.Message);
DesignerHelpers.DisplayError(Messages.Error_ActionsParser + "\n" + ex.Message, this.Text);
e.Cancel = true;
}
}
private void NewRuleToolStripButton_Click(object sender, EventArgs e)
{
// verify to run validation first
if (this.rulesToolStrip.Focus())
{
Rule newRule = new Rule
{
Name = CreateNewName()
};
this.dialogRuleSet.Rules.Add(newRule);
ListViewItem listViewItem = AddNewItem(newRule);
listViewItem.Selected = true;
listViewItem.Focused = true;
int index = rulesListView.Items.IndexOf(listViewItem);
rulesListView.EnsureVisible(index);
}
}
private void DeleteToolStripButton_Click(object sender, EventArgs e)
{
if (this.ActiveControl is IntellisenseTextBox itb)
itb.HideIntellisenceDropDown();
MessageBoxOptions mbo = (MessageBoxOptions)0;
if (CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft)
mbo = MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading;
DialogResult dr = MessageBox.Show(this, Messages.RuleConfirmDeleteMessageText, Messages.DeleteRule,
MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, mbo);
if (dr == DialogResult.OK)
{
Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule;
int selectionIndex = this.rulesListView.SelectedIndices[0];
this.dialogRuleSet.Rules.Remove(rule);
this.rulesListView.Items.RemoveAt(selectionIndex);
if (this.rulesListView.Items.Count > 0)
{
int newSelectionIndex = Math.Min(selectionIndex, this.rulesListView.Items.Count - 1);
this.rulesListView.Items[newSelectionIndex].Selected = true;
}
}
}
private void NameTextBox_Validating(object sender, CancelEventArgs e)
{
if (this.rulesListView.SelectedItems.Count > 0)
{
Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule;
if (this.nameTextBox.Text != rule.Name)
{
string ruleName = this.nameTextBox.Text;
if (string.IsNullOrEmpty(ruleName))
{
e.Cancel = true;
DesignerHelpers.DisplayError(Messages.Error_RuleNameIsEmpty, this.Text);
}
else if (rule.Name == ruleName)
{
this.nameTextBox.Text = ruleName;
}
else if (!IsUniqueIdentifier(ruleName))
{
e.Cancel = true;
DesignerHelpers.DisplayError(Messages.Error_DuplicateRuleName, this.Text);
}
else
{
rule.Name = ruleName;
UpdateItem(this.rulesListView.SelectedItems[0], rule);
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void PriorityTextBox_Validating(object sender, CancelEventArgs e)
{
if (this.rulesListView.SelectedItems.Count > 0)
{
Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule;
try
{
rule.Priority = int.Parse(this.priorityTextBox.Text, CultureInfo.CurrentCulture);
UpdateItem(this.rulesListView.SelectedItems[0], rule);
}
catch
{
e.Cancel = true;
DesignerHelpers.DisplayError(Messages.Error_InvalidPriority, this.Text);
}
}
}
private void ActiveCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (this.rulesListView.SelectedItems.Count > 0)
{
Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule;
rule.Active = this.activeCheckBox.Checked;
UpdateItem(this.rulesListView.SelectedItems[0], rule);
}
}
private void ReevaluationComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.rulesListView.SelectedItems.Count > 0)
{
Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule;
rule.ReevaluationBehavior = (RuleReevaluationBehavior)this.reevaluationComboBox.SelectedIndex;
UpdateItem(this.rulesListView.SelectedItems[0], rule);
}
}
private void ChainingBehaviourComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
this.dialogRuleSet.ChainingBehavior = (RuleChainingBehavior)this.chainingBehaviourComboBox.SelectedIndex;
}
private void RulesListView_ColumnClick(object sender, ColumnClickEventArgs e)
{
if (e.Column < numCols)
{
this.rulesListView.ListViewItemSorter = new ListViewItemComparer(e.Column, sortOrder[e.Column]);
sortOrder[e.Column] = !sortOrder[e.Column];
}
}
#endregion
#region private helpers
private ListViewItem AddNewItem(Rule rule)
{
ListViewItem listViewItem = new ListViewItem(new string[] { rule.Name, String.Empty, String.Empty, String.Empty, String.Empty });
this.rulesListView.Items.Add(listViewItem);
listViewItem.Tag = rule;
UpdateItem(listViewItem, rule);
return listViewItem;
}
private void UpdateItem(ListViewItem listViewItem, Rule rule)
{
listViewItem.SubItems[0].Text = rule.Name;
listViewItem.SubItems[1].Text = rule.Priority.ToString(CultureInfo.CurrentCulture);
listViewItem.SubItems[2].Text = (string)this.reevaluationComboBox.Items[(int)rule.ReevaluationBehavior];
listViewItem.SubItems[3].Text = rule.Active.ToString(CultureInfo.CurrentCulture);
listViewItem.SubItems[4].Text = DesignerHelpers.GetRulePreview(rule);
}
private string CreateNewName()
{
string newRuleNameBase = Messages.NewRuleName;
int index = 1;
while (true)
{
string newRuleName = newRuleNameBase + index.ToString(CultureInfo.InvariantCulture);
if (IsUniqueIdentifier(newRuleName))
return newRuleName;
index++;
}
}
private bool IsUniqueIdentifier(string name)
{
foreach (Rule rule1 in this.dialogRuleSet.Rules)
{
if (rule1.Name == name)
return false;
}
return true;
}
private static string GetActionsString(IList<RuleAction> actions)
{
if (actions == null)
throw new ArgumentNullException("actions");
bool first = true;
StringBuilder actionsText = new StringBuilder();
foreach (RuleAction ruleAction in actions)
{
if (!first)
actionsText.Append("\r\n");
else
first = false;
actionsText.Append(ruleAction.ToString());
}
return actionsText.ToString();
}
private static void SetCaretAt(TextBoxBase textBox, int position)
{
textBox.Focus();
textBox.SelectionStart = position;
textBox.SelectionLength = 0;
textBox.ScrollToCaret();
}
#endregion
#region class ListViewItemComparer
private class ListViewItemComparer : IComparer
{
private int col;
private bool ascending;
public ListViewItemComparer(int column, bool ascending)
{
this.col = column;
this.ascending = ascending;
}
public int Compare(object x, object y)
{
int retval = 0;
ListViewItem item1 = (ListViewItem)x;
ListViewItem item2 = (ListViewItem)y;
if (this.col == 1)
{
// looking at priority
int.TryParse(item1.SubItems[col].Text, NumberStyles.Integer, CultureInfo.CurrentCulture, out int val1);
int.TryParse(item2.SubItems[col].Text, NumberStyles.Integer, CultureInfo.CurrentCulture, out int val2);
if (val1 != val2)
retval = (val2 - val1);
else
// priorities are the same, so sort on name (column 0)
retval = String.Compare(item1.SubItems[0].Text, item2.SubItems[0].Text, StringComparison.CurrentCulture);
}
else
{
retval = String.Compare(item1.SubItems[col].Text, item2.SubItems[col].Text, StringComparison.CurrentCulture);
}
return ascending ? retval : -retval;
}
}
#endregion
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData.Equals(Keys.Escape))
{
this.conditionTextBox.Validating -= this.ConditionTextBox_Validating;
this.thenTextBox.Validating -= this.ThenTextBox_Validating;
this.elseTextBox.Validating -= this.ElseTextBox_Validating;
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void OnHelpClicked(object sender, CancelEventArgs e)
{
e.Cancel = true;
ShowHelp();
}
private void OnHelpRequested(object sender, HelpEventArgs e)
{
ShowHelp();
}
private void ShowHelp()
{
IUIService uisvc = (IUIService)GetService(typeof(IUIService));
if (uisvc != null)
uisvc.ShowError(Messages.NoHelp);
}
}
#endregion
}
| |
using System;
using System.Threading;
using Microsoft.SPOT;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using uScoober.Extensions;
using uScoober.Hardware;
using uScoober.Hardware.Light;
using uScoober.Hardware.Motors;
using uScoober.Hardware.Spot;
using uScoober.Threading;
namespace uDerby
{
using Board = uScoober.Hardware.Boards.NetduinoPlus2;
public class Car
{
private readonly Task _lightsManager;
private readonly IDigitalInput _modeSwitch;
private readonly Board _netduino;
private readonly BrushlessSpeedController _speedController;
private readonly IDigitalInput _triggerLock;
private CancellationSource _cancelRace;
private Modes _mode;
private int _wantedPower;
public Car()
{
_netduino = new Board();
_speedController = new BrushlessSpeedController(_netduino.PwmOut.D5);
//initialize input listeners
_modeSwitch = _netduino.DigitalIn.Bind(Pins.GPIO_PIN_D1, "mode switch", ResistorMode.PullUp,
InterruptMode.InterruptEdgeBoth, 50);
_modeSwitch.InvertReading = true;
_modeSwitch.OnInterupt += (source, state, time) =>
{
_mode = _modeSwitch.Read() ? Modes.Staging : Modes.LightShow;
_speedController.Stop();
};
_triggerLock = _netduino.DigitalIn.Bind(Pins.GPIO_PIN_D2, "trigger-lock/e-stop", ResistorMode.PullUp,
InterruptMode.InterruptEdgeBoth, 100);
_triggerLock.InvertReading = true;
_triggerLock.OnInterupt += (source, state, time) =>
{
//fire on button down, coud use InterruptMode.InterruptEdgeLow
if (!_triggerLock.Read())
{
return;
}
switch (_mode)
{
case Modes.LightShow:
case Modes.Celebrate:
case Modes.Arming:
return;
case Modes.Staging:
if (!StartingPinFound())
{
return;
}
_mode = Modes.Arming;
Thread.Sleep(1500);
if (!StartingPinFound())
{
_mode = Modes.Staging;
return;
}
SnapshotWantedPower();
_cancelRace = new CancellationSource();
Task.Run(token =>
{
while (StartingPinFound())
{
_mode = Modes.Armed;
//wait for the pin to drop, or cancellation
token.ThrowIfCancellationRequested();
}
//Go Baby Go: fire all engines!
_mode = Modes.Race;
_speedController.SetPower(_wantedPower);
// todo: how long should we run?
int counter = 0;
while (counter < 2500)
{
if (token.IsCancellationRequested)
{
_speedController.Stop();
token.ThrowIfCancellationRequested();
}
counter++;
Thread.Sleep(1);
}
},
_cancelRace)
.ContinueWith(previous =>
{
_speedController.Stop();
_mode = (previous.IsCanceled) ? Modes.LightShow : Modes.Celebrate;
_cancelRace = null;
});
return;
case Modes.Armed:
case Modes.Race:
_speedController.Stop();
_cancelRace.Cancel();
return;
default:
throw new ArgumentOutOfRangeException();
}
};
_lightsManager = Task.New(() =>
{
var leftFrontLed = new DigitalLed(_netduino.DigitalOut.Bind(Pins.GPIO_PIN_D13, false, "Left Front"));
var rightFrontLed = new DigitalLed(_netduino.DigitalOut.Bind(Pins.GPIO_PIN_D12, false, "Right Front"));
var leftRearLed = new DigitalLed(_netduino.DigitalOut.Bind(Pins.GPIO_PIN_D11, false, "Left Rear"));
var rightRearLed = new DigitalLed(_netduino.DigitalOut.Bind(Pins.GPIO_PIN_D10, false, "Right Rear"));
var random = new Random();
int counter1 = 0;
while (true)
{
bool flag;
switch (_mode)
{
case Modes.LightShow:
counter1 = (counter1 + 1)%50;
if (counter1 == 1 || counter1 == 26)
{
leftFrontLed.IsOn = random.NextBool();
leftRearLed.IsOn = random.NextBool();
rightFrontLed.IsOn = random.NextBool();
rightRearLed.IsOn = random.NextBool();
}
_netduino.OnboardLed.TurnOn(counter1/50.0);
break;
case Modes.Staging:
// blink left and right, front and back together
counter1 = (counter1 + 1)%50;
flag = counter1 < 25;
leftFrontLed.IsOn = flag;
leftRearLed.IsOn = flag;
rightFrontLed.IsOn = !flag;
rightRearLed.IsOn = !flag;
_netduino.OnboardLed.IsOn = counter1 < 5;
break;
case Modes.Arming:
counter1 = (counter1 + 1)%10;
flag = counter1 < 5;
leftFrontLed.IsOn = flag;
leftRearLed.IsOn = flag;
rightFrontLed.IsOn = flag;
rightRearLed.IsOn = flag;
_netduino.OnboardLed.IsOn = flag;
break;
case Modes.Armed:
// blink left and right front, rears on
counter1 = (counter1 + 1)%50;
flag = counter1 < 25;
leftFrontLed.IsOn = flag;
leftRearLed.IsOn = true;
rightFrontLed.IsOn = !flag;
rightRearLed.IsOn = true;
_netduino.OnboardLed.TurnOn();
break;
case Modes.Race:
// fronts on, rears off
leftFrontLed.IsOn = true;
leftRearLed.IsOn = false;
rightFrontLed.IsOn = true;
rightRearLed.IsOn = false;
_netduino.OnboardLed.TurnOff();
break;
case Modes.Celebrate:
// fronts fast random, rears blink together
counter1 = (counter1 + 1)%50;
flag = counter1 < 25;
if (counter1 == 1 || counter1 == 26)
{
leftFrontLed.IsOn = random.NextBool();
rightFrontLed.IsOn = random.NextBool();
}
leftRearLed.IsOn = flag;
rightRearLed.IsOn = flag;
_netduino.OnboardLed.TurnOn((50 - counter1)/50.0);
break;
default:
throw new ArgumentOutOfRangeException();
}
Thread.Sleep(10);
}
});
}
public void Start()
{
_netduino.OnboardLed.TurnOn();
_speedController.Arm();
_mode = Modes.LightShow;
_modeSwitch.InteruptEnabled = true;
_triggerLock.InteruptEnabled = true;
_lightsManager.Start();
}
private void SnapshotWantedPower()
{
// 2 part scale
// 0v to 1.6v => 0% to 50%
// 1.6v to 2.15v => 50% to 100%
double reading = _netduino.AnalogIn[2].Read();
if (reading < 1.6)
{
_wantedPower = (int) ((reading*50)/1.6);
}
else
{
_wantedPower = 50 + (int) (((reading - 1.6)*50)/0.55);
}
Debug.Print("Wanted Power:" + _wantedPower);
}
private bool StartingPinFound()
{
double light = _netduino.AnalogIn.A0.Read();
Debug.Print("Start Light:" + light);
return light >= 1.6;
}
private enum Modes
{
LightShow,
Staging,
Arming,
Armed,
Race,
Celebrate
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Runtime.TypeSystem
{
using System;
using System.Collections.Generic;
public sealed class BoxedValueTypeRepresentation : ReferenceTypeRepresentation
{
//
// State
//
private TypeRepresentation m_valueType; // We need to use TypeRepresentation instead of ValueTypeRepresentation because we might need to box a delayed type.
//
// Constructor Methods
//
public BoxedValueTypeRepresentation( TypeRepresentation valueType ) : base( valueType.Owner, valueType.BuiltInType, valueType.Flags )
{
m_valueType = valueType;
}
//
// MetaDataEquality Methods
//
public override bool EqualsThroughEquivalence( object obj ,
EquivalenceSet set )
{
if(obj is BoxedValueTypeRepresentation)
{
BoxedValueTypeRepresentation other = (BoxedValueTypeRepresentation)obj;
return EqualsThroughEquivalence( m_valueType, other.m_valueType, set );
}
return false;
}
public override bool Equals( object obj )
{
return this.EqualsThroughEquivalence( obj, null );
}
public override int GetHashCode()
{
return m_valueType.GetHashCode();
}
//--//
//
// Helper Methods
//
protected override void PerformInnerDelayedTypeAnalysis( TypeSystem typeSystem ,
ref ConversionContext context )
{
m_extends = m_valueType.Extends;
}
//--//
public override void ApplyTransformation( TransformationContext context )
{
context.Push( this );
//
// Load before calling the base method, because we might get a call to GetHashCode().
//
context.Transform( ref m_valueType );
base.ApplyTransformation( context );
context.Pop();
}
//--//
protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic )
{
TypeRepresentation valueType = ic.Instantiate( m_valueType );
//
// When expanding box or unbox in the context of a generic method or type, we might need to box a delayed type.
// At instantiation time, the delayed type might be resolved to a reference type.
//
if(valueType is ValueTypeRepresentation)
{
BoxedValueTypeRepresentation tdRes = new BoxedValueTypeRepresentation( valueType );
tdRes.PopulateInstantiation( this, ic );
return tdRes;
}
else
{
return valueType;
}
}
//--//
public override GCInfo.Kind ClassifyAsPointer()
{
return GCInfo.Kind.Internal;
}
//
// Access Methods
//
public override TypeRepresentation ContainedType
{
get
{
return m_valueType;
}
}
public override TypeRepresentation UnderlyingType
{
get
{
return m_valueType;
}
}
public override bool IsOpenType
{
get
{
return m_valueType.IsOpenType;
}
}
public override bool IsDelayedType
{
get
{
return m_valueType.IsDelayedType;
}
}
public override StackEquivalentType StackEquivalentType
{
get
{
return StackEquivalentType.Object;
}
}
//--//
public override bool CanBeAssignedFrom( TypeRepresentation rvalue ,
EquivalenceSet set )
{
if(this.EqualsThroughEquivalence( rvalue, set ))
{
return true;
}
if(rvalue is PointerTypeRepresentation)
{
//
// Going from a byref to a boxed valuetype is OK.
//
return m_valueType.EqualsThroughEquivalence( rvalue.UnderlyingType, set );
}
return m_valueType.CanBeAssignedFrom( rvalue, set );
}
//--//
//
// Debug Methods
//
public override String ToString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder( "BoxedValueTypeRepresentation(" );
PrettyToString( sb, true, false );
sb.Append( ")" );
return sb.ToString();
}
internal override void PrettyToString( System.Text.StringBuilder sb ,
bool fPrefix ,
bool fWithAbbreviations )
{
sb.Append( "boxed " );
m_valueType.PrettyToString( sb, fPrefix, fWithAbbreviations );
}
}
}
| |
using FontBuddyLib;
using GameTimer;
using InputHelper;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Text;
namespace MenuBuddy
{
public class Label : Widget, ILabel, IDisposable
{
#region Fields
private string _text;
private string _renderedText;
private bool _isPassword;
private FontSize _fontSize;
#pragma warning disable 0414
public event EventHandler<ClickEventArgs> OnClick;
#pragma warning restore 0414
#endregion //Fields
#region Properties
public bool Clickable { get; set; }
/// <summary>
/// The text of this label
/// </summary>
public string Text
{
get
{
return _text;
}
set
{
if (_text != value)
{
_text = value;
SetRenderText();
CalculateRect();
}
}
}
public FontSize FontSize
{
get
{
return _fontSize;
}
private set
{
if (_fontSize != value)
{
_fontSize = value;
CalculateRect();
}
}
}
public bool IsClicked { get; set; }
/// <summary>
/// Whether or not this label will take care of it's own fonts
/// </summary>
private bool ManagedFonts { get; set; } = false;
/// <summary>
/// If this is set, use it to draw this label
/// </summary>
public IFontBuddy Font { get; set; }
/// <summary>
/// If this is set, use it to draw this label
/// </summary>
public IFontBuddy HighlightedFont { get; set; }
/// <summary>
/// If this is not null, use it as the shadow color.
/// </summary>
public Color? ShadowColor { get; set; }
/// <summary>
/// If this is not null, use it as the text color.
/// </summary>
public Color? TextColor { get; set; }
public bool IsPassword
{
get
{
return _isPassword;
}
set
{
if (_isPassword != value)
{
_isPassword = value;
SetRenderText();
CalculateRect();
}
}
}
#endregion //Properties
#region Initialization
/// <summary>
/// constructor
/// </summary>
/// <param name="text"></param>
public Label(string text, ContentManager content, FontSize fontSize = FontSize.Medium, string fontResource = null, bool? useFontPlus = null, int? fontPlusSize = null)
{
_fontSize = fontSize;
Text = text;
Clickable = true;
ManagedFonts = true;
//If there is no value for the font plus flag, grab it from the stylesheet
if (!useFontPlus.HasValue)
{
useFontPlus = StyleSheet.UseFontPlus;
}
if (!useFontPlus.Value)
{
//load the fonts from the stylesheet
InitializeFonts(content, fontResource);
}
else
{
InitializeFontPlus(content, fontResource, fontPlusSize);
}
CalculateRect();
}
public Label(string text, IFontBuddy font, IFontBuddy highlightedFont = null)
{
_fontSize = FontSize.Medium;
Text = text;
Clickable = true;
//hold onto the provided fonts
Font = font;
HighlightedFont = highlightedFont;
CalculateRect();
}
public Label(Label inst) : base(inst)
{
if (null == inst)
{
throw new ArgumentNullException("inst");
}
Font = inst.Font;
HighlightedFont = inst.HighlightedFont;
Clickable = inst.Clickable;
_text = inst.Text;
_renderedText = inst._renderedText;
_fontSize = inst.FontSize;
TextColor = inst.TextColor;
ShadowColor = inst.ShadowColor;
}
/// <summary>
/// Get a deep copy of this item
/// </summary>
/// <returns></returns>
public override IScreenItem DeepCopy()
{
return new Label(this);
}
protected virtual void InitializeFonts(ContentManager content, string fontResource)
{
fontResource = GetFontResource(fontResource);
switch (FontSize)
{
case FontSize.Large:
{
Font = new FontBuddy();
HighlightedFont = new PulsateBuddy();
}
break;
case FontSize.Medium:
{
Font = new ShadowTextBuddy()
{
ShadowSize = 1.0f,
ShadowOffset = new Vector2(7.0f, 7.0f),
};
HighlightedFont = new PulsateBuddy()
{
ShadowSize = 1.0f,
ShadowOffset = new Vector2(7.0f, 7.0f),
};
}
break;
default:
{
if (StyleSheet.SmallFontHasShadow)
{
Font = new ShadowTextBuddy()
{
ShadowSize = 1.0f,
ShadowOffset = new Vector2(3.0f, 4.0f),
};
}
else
{
Font = new FontBuddy();
}
HighlightedFont = new PulsateBuddy()
{
ShadowSize = 1.0f,
ShadowOffset = new Vector2(3.0f, 4.0f),
};
}
break;
}
Font.LoadContent(content, fontResource);
HighlightedFont.LoadContent(content, fontResource);
}
protected virtual void InitializeFontPlus(ContentManager content, string fontResource, int? fontPlusSize)
{
fontResource = GetFontResource(fontResource);
var fontSize = GetFontPlusSize(fontPlusSize);
switch (FontSize)
{
case FontSize.Large:
{
Font = new FontBuddyPlus();
HighlightedFont = new PulsateBuddy();
}
break;
case FontSize.Medium:
{
Font = new ShadowTextBuddy()
{
ShadowSize = 1.0f,
ShadowOffset = new Vector2(7.0f, 7.0f),
};
HighlightedFont = new PulsateBuddy()
{
ShadowSize = 1.0f,
ShadowOffset = new Vector2(7.0f, 7.0f),
};
}
break;
default:
{
if (StyleSheet.SmallFontHasShadow)
{
Font = new ShadowTextBuddy()
{
ShadowSize = 1.0f,
ShadowOffset = new Vector2(3.0f, 4.0f),
};
}
else
{
Font = new FontBuddyPlus();
}
HighlightedFont = new PulsateBuddy()
{
ShadowSize = 1.0f,
ShadowOffset = new Vector2(3.0f, 4.0f),
};
}
break;
}
Font.LoadContent(content, fontResource, true, fontSize);
HighlightedFont.LoadContent(content, fontResource, true, fontSize);
}
private string GetFontResource(string fontResource)
{
if (string.IsNullOrEmpty(fontResource))
{
switch (FontSize)
{
case FontSize.Large:
{
fontResource = StyleSheet.LargeFontResource;
}
break;
case FontSize.Medium:
{
fontResource = StyleSheet.MediumFontResource;
}
break;
case FontSize.Small:
{
fontResource = StyleSheet.SmallFontResource;
}
break;
}
}
return fontResource;
}
private int GetFontPlusSize(int? fontPlusSize)
{
if (fontPlusSize.HasValue)
{
return fontPlusSize.Value;
}
else
{
switch (FontSize)
{
case FontSize.Large:
{
return StyleSheet.LargeFontSize;
}
case FontSize.Medium:
{
return StyleSheet.MediumFontSize;
}
default:
{
return StyleSheet.SmallFontSize;
}
}
}
}
public override void UnloadContent()
{
base.UnloadContent();
OnClick = null;
if (ManagedFonts)
{
Font?.Dispose();
Font = null;
HighlightedFont?.Dispose();
HighlightedFont = null;
}
}
#endregion //Initialization
#region Methods
protected Vector2 TextPosition(IScreen screen)
{
//get the draw position
switch (Horizontal)
{
case HorizontalAlignment.Left:
{
return TransitionObject.Position(screen, new Point(Rect.X, Rect.Y));
}
case HorizontalAlignment.Center:
{
return TransitionObject.Position(screen, new Point(Rect.Center.X, Rect.Y));
}
default:
{
return TransitionObject.Position(screen, new Point(Rect.Right, Rect.Y));
}
}
}
public override void Draw(IScreen screen, GameClock gameTime)
{
if (!ShouldDraw(screen))
{
return;
}
//Get the font to use
var font = GetFont();
var screenTransition = TransitionObject.GetScreenTransition(screen);
//make sure the shadow color is correct
var shadow = font as ShadowTextBuddy;
if (null != shadow)
{
shadow.ShadowColor = screenTransition.AlphaColor(GetShadowColor());
}
//adjust the pulsate scale
var pulsate = font as PulsateBuddy;
if (Highlightable && null != pulsate)
{
pulsate.PulsateSize = IsClicked ? 1.2f : 1f;
}
//Write the text
font.Write(_renderedText,
TextPosition(screen),
AlignmentToJustify(),
Scale,
screenTransition.AlphaColor(GetColor()),
screen.ScreenManager.SpriteBatch,
HighlightClock);
}
protected override void CalculateRect()
{
//get the size of the rect
var font = GetFont();
var size = MeasureText(font) * Scale;
//set the x component
Vector2 pos = Position.ToVector2();
switch (Horizontal)
{
case HorizontalAlignment.Center: { pos.X -= size.X / 2f; } break;
case HorizontalAlignment.Right: { pos.X -= size.X; } break;
}
//set the y component
switch (Vertical)
{
case VerticalAlignment.Center: { pos.Y -= size.Y / 2f; } break;
case VerticalAlignment.Bottom: { pos.Y -= size.Y; } break;
}
_rect = new Rectangle((int)pos.X, (int)pos.Y, (int)size.X, (int)size.Y);
}
protected void SetRenderText()
{
if (!IsPassword)
{
_renderedText = _text;
}
else
{
var textBuilder = new StringBuilder();
textBuilder.Append('*', _text?.Length ?? 0);
_renderedText = textBuilder.ToString();
}
}
private Justify AlignmentToJustify()
{
switch (Horizontal)
{
case HorizontalAlignment.Center: return Justify.Center;
case HorizontalAlignment.Left: return Justify.Left;
default: return Justify.Right;
}
}
protected virtual IFontBuddy GetFont()
{
if (!IsHighlighted || null == HighlightedFont)
{
return Font;
}
else
{
return HighlightedFont;
}
}
protected virtual Color GetColor()
{
if (TextColor.HasValue)
{
return TextColor.Value;
}
else if (IsClicked)
{
return StyleSheet.SelectedTextColor;
}
else if (IsHighlighted)
{
return StyleSheet.HighlightedTextColor;
}
else
{
return StyleSheet.NeutralTextColor;
}
}
protected virtual Color GetShadowColor()
{
if (ShadowColor.HasValue)
{
return ShadowColor.Value;
}
else
{
return StyleSheet.TextShadowColor;
}
}
public bool CheckClick(ClickEventArgs click)
{
return false;
}
private Vector2 MeasureText(IFontBuddy font)
{
if (!string.IsNullOrEmpty(_renderedText) && null != font)
{
return font.MeasureString(_renderedText);
}
else
{
return Vector2.Zero;
}
}
public void ScaleToFit(int rowWidth)
{
Scale = Font.ScaleToFit(Text, rowWidth);
}
public void ShrinkToFit(int rowWidth)
{
if (Font.NeedsToShrink(Text, Scale, rowWidth))
{
Scale = Font.ShrinkToFit(Text, rowWidth);
}
}
#endregion //Methods
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Rest.FlexApi.V1;
namespace Twilio.Tests.Rest.FlexApi.V1
{
[TestFixture]
public class FlexFlowTest : TwilioTest
{
[Test]
public void TestReadRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.FlexApi,
"/v1/FlexFlows",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
FlexFlowResource.Read(client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestReadFullResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://flex-api.twilio.com/v1/FlexFlows?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://flex-api.twilio.com/v1/FlexFlows?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"flex_flows\"},\"flex_flows\": [{\"sid\": \"FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2016-08-01T22:10:40Z\",\"date_updated\": \"2016-08-01T22:10:40Z\",\"friendly_name\": \"friendly_name\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"channel_type\": \"sms\",\"contact_identity\": \"12345\",\"enabled\": true,\"integration_type\": \"studio\",\"integration\": {\"flow_sid\": \"FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"retry_count\": 1},\"long_lived\": true,\"janitor_enabled\": true,\"url\": \"https://flex-api.twilio.com/v1/FlexFlows/FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}]}"
));
var response = FlexFlowResource.Read(client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestReadEmptyResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://flex-api.twilio.com/v1/FlexFlows?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://flex-api.twilio.com/v1/FlexFlows?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"flex_flows\"},\"flex_flows\": []}"
));
var response = FlexFlowResource.Read(client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestFetchRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.FlexApi,
"/v1/FlexFlows/FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
FlexFlowResource.Fetch("FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestFetchResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"sid\": \"FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2016-08-01T22:10:40Z\",\"date_updated\": \"2016-08-01T22:10:40Z\",\"friendly_name\": \"friendly_name\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"channel_type\": \"sms\",\"contact_identity\": \"12345\",\"enabled\": true,\"integration_type\": \"studio\",\"integration\": {\"flow_sid\": \"FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"retry_count\": 1},\"long_lived\": true,\"janitor_enabled\": true,\"url\": \"https://flex-api.twilio.com/v1/FlexFlows/FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = FlexFlowResource.Fetch("FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestCreateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.FlexApi,
"/v1/FlexFlows",
""
);
request.AddPostParam("FriendlyName", Serialize("friendly_name"));
request.AddPostParam("ChatServiceSid", Serialize("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"));
request.AddPostParam("ChannelType", Serialize(FlexFlowResource.ChannelTypeEnum.Web));
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
FlexFlowResource.Create("friendly_name", "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", FlexFlowResource.ChannelTypeEnum.Web, client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestCreateResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.Created,
"{\"sid\": \"FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2016-08-01T22:10:40Z\",\"date_updated\": \"2016-08-01T22:10:40Z\",\"friendly_name\": \"friendly_name\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"channel_type\": \"sms\",\"contact_identity\": \"12345\",\"enabled\": true,\"integration_type\": \"studio\",\"integration\": {\"flow_sid\": \"FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"retry_count\": 1},\"long_lived\": true,\"janitor_enabled\": true,\"url\": \"https://flex-api.twilio.com/v1/FlexFlows/FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = FlexFlowResource.Create("friendly_name", "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", FlexFlowResource.ChannelTypeEnum.Web, client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestUpdateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.FlexApi,
"/v1/FlexFlows/FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
FlexFlowResource.Update("FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestUpdateResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"sid\": \"FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2016-08-01T22:10:40Z\",\"date_updated\": \"2016-08-01T22:10:40Z\",\"friendly_name\": \"friendly_name\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"channel_type\": \"sms\",\"contact_identity\": \"12345\",\"enabled\": true,\"integration_type\": \"studio\",\"integration\": {\"flow_sid\": \"FWaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"retry_count\": 1},\"long_lived\": true,\"janitor_enabled\": true,\"url\": \"https://flex-api.twilio.com/v1/FlexFlows/FOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = FlexFlowResource.Update("FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestDeleteRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Delete,
Twilio.Rest.Domain.FlexApi,
"/v1/FlexFlows/FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
FlexFlowResource.Delete("FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestDeleteResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.NoContent,
"null"
));
var response = FlexFlowResource.Delete("FOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Albatross.Web.Example.Models;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
namespace Albatross.Web.Example.Migrations
{
[ContextType(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
public override void BuildModel(ModelBuilder builder)
{
builder
.Annotation("SqlServer:ValueGeneration", "Identity");
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("NormalizedName")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity)
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity)
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ProviderKey")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ProviderDisplayName")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 1);
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("Albatross.Web.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<int>("AccessFailedCount")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 2);
b.Property<string>("Email")
.Annotation("OriginalValueIndex", 3);
b.Property<bool>("EmailConfirmed")
.Annotation("OriginalValueIndex", 4);
b.Property<bool>("LockoutEnabled")
.Annotation("OriginalValueIndex", 5);
b.Property<DateTimeOffset?>("LockoutEnd")
.Annotation("OriginalValueIndex", 6);
b.Property<string>("NormalizedEmail")
.Annotation("OriginalValueIndex", 7);
b.Property<string>("NormalizedUserName")
.Annotation("OriginalValueIndex", 8);
b.Property<string>("PasswordHash")
.Annotation("OriginalValueIndex", 9);
b.Property<string>("PhoneNumber")
.Annotation("OriginalValueIndex", 10);
b.Property<bool>("PhoneNumberConfirmed")
.Annotation("OriginalValueIndex", 11);
b.Property<string>("SecurityStamp")
.Annotation("OriginalValueIndex", 12);
b.Property<bool>("TwoFactorEnabled")
.Annotation("OriginalValueIndex", 13);
b.Property<string>("UserName")
.Annotation("OriginalValueIndex", 14);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Reference("Albatross.Web.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Reference("Albatross.Web.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
b.Reference("Albatross.Web.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using bv.common.Configuration;
using bv.common.Resources;
namespace bv.common.Core
{
public class Localizer
{
public static string lngEn {get { return Core.SupportedLanguages.lngEn; }}
public static string lngRu { get { return Core.SupportedLanguages.lngRu; } }
public static string lngGe { get { return Core.SupportedLanguages.lngGe; } }
public static string lngKz { get { return Core.SupportedLanguages.lngKz; } }
public static string lngUzCyr { get { return Core.SupportedLanguages.lngUzCyr; } }
public static string lngUzLat { get { return Core.SupportedLanguages.lngUzLat; } }
public static string lngAzLat { get { return Core.SupportedLanguages.lngAzLat; } }
public static string lngAr { get { return Core.SupportedLanguages.lngAr; } }
public static string lngUk { get { return Core.SupportedLanguages.lngUk; } }
public static string lngIraq { get { return Core.SupportedLanguages.lngIraq; } }
public static string lngVietnam { get { return Core.SupportedLanguages.lngVietnam; } }
public static string lngLaos { get { return Core.SupportedLanguages.lngLaos; } }
public static string lngThai { get { return Core.SupportedLanguages.lngThai; } }
public static BaseStringsStorage MenuMessages { get; set; }
//public static string Language { get; set; }
public static Dictionary<string, string> SupportedLanguages
{
get { return Core.SupportedLanguages.Installed; }
//set { m_SupportedLanguages = value; }
}
public static Dictionary<string, string> AllSupportedLanguages
{
get { return Core.SupportedLanguages.All; }
//set { m_AllSupportedLanguages = value; }
}
public static string CurrentCultureLanguageID
{
get { return GetLanguageID(Thread.CurrentThread.CurrentCulture); }
}
public static int YearShift
{
get { return CurrentCultureLanguageID == lngThai ? 543 : 0; }
}
private static void AddLanguage(Dictionary<string, string> dict, string langID, string cultureName)
{
if (!dict.ContainsKey(langID))
{
dict.Add(langID, cultureName);
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Converts passed <b>CultureInfo</b> object to the application language identifier
/// </summary>
/// <param name="culture">
/// <b>CultureInfo</b> object
/// </param>
/// <returns>
/// Returns application language identifier related with passed <i>culture</i>.
/// </returns>
/// <remarks>
/// Use this method to retrieve application language identifier for the specific <b>CultureInfo</b>.
/// Application language identifier is used to set/get current application language and
/// perform related application translation to this language.
/// </remarks>
/// <history>
/// [Mike] 30.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
public static string GetLanguageID(CultureInfo culture)
{
switch (culture.TwoLetterISOLanguageName)
{
case "uz":
if (culture.Name.IndexOf("Cyrl", StringComparison.Ordinal) > 0)
{
return lngUzCyr;
}
return lngUzLat;
case "az":
return lngAzLat;
case "ar":
return lngIraq;
default:
return culture.TwoLetterISOLanguageName;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets the translated human readable language name related with specific application language identifier
/// </summary>
/// <param name="langID">
/// application language identifier for which the human readable language name should be retrieved
/// </param>
/// <param name="displayLangID">
/// application language identifier of language to which the language name should be translated
/// </param>
/// <remarks>
/// <b>Note:</b> only English, Russian, Georgian, Kazakh, Uzbek Cyrillic and Uzbek Latin languages are supported by the
/// system
/// </remarks>
/// <history>
/// [Mike] 30.03.2006 Created
/// </history>
/// -----------------------------------------------------------------------------
public static string GetLanguageName(string langID, string displayLangID = null)
{
if (MenuMessages == null)
{
MenuMessages = BvMessages.Instance;
}
switch (langID)
{
case Core.SupportedLanguages.lngEn:
return MenuMessages.GetString("MenuEnglish", "&English", displayLangID).Replace("&", "");
case Core.SupportedLanguages.lngRu:
return MenuMessages.GetString("MenuRussian", "&Russian", displayLangID).Replace("&", "");
case Core.SupportedLanguages.lngGe:
return MenuMessages.GetString("MenuGeorgian", "&Georgian", displayLangID).Replace("&", "");
case Core.SupportedLanguages.lngKz:
return MenuMessages.GetString("MenuKazakh", "&Kazakh", displayLangID).Replace("&", "");
case Core.SupportedLanguages.lngUzCyr:
return MenuMessages.GetString("MenuUzbekCyr", "Uzbeck (&Cyr)", displayLangID).Replace("&", "");
case Core.SupportedLanguages.lngUzLat:
return MenuMessages.GetString("MenuUzbekLat", "Uzbek (&Lat)", displayLangID).Replace("&", "");
case Core.SupportedLanguages.lngAzLat:
return MenuMessages.GetString("MenuAzeriLat", "Azeri (&Lat)", displayLangID).Replace("&", "");
case Core.SupportedLanguages.lngAr:
return MenuMessages.GetString("MenuArmenian", "Armenian", displayLangID).Replace("&", "");
case Core.SupportedLanguages.lngUk:
return MenuMessages.GetString("MenuUkrainian", "Ukrainian", displayLangID).Replace("&", "");
case Core.SupportedLanguages.lngIraq:
return MenuMessages.GetString("MenuIraq", "Arabic (Iraq)", displayLangID).Replace("&", "");
case Core.SupportedLanguages.lngLaos:
return MenuMessages.GetString("MenuLaos", "Laos", displayLangID).Replace("&", "");
case Core.SupportedLanguages.lngVietnam:
return MenuMessages.GetString("MenuVietnam", "Vietnam", displayLangID).Replace("&", "");
case Core.SupportedLanguages.lngThai:
return MenuMessages.GetString("MenuThai", "Thai", displayLangID).Replace("&", "");
}
return MenuMessages.GetString("MenuEnglish", "&English", displayLangID).Replace("&", "");
}
public static string GetMenuLanguageName(string langID, string displayLangID = null)
{
return string.Format("{0} ({1})", GetLanguageName(langID, displayLangID), GetLanguageName(langID, lngEn));
//if (MenuMessages == null)
//{
// MenuMessages = BvMessages.Instance;
//}
//switch (langID)
//{
// case lngEn:
// return MenuMessages.GetString("MenuEnglish", "&English", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuEnglish", "&English", lngEn).Replace("&", "") + ")";
// case lngRu:
// return MenuMessages.GetString("MenuRussian", "&Russian", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuRussian", "&Russian", lngRu).Replace("&", "") + ")";
// case lngGe:
// return MenuMessages.GetString("MenuGeorgian", "&Georgian", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuGeorgian", "&Georgian", lngGe).Replace("&", "") + ")";
// case lngKz:
// return MenuMessages.GetString("MenuKazakh", "&Kazakh", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuKazakh", "&Kazakh", lngKz).Replace("&", "") + ")";
// case lngUzCyr:
// return MenuMessages.GetString("MenuUzbekCyr", "Uzbeck (&Cyr)", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuUzbekCyr", "Uzbeck (&Cyr)", lngUzCyr).Replace("&", "") + ")";
// case lngUzLat:
// return MenuMessages.GetString("MenuUzbekLat", "Uzbek (&Lat)", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuUzbekLat", "Uzbek (&Lat)", lngUzLat).Replace("&", "") + ")";
// case lngAzLat:
// return MenuMessages.GetString("MenuAzeriLat", "Azeri (&Lat)", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuAzeriLat", "Azeri (&Lat)", lngAzLat).Replace("&", "") + ")";
// case lngAr:
// return MenuMessages.GetString("MenuArmenian", "Armenian", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuArmenian", "Armenian", lngAr).Replace("&", "") + ")";
// case lngUk:
// return MenuMessages.GetString("MenuUkrainian", "Ukrainian", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuUkrainian", "Ukrainian", lngUk).Replace("&", "") + ")";
// case lngIraq:
// return MenuMessages.GetString("MenuIraq", "Arabic (Iraq)", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuIraq", "Arabic (Iraq)", lngIraq).Replace("&", "") + ")";
// case lngLaos:
// return MenuMessages.GetString("MenuLaos", "Laos", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuLaos", "Laos", lngLaos).Replace("&", "") + ")";
// case lngVietnam:
// return MenuMessages.GetString("MenuVietnam", "Vietnam", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuVietnam", "Vietnam", lngVietnam).Replace("&", "") + ")";
// case lngThai:
// return MenuMessages.GetString("MenuThai", "Thai", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuThai", "Thai", lngUk).Replace("&", "") + ")";
//}
//return MenuMessages.GetString("MenuEnglish", "&English", displayLangID).Replace("&", "") + " (" +
// MenuMessages.GetString("MenuEnglish", "&English", lngEn).Replace("&", "") + ")";
}
public static string DefaultLanguage
{
get { return Config.GetSetting("DefaultLanguage", "en"); }
}
public static string DefaultLanguageLocale
{
get { return CustomCultureHelper.SupportedLanguages[DefaultLanguage]; }
}
public static bool ReverseFromToLabelsPosition
{
get { return CultureInfo.CurrentCulture.Name.ToLowerInvariant() == "ka-ge"; }
}
public static bool IsRtl
{
get { return BaseSettings.ForceRightToLeft || (Thread.CurrentThread.CurrentUICulture.TextInfo.IsRightToLeft && !BaseSettings.ForceLeftToRight); }
}
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace System.IO.MemoryMappedFiles
{
public partial class MemoryMappedFile
{
/// <summary>
/// Used by the 2 Create factory method groups. A null fileHandle specifies that the
/// memory mapped file should not be associated with an exsiting file on disk (i.e. start
/// out empty).
/// </summary>
private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
[SecurityCritical]
private static SafeMemoryMappedFileHandle CreateCore(
FileStream fileStream, string mapName, HandleInheritability inheritability,
MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity)
{
SafeFileHandle fileHandle = fileStream != null ? fileStream.SafeFileHandle : null;
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability);
// split the long into two ints
int capacityLow = unchecked((int)(capacity & 0x00000000FFFFFFFFL));
int capacityHigh = unchecked((int)(capacity >> 32));
SafeMemoryMappedFileHandle handle = fileHandle != null ?
Interop.mincore.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName) :
Interop.mincore.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName);
int errorCode = Marshal.GetLastWin32Error();
if (!handle.IsInvalid)
{
if (errorCode == Interop.mincore.Errors.ERROR_ALREADY_EXISTS)
{
handle.Dispose();
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
else // handle.IsInvalid
{
handle.Dispose();
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
return handle;
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, bool createOrOpen)
{
return OpenCore(mapName, inheritability, GetFileMapAccess(access), createOrOpen);
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileRights rights, bool createOrOpen)
{
return OpenCore(mapName, inheritability, GetFileMapAccess(rights), createOrOpen);
}
/// <summary>
/// Used by the CreateOrOpen factory method groups.
/// </summary>
[SecurityCritical]
private static SafeMemoryMappedFileHandle CreateOrOpenCore(
string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access,
MemoryMappedFileOptions options, long capacity)
{
/// Try to open the file if it exists -- this requires a bit more work. Loop until we can
/// either create or open a memory mapped file up to a timeout. CreateFileMapping may fail
/// if the file exists and we have non-null security attributes, in which case we need to
/// use OpenFileMapping. But, there exists a race condition because the memory mapped file
/// may have closed between the two calls -- hence the loop.
///
/// The retry/timeout logic increases the wait time each pass through the loop and times
/// out in approximately 1.4 minutes. If after retrying, a MMF handle still hasn't been opened,
/// throw an InvalidOperationException.
Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf");
SafeMemoryMappedFileHandle handle = null;
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability);
// split the long into two ints
int capacityLow = unchecked((int)(capacity & 0x00000000FFFFFFFFL));
int capacityHigh = unchecked((int)(capacity >> 32));
int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins
int waitSleep = 0;
// keep looping until we've exhausted retries or break as soon we get valid handle
while (waitRetries > 0)
{
// try to create
handle = Interop.mincore.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs,
GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName);
if (!handle.IsInvalid)
{
break;
}
else
{
handle.Dispose();
int createErrorCode = Marshal.GetLastWin32Error();
if (createErrorCode != Interop.mincore.Errors.ERROR_ACCESS_DENIED)
{
throw Win32Marshal.GetExceptionForWin32Error(createErrorCode);
}
}
// try to open
handle = Interop.mincore.OpenFileMapping(GetFileMapAccess(access), (inheritability &
HandleInheritability.Inheritable) != 0, mapName);
// valid handle
if (!handle.IsInvalid)
{
break;
}
// didn't get valid handle; have to retry
else
{
handle.Dispose();
int openErrorCode = Marshal.GetLastWin32Error();
if (openErrorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
{
throw Win32Marshal.GetExceptionForWin32Error(openErrorCode);
}
// increase wait time
--waitRetries;
if (waitSleep == 0)
{
waitSleep = 10;
}
else
{
ThreadSleep(waitSleep);
waitSleep *= 2;
}
}
}
// finished retrying but couldn't create or open
if (handle == null || handle.IsInvalid)
{
throw new InvalidOperationException(SR.InvalidOperation_CantCreateFileMapping);
}
return handle;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>
/// This converts a MemoryMappedFileRights to its corresponding native FILE_MAP_XXX value to be used when
/// creating new views.
/// </summary>
private static int GetFileMapAccess(MemoryMappedFileRights rights)
{
return (int)rights;
}
/// <summary>
/// This converts a MemoryMappedFileAccess to its corresponding native FILE_MAP_XXX value to be used when
/// creating new views.
/// </summary>
internal static int GetFileMapAccess(MemoryMappedFileAccess access)
{
switch (access)
{
case MemoryMappedFileAccess.Read: return Interop.mincore.FileMapOptions.FILE_MAP_READ;
case MemoryMappedFileAccess.Write: return Interop.mincore.FileMapOptions.FILE_MAP_WRITE;
case MemoryMappedFileAccess.ReadWrite: return Interop.mincore.FileMapOptions.FILE_MAP_READ | Interop.mincore.FileMapOptions.FILE_MAP_WRITE;
case MemoryMappedFileAccess.CopyOnWrite: return Interop.mincore.FileMapOptions.FILE_MAP_COPY;
case MemoryMappedFileAccess.ReadExecute: return Interop.mincore.FileMapOptions.FILE_MAP_EXECUTE | Interop.mincore.FileMapOptions.FILE_MAP_READ;
default:
Debug.Assert(access == MemoryMappedFileAccess.ReadWriteExecute);
return Interop.mincore.FileMapOptions.FILE_MAP_EXECUTE | Interop.mincore.FileMapOptions.FILE_MAP_READ | Interop.mincore.FileMapOptions.FILE_MAP_WRITE;
}
}
/// <summary>
/// This converts a MemoryMappedFileAccess to it's corresponding native PAGE_XXX value to be used by the
/// factory methods that construct a new memory mapped file object. MemoryMappedFileAccess.Write is not
/// valid here since there is no corresponding PAGE_XXX value.
/// </summary>
internal static int GetPageAccess(MemoryMappedFileAccess access)
{
switch (access)
{
case MemoryMappedFileAccess.Read: return Interop.mincore.PageOptions.PAGE_READONLY;
case MemoryMappedFileAccess.ReadWrite: return Interop.mincore.PageOptions.PAGE_READWRITE;
case MemoryMappedFileAccess.CopyOnWrite: return Interop.mincore.PageOptions.PAGE_WRITECOPY;
case MemoryMappedFileAccess.ReadExecute: return Interop.mincore.PageOptions.PAGE_EXECUTE_READ;
default:
Debug.Assert(access == MemoryMappedFileAccess.ReadWriteExecute);
return Interop.mincore.PageOptions.PAGE_EXECUTE_READWRITE;
}
}
/// <summary>
/// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
/// We'll throw an ArgumentException if the file mapping object didn't exist and the
/// caller used CreateOrOpen since Create isn't valid with Write access
/// </summary>
[SecurityCritical]
private static SafeMemoryMappedFileHandle OpenCore(
string mapName, HandleInheritability inheritability, int desiredAccessRights, bool createOrOpen)
{
SafeMemoryMappedFileHandle handle = Interop.mincore.OpenFileMapping(
desiredAccessRights, (inheritability & HandleInheritability.Inheritable) != 0, mapName);
int lastError = Marshal.GetLastWin32Error();
if (handle.IsInvalid)
{
handle.Dispose();
if (createOrOpen && (lastError == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND))
{
throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access");
}
else
{
throw Win32Marshal.GetExceptionForWin32Error(lastError);
}
}
return handle;
}
/// <summary>
/// Helper method used to extract the native binary security descriptor from the MemoryMappedFileSecurity
/// type. If pinningHandle is not null, caller must free it AFTER the call to CreateFile has returned.
/// </summary>
[SecurityCritical]
private unsafe static Interop.mincore.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability)
{
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES);
if ((inheritability & HandleInheritability.Inheritable) != 0)
{
secAttrs = new Interop.mincore.SECURITY_ATTRIBUTES();
secAttrs.nLength = (uint)sizeof(Interop.mincore.SECURITY_ATTRIBUTES);
secAttrs.bInheritHandle = Interop.BOOL.TRUE;
}
return secAttrs;
}
/// <summary>
/// Replacement for Thread.Sleep(milliseconds), which isn't available.
/// </summary>
internal static void ThreadSleep(int milliseconds)
{
new ManualResetEventSlim(initialState: false).Wait(milliseconds);
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
namespace Igor
{
public class MonsterTestWindow : GraphWindow<MonsterTestBase> {
private static MonsterTestWindow WindowInstance;
public static MonsterTestWindow GetInstance()
{
return WindowInstance;
}
public static MonsterTest CurrentlyOpenTest = null;
public override void CreateStaticNodesIfNotPresent()
{
MonsterTestManager.GetActiveInstance().CreateStaticNodesIfNotPresent();
}
[MenuItem ("Window/Monster/Test/Open Test Editor", false, 0)]
static public void Init () {
/* if(MonsterTestManager.GetActiveInstance() == null)
{
ChapterManager.GetInstance().GetGameStart();
}*/
WindowInstance = (MonsterTestWindow)EditorWindow.GetWindow<MonsterTestWindow>("Monster Test", typeof (SceneView));
WindowInstance.Initialize();
ReloadTestFromFile();
}
[MenuItem ("Window/Monster/Test/Reload Test From File", false, 1)]
static public void ReloadTestFromFile()
{
if(WindowInstance != null)
{
WindowInstance.ClearAllBoxesAndLinks();
if(CurrentlyOpenTest != null)
{
MonsterTestManager.SwapActiveMonsterTestManager(CurrentlyOpenTest);
}
MonsterTestManager.LoadTest();
WindowInstance.PreInit();
List<MonsterTestBase> AllTestStates = MonsterTestManager.EditorGetTestStateList();
foreach(MonsterTestBase CurrentTestState in AllTestStates)
{
MonsterTestBaseBox NewBox = (MonsterTestBaseBox)TypeUtils.GetEditorBoxForTypeString(CurrentTestState.GetEntityName(), WindowInstance, CurrentTestState);
WindowInstance.AddBox(NewBox);
}
WindowInstance.PostInit();
}
}
static public void FullGraphRefreshFromCurrentData()
{
if(WindowInstance != null)
{
WindowInstance.ClearAllBoxesAndLinks();
WindowInstance.PreInit();
List<MonsterTestBase> AllTestStates = MonsterTestManager.EditorGetTestStateList();
foreach(MonsterTestBase CurrentTestState in AllTestStates)
{
MonsterTestBaseBox NewBox = (MonsterTestBaseBox)TypeUtils.GetEditorBoxForTypeString(CurrentTestState.GetEntityName(), WindowInstance, CurrentTestState);
WindowInstance.AddBox(NewBox);
}
WindowInstance.PostInit();
}
}
[MenuItem ("Window/Monster/Test/Save Test", false, 2)]
static public void SaveTestStateList()
{
MonsterTestManager.GetActiveInstance().SaveEntities();
if(CurrentlyOpenTest != null)
{
CurrentlyOpenTest.EditorSaveMonsterTest();
}
MonsterTestWindow.GetInstance().SerializeBoxMetadata(true);
}
/* [MenuItem ("Dialogue/Tests/Conversation/Check For Missing VO", false, 15)]
static public void RunMissingAudioCheck()
{
RunTest(EditorTypeUtils.EntityTestType.TestForMissingAudio);
}
[MenuItem ("Dialogue/Tests/Conversation/Check For Missing Connections", false, 22)]
static public void RunMissingConnectionCheck()
{
RunTest(EditorTypeUtils.EntityTestType.TestForMissingConnections);
}*/
static public void RunTest(EditorTypeUtils.EntityTestType TestType)
{
if(WindowInstance != null)
{
foreach(EntityBox<MonsterTestBase> CurrentBox in WindowInstance.Boxes)
{
CurrentBox.RunChecks(TestType);
}
WindowInstance.Repaint();
}
}
/* [MenuItem ("Dialogue/Tests/Conversation/Fix One Way Links", false, 23)]
static public void FixOneWayLinks()
{
RunTest(EditorTypeUtils.EntityTestType.FixOneWayLinks);
}*/
public virtual MonsterTestBase GetCurrentlySelected()
{
object SelectedInst = SelectedBox.GetInspectorInstance();
if(SelectedInst != null)
{
if(typeof(MonsterTestBase).IsAssignableFrom(SelectedInst.GetType()))
{
return (MonsterTestBase)SelectedInst;
}
}
return null;
}
public override LinkedEntityManager<MonsterTestBase> GetManager()
{
return MonsterTestManager.GetActiveInstance();
}
public override void CreateInputOutputBoxes()
{
StartBox = new MonsterTestInputOutputBox(this, null, "Test Begins", true);
EndBox = new MonsterTestInputOutputBox(this, null, "Test Ends", false);
AddBox(StartBox);
AddBox(EndBox);
}
public virtual List<string> GetAllDerivedTestStateTypes()
{
List<Type> DerivedTypes = IgorRuntimeUtils.GetTypesInheritFrom<MonsterTestState>();
List<string> TypeNames = new List<string>();
foreach(Type CurrentType in DerivedTypes)
{
MonsterTestState StateInst = (MonsterTestState)Activator.CreateInstance(CurrentType);
TypeNames.Add(StateInst.GetEntityName());
}
return TypeNames;
}
public override void AddNoBoxContextMenuEntries(GenericMenu MenuToAddTo)
{
List<string> TypesToSuggest = GetAllDerivedTestStateTypes();
foreach(string CurrentType in TypesToSuggest)
{
MenuToAddTo.AddItem(new GUIContent("Add " + CurrentType), false, AddEntity, CurrentType);
}
// MenuToAddTo.AddItem(new GUIContent("Add Line"), false, AddLine);
MenuToAddTo.AddSeparator("");
MenuToAddTo.AddItem(new GUIContent("Reload Test From File"), false, ReloadTestFromFile);
MenuToAddTo.AddItem(new GUIContent("Organize Boxes"), false, OrganizeBoxes);
MenuToAddTo.AddItem(new GUIContent("Save Test"), false, SaveTestStateList);
}
public override void AddNewBoxContextMenuEntries(GenericMenu MenuToAddTo)
{
base.AddNewBoxContextMenuEntries(MenuToAddTo);
List<string> TypesToSuggest = GetAllDerivedTestStateTypes();
foreach(string CurrentType in TypesToSuggest)
{
MenuToAddTo.AddItem(new GUIContent("Connect new " + CurrentType), false, ConnectEntity, CurrentType);
}
// MenuToAddTo.AddItem(new GUIContent("Connect new Line"), false, ConnectLine);
}
public virtual void AddEntity(object EntityTypeName)
{
AddEntity((string)EntityTypeName);
}
public virtual void AddEntity(string EntityTypeName)
{
MonsterTestState NewState = (MonsterTestState)TypeUtils.GetNewObjectOfTypeString(EntityTypeName);
SetupNewBox(EntityTypeName, NewState);
}
public virtual void ConnectEntity(object EntityTypeName)
{
ConnectEntity((string)EntityTypeName);
}
public virtual void ConnectEntity(string EntityTypeName)
{
MonsterTestState NewState = (MonsterTestState)TypeUtils.GetNewObjectOfTypeString(EntityTypeName);
NewState.CreateStaticNodesIfNotPresent();
MonsterTestBaseBox NewBox = SetupNewBox(EntityTypeName, NewState);
if(NewBox.GetAllAnchors().Count > 0)
{
Anchor<MonsterTestBase> NewBoxAnchor = NewBox.GetAllAnchors()[0];
ConnectInputToOutput(NewBoxAnchor, StartingAnchorForNewBox);
}
}
public virtual MonsterTestBaseBox SetupNewBox(string EntityTypeName, MonsterTestState NewEntity)
{
MonsterTestManager.AddTestState(NewEntity);
MonsterTestBaseBox NewBox = (MonsterTestBaseBox)TypeUtils.GetEditorBoxForTypeString(EntityTypeName, MonsterTestWindow.WindowInstance, NewEntity);
NewBox.InitializeNewBox();
NewBox.MoveBoxTo(InputState.GetLocalMousePosition(this, -GetWindowOffset()));
MonsterTestWindow.WindowInstance.AddBox(NewBox);
return NewBox;
}
/* public virtual void AddLine()
{
Line NewLine = new Line();
SetupNewLineBox(NewLine);
}
public virtual void ConnectLine()
{
Line NewLine = new Line();
NewLine.CreateStaticNodesIfNotPresent();
LineBox NewBox = SetupNewLineBox(NewLine);
if(NewBox.GetAllAnchors().Count > 0)
{
Anchor<ConversationBase> NewBoxAnchor = NewBox.GetAllAnchors()[0];
ConnectInputToOutput(NewBoxAnchor, StartingAnchorForNewBox);
}
}
public virtual LineBox SetupNewLineBox(Line NewLine)
{
ConversationManager.AddConversation(NewLine);
LineBox NewBox = new LineBox(ConversationWindow.WindowInstance, NewLine);
NewBox.InitializeNewBox();
NewBox.MoveBoxTo(InputState.GetLocalMousePosition(this, -GetWindowOffset()));
ConversationWindow.WindowInstance.AddBox(NewBox);
return NewBox;
}*/
public override string GetBoxMetadataFile()
{
return MonsterTestCore.MonsterLocalDirectoryRoot + "/Config/Editor/MonsterTests/MonsterTestBoxes" + MonsterTestManager.GetActiveInstance().GetOwnerFilename() + ".xml";
}
public override void SaveRequested()
{
MonsterTestManager.SaveTest();
}
public override string[] GetSaveDialogText()
{
string[] DialogText = { "Save all test states for this test?", "Would you like to save all the test states for this test?", "Yes", "No" };
return DialogText;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace System.Net.Http.Headers
{
public class RangeItemHeaderValue : ICloneable
{
private long? _from;
private long? _to;
public long? From
{
get { return _from; }
}
public long? To
{
get { return _to; }
}
public RangeItemHeaderValue(long? from, long? to)
{
if (!from.HasValue && !to.HasValue)
{
throw new ArgumentException(SR.net_http_headers_invalid_range);
}
if (from.HasValue && (from.Value < 0))
{
throw new ArgumentOutOfRangeException(nameof(from));
}
if (to.HasValue && (to.Value < 0))
{
throw new ArgumentOutOfRangeException(nameof(to));
}
if (from.HasValue && to.HasValue && (from.Value > to.Value))
{
throw new ArgumentOutOfRangeException(nameof(from));
}
_from = from;
_to = to;
}
private RangeItemHeaderValue(RangeItemHeaderValue source)
{
Debug.Assert(source != null);
_from = source._from;
_to = source._to;
}
public override string ToString()
{
if (!_from.HasValue)
{
return "-" + _to.Value.ToString(NumberFormatInfo.InvariantInfo);
}
else if (!_to.HasValue)
{
return _from.Value.ToString(NumberFormatInfo.InvariantInfo) + "-";
}
return _from.Value.ToString(NumberFormatInfo.InvariantInfo) + "-" +
_to.Value.ToString(NumberFormatInfo.InvariantInfo);
}
public override bool Equals(object obj)
{
RangeItemHeaderValue other = obj as RangeItemHeaderValue;
if (other == null)
{
return false;
}
return ((_from == other._from) && (_to == other._to));
}
public override int GetHashCode()
{
if (!_from.HasValue)
{
return _to.GetHashCode();
}
else if (!_to.HasValue)
{
return _from.GetHashCode();
}
return _from.GetHashCode() ^ _to.GetHashCode();
}
// Returns the length of a range list. E.g. "1-2, 3-4, 5-6" adds 3 ranges to 'rangeCollection'. Note that empty
// list segments are allowed, e.g. ",1-2, , 3-4,,".
internal static int GetRangeItemListLength(string input, int startIndex,
ICollection<RangeItemHeaderValue> rangeCollection)
{
Debug.Assert(rangeCollection != null);
Debug.Assert(startIndex >= 0);
if ((string.IsNullOrEmpty(input)) || (startIndex >= input.Length))
{
return 0;
}
// Empty segments are allowed, so skip all delimiter-only segments (e.g. ", ,").
bool separatorFound = false;
int current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, startIndex, true, out separatorFound);
// It's OK if we didn't find leading separator characters. Ignore 'separatorFound'.
if (current == input.Length)
{
return 0;
}
RangeItemHeaderValue range = null;
while (true)
{
int rangeLength = GetRangeItemLength(input, current, out range);
if (rangeLength == 0)
{
return 0;
}
rangeCollection.Add(range);
current = current + rangeLength;
current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out separatorFound);
// If the string is not consumed, we must have a delimiter, otherwise the string is not a valid
// range list.
if ((current < input.Length) && !separatorFound)
{
return 0;
}
if (current == input.Length)
{
return current - startIndex;
}
}
}
internal static int GetRangeItemLength(string input, int startIndex, out RangeItemHeaderValue parsedValue)
{
Debug.Assert(startIndex >= 0);
// This parser parses number ranges: e.g. '1-2', '1-', '-2'.
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Caller must remove leading whitespace. If not, we'll return 0.
int current = startIndex;
// Try parse the first value of a value pair.
int fromStartIndex = current;
int fromLength = HttpRuleParser.GetNumberLength(input, current, false);
if (fromLength > HttpRuleParser.MaxInt64Digits)
{
return 0;
}
current = current + fromLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
// After the first value, the '-' character must follow.
if ((current == input.Length) || (input[current] != '-'))
{
// We need a '-' character otherwise this can't be a valid range.
return 0;
}
current++; // skip the '-' character
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
int toStartIndex = current;
int toLength = 0;
// If we didn't reach the end of the string, try parse the second value of the range.
if (current < input.Length)
{
toLength = HttpRuleParser.GetNumberLength(input, current, false);
if (toLength > HttpRuleParser.MaxInt64Digits)
{
return 0;
}
current = current + toLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
if ((fromLength == 0) && (toLength == 0))
{
return 0; // At least one value must be provided in order to be a valid range.
}
// Try convert first value to int64
long from = 0;
if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input, fromStartIndex, fromLength, out from))
{
return 0;
}
// Try convert second value to int64
long to = 0;
if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input, toStartIndex, toLength, out to))
{
return 0;
}
// 'from' must not be greater than 'to'
if ((fromLength > 0) && (toLength > 0) && (from > to))
{
return 0;
}
parsedValue = new RangeItemHeaderValue((fromLength == 0 ? (long?)null : (long?)from),
(toLength == 0 ? (long?)null : (long?)to));
return current - startIndex;
}
object ICloneable.Clone()
{
return new RangeItemHeaderValue(this);
}
}
}
| |
#define TEST_DIRECT
using System;
using System.Diagnostics;
using System.Collections.Generic;
using ProtoCore;
namespace ProtoAssociative.DependencyPass
{
//@TODO: Replace this whole structure with a DS-Hydrogen implementation
public class AST
{
public AST ()
{
}
public DependencyPass.DependencyTracker GetDemoTracker2(ProtoCore.Core core)
{
Associative.Scanner s = new Associative.Scanner(@"..\..\Scripts\expr.ds");
Associative.Parser p = new Associative.Parser(s, core);
p.Parse();
CodeBlockNode code = p.codeblock as CodeBlockNode;
DependencyTracker tempTracker = new DependencyTracker();
Dictionary<string, List<Node>> names = new Dictionary<string, List<Node>>();
code.ConsolidateNames(ref(names));
tempTracker.GenerateDependencyGraph(code.Body);
return tempTracker;
}
public DependencyPass.DependencyTracker GetDemoTracker3(out ProtoCore.DSASM.SymbolTable symbols, string pathFilename, ProtoCore.Core core)
{
Associative.Scanner s = new Associative.Scanner(pathFilename);
Associative.Parser p = new Associative.Parser(s, core);
p.Parse();
CodeBlockNode code = p.codeblock as CodeBlockNode;
symbols = code.symbols;
DependencyTracker tempTracker = new DependencyTracker();
#if TEST_DIRECT
foreach (Node node in code.Body)
{
tempTracker.AllNodes.Add(node);
}
#else
Dictionary<string, List<Node>> names = new Dictionary<string, List<Node>>();
code.ConsolidateNames(ref(names));
tempTracker.GenerateDependencyGraph(code.Body);
#endif
return tempTracker;
}
/*
public DependencyPass.DependencyTracker generateAST(ProtoCore.CodeBlock codeblock)
{
DependencyTracker tempTracker = new DependencyTracker();
foreach (Object obj in codeblock.Body)
{
Debug.Assert(obj is ProtoAssociative.DependencyPass.Node);
Node node = obj as ProtoAssociative.DependencyPass.Node;
tempTracker.AllNodes.Add(node);
}
return tempTracker;
}
* */
public DependencyPass.DependencyTracker GetDemoTracker()
{
IdentifierNode a = new IdentifierNode();
a.Value = "1..1000..+1";
FunctionCallNode b = new FunctionCallNode();
b.Function = new IdentifierNode() { Value = "SQRT" };
b.FormalArguments.Add(a);
BinaryExpressionNode c = new BinaryExpressionNode();
c.LeftNode = a;
c.Optr = ProtoCore.DSASM.Operator.mul;
IdentifierNode _2Node = new IdentifierNode() { Value = "2" };
c.RightNode = _2Node;
BinaryExpressionNode d = new BinaryExpressionNode();
d.LeftNode = c;
d.RightNode = c;
d.Optr = ProtoCore.DSASM.Operator.mul;
FunctionCallNode e = new FunctionCallNode();
e.Function = new IdentifierNode() { Value = "LineFromPoint" };
e.FormalArguments.Add(a);
e.FormalArguments.Add(b);
e.FormalArguments.Add(d);
Node f = new FunctionCallNode() { Function = new IdentifierNode() { Value = "Trim" } };
Node g = new FunctionCallNode() { Function = new IdentifierNode() { Value = "Rotate" } };
DependencyPass.DependencyTracker tracker = new DependencyPass.DependencyTracker();
tracker.AllNodes.Add(a);
tracker.AllNodes.Add(b);
tracker.AllNodes.Add(c);
tracker.AllNodes.Add(_2Node);
tracker.AllNodes.Add(d);
tracker.AllNodes.Add(e);
tracker.AllNodes.Add(f);
tracker.AllNodes.Add(g);
tracker.DirectContingents.Add(a, new List<Node>() { });
tracker.DirectContingents.Add(_2Node, new List<Node>() { });
tracker.DirectContingents.Add(b, new List<Node>() { a });
tracker.DirectContingents.Add(c, new List<Node>() { a, _2Node });
tracker.DirectContingents.Add(d, new List<Node>() { c });
tracker.DirectContingents.Add(e, new List<Node>() { a, b, d });
tracker.DirectContingents.Add(f, new List<Node>() { e });
tracker.DirectContingents.Add(g, new List<Node>() { f });
tracker.DirectDependents.Add(a, new List<Node>() {b, c, e});
tracker.DirectDependents.Add(b, new List<Node>() {e});
tracker.DirectDependents.Add(c, new List<Node>() {d});
tracker.DirectDependents.Add(d, new List<Node>() {e});
tracker.DirectDependents.Add(e, new List<Node>() {f});
tracker.DirectDependents.Add(f, new List<Node>() {g});
tracker.DirectDependents.Add(g, new List<Node>() {});
tracker.DirectDependents.Add(_2Node, new List<Node>() {c});
return tracker;
}
// a = 25
// b = 4 + 20 / 5
// c = a - 20 * 5
public DependencyPass.DependencyTracker GetDemoTrackerJun()
{
DependencyPass.DependencyTracker tracker = new DependencyPass.DependencyTracker();
string varIdent = null;
//========================================================
// a = 25
BinaryExpressionNode i1 = new BinaryExpressionNode();
varIdent = "a";
IdentifierNode fAssignLeft = new IdentifierNode() { Value = varIdent, type = /*SDD*/(int)ProtoCore.PrimitiveType.kTypeVar };
// SDD - automatic allocation
//tracker.Allocate(varIdent, (int)FusionCore.DSASM.Constants.kGlobalScope, (int)FusionCore.DSASM.Constants.kPrimitiveSize);
i1.LeftNode = fAssignLeft;
i1.Optr = ProtoCore.DSASM.Operator.assign;
IdentifierNode fAssignRight = new IdentifierNode() { Value = "25", type = (int)ProtoCore.PrimitiveType.kTypeInt };
i1.RightNode = fAssignRight;
//========================================================
// b = 4 + 20 / 5
// 20 / 5
BinaryExpressionNode sDiv = new BinaryExpressionNode();
IdentifierNode sDivLeft = new IdentifierNode() { Value = "20", /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeInt };
sDiv.LeftNode = sDivLeft;
sDiv.Optr = ProtoCore.DSASM.Operator.div;
IdentifierNode sDivRight = new IdentifierNode() { Value = "5", /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeInt };
sDiv.RightNode = sDivRight;
// 4 + ( 20 / 5 )
BinaryExpressionNode sAdd = new BinaryExpressionNode();
IdentifierNode sAddLeft = new IdentifierNode() { Value = "4", /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeInt };
sAdd.LeftNode = sAddLeft;
sAdd.Optr = ProtoCore.DSASM.Operator.add;
BinaryExpressionNode sAddRight = new BinaryExpressionNode();
sAddRight = sDiv;
sAdd.RightNode = sAddRight;
// b = 4 + 20 / 5
BinaryExpressionNode i2 = new BinaryExpressionNode();
varIdent = "b";
IdentifierNode sAssignLeft = new IdentifierNode() { Value = varIdent, /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeVar };
// SDD - automatic allocation
//tracker.Allocate(varIdent, (int)FusionCore.DSASM.Constants.kGlobalScope, (int)FusionCore.DSASM.Constants.kPrimitiveSize);
i2.LeftNode = sAssignLeft;
i2.Optr = ProtoCore.DSASM.Operator.assign;
BinaryExpressionNode sAssignRight = new BinaryExpressionNode();
sAssignRight = sAdd;
i2.RightNode = sAssignRight;
// c = a - 20 * 5
// 20 * 5
BinaryExpressionNode sMul = new BinaryExpressionNode();
IdentifierNode sMulLeft = new IdentifierNode() { Value = "20", /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeInt };
sMul.LeftNode = sMulLeft;
sMul.Optr = ProtoCore.DSASM.Operator.mul;
IdentifierNode sMulRight = new IdentifierNode() { Value = "5", /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeInt };
sMul.RightNode = sMulRight;
// a - ( 20 * 5 )
BinaryExpressionNode sSub = new BinaryExpressionNode();
IdentifierNode sSubLeft = new IdentifierNode() { Value = "a", /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeVar };
sSub.LeftNode = sSubLeft;
sSub.Optr = ProtoCore.DSASM.Operator.sub;
BinaryExpressionNode sSubRight = new BinaryExpressionNode();
sSubRight = sMul;
sSub.RightNode = sSubRight;
// c = a - 20 * 5
BinaryExpressionNode i3 = new BinaryExpressionNode();
varIdent = "c";
IdentifierNode si3Left = new IdentifierNode() { Value = varIdent, /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeVar };
// SDD - automatic allocation
//tracker.Allocate(varIdent, (int)FusionCore.DSASM.Constants.kGlobalScope, (int)FusionCore.DSASM.Constants.kPrimitiveSize);
i3.LeftNode = si3Left;
i3.Optr = ProtoCore.DSASM.Operator.assign;
BinaryExpressionNode si3Right = new BinaryExpressionNode();
si3Right = sSub;
i3.RightNode = si3Right;
tracker.AllNodes.Add(i1);
tracker.AllNodes.Add(i2);
tracker.AllNodes.Add(i3);
return tracker;
}
}
public abstract class Node: ProtoCore.NodeBase
{
private static int sID = 0;
//allow the assignment node to be part of dependency struture?
//this lead to entiely different set of results in optimization
protected static bool AssignNodeDependencyEnabled = true;
//even if the '=' is not a link between LHS and RHS, can we keep it in dependency graph?
//protected static bool AssignNodeDependencyEnabledLame = true;
public int ID
{
get;
private set;
}
public Node()
{
ID = ++sID;
}
/// <summary>
/// Optional name for the node
/// </summary>
public string Name {
get;
set;
}
public virtual void GenerateDependencyGraph(DependencyTracker tracker)
{
tracker.AddNode(this);//get rid of this later
IEnumerable<Node> contingents = getContingents();
foreach (Node node in contingents)
{
tracker.AddNode(node);
if (node == null)
continue;
tracker.AddDirectContingent(this, node);
tracker.AddDirectDependent(node, this);
node.GenerateDependencyGraph(tracker);
}
}
public virtual IEnumerable<Node> getContingents()
{
return new List<Node>();
}
public virtual void ConsolidateNames(ref Dictionary<string, List<Node>> names)
{
}
protected static void Consolidate(ref Dictionary<string, List<Node>> names, ref IdentifierNode node)
{
if (null != node.Name)
{
if (names.ContainsKey(node.Name))
{
List<Node> candidates = names[node.Name];
node = candidates[candidates.Count - 1] as IdentifierNode;
}
else
{
//symbol not defined.
//should we ignore this until somebody else defines a symbol?
//or add the symbol?
//throw new KeyNotFoundException();
List<Node> candidates = new List<Node>();
candidates.Add(node);
names.Add(node.Name, candidates);
}
}
}
}
public class LanguageBlockNode : Node
{
public LanguageBlockNode()
{
codeblock = new ProtoCore.LanguageCodeBlock();
}
public ProtoCore.LanguageCodeBlock codeblock { get; set; }
public ProtoCore.NodeBase codeBlockNode { get; set; }
}
/// <summary>
/// This node will be used by the optimiser
/// </summary>
public class MergeNode : Node
{
public List<Node> MergedNodes {
get;
private set;
}
public MergeNode ()
{
MergedNodes = new List<Node>();
}
public override IEnumerable<Node> getContingents()
{
return MergedNodes;
}
public override void ConsolidateNames(ref Dictionary<string, List<Node>> names)
{
foreach (Node node in MergedNodes)
node.ConsolidateNames(ref(names));
}
}
public class IdentifierNode : Node
{
public IdentifierNode()
{
type = (int)ProtoCore.PrimitiveType.kInvalidType;
}
public int type {
get;
set;
}
public ProtoCore.PrimitiveType datatype {
get;
set;
}
public string Value {
get;
set;
}
public ArrayNode ArrayDimensions
{
get;
set;
}
public List<Node> ReplicationGuides
{
get;
set;
}
public override void ConsolidateNames(ref Dictionary<string, List<Node>> names)
{
throw new NotImplementedException(); //we should not be here at all. the parent node should take care.
//disabling execption as functioncalls will still need to add the nodes to
}
}
public class IdentifierListNode : Node
{
public Node LeftNode
{
get;
set;
}
public ProtoCore.DSASM.Operator Optr
{
get;
set;
}
public Node RightNode
{
get;
set;
}
}
public class IntNode : Node
{
public string value { get; set; }
}
public class DoubleNode : Node
{
public string value { get; set; }
}
public class BooleanNode : Node
{
public string value { get; set; }
}
public class CharNode : Node
{
public string value { get; set; }
}
public class StringNode : Node
{
public string value { get; set; }
}
public class NullNode : Node
{
}
public class ReturnNode : Node
{
public Node ReturnExpr
{
get;
set;
}
}
public class FunctionCallNode : Node
{
public Node Function { get; set; }
public List<Node> FormalArguments { get; set; }
public FunctionCallNode ()
{
FormalArguments = new List<Node>();
}
public override IEnumerable<Node> getContingents()
{
List<Node> contingents = new List<Node>(FormalArguments) ;
contingents.Add(Function);
return contingents;
}
public override void ConsolidateNames(ref Dictionary<string, List<Node>> names)
{
List<Node> newFormalArguments = new List<Node>();
//replace the names in arguments by current names in calling context
foreach(Node argument in FormalArguments)
{
Node newArgument = argument;
IdentifierNode terminalNode = newArgument as IdentifierNode;
if (terminalNode != null)
{
Consolidate(ref(names), ref(terminalNode));
newArgument = terminalNode;
}
else
{
argument.ConsolidateNames(ref(names));
}
newFormalArguments.Add(newArgument);
}
FormalArguments = newFormalArguments;
}
}
public class QualifiedNode : Node
{
public Node Value { get; set; }
public List<Node> ReplicationGuides { get; set; }
public override IEnumerable<Node> getContingents()
{
List<Node> contingents = new List<Node>(ReplicationGuides);
contingents.Add(Value);
return contingents;
}
public override void ConsolidateNames(ref Dictionary<string, List<Node>> names)
{
Value.ConsolidateNames(ref(names));
}
}
public class VarDeclNode : Node
{
public VarDeclNode()
{
memregion = ProtoCore.DSASM.MemoryRegion.kInvalidRegion;
}
public ProtoCore.DSASM.MemoryRegion memregion { get; set; }
public ProtoCore.Type ArgumentType { get; set; }
public Node NameNode { get; set; }
public ProtoCore.DSASM.AccessSpecifier access { get; set; }
public override void ConsolidateNames(ref Dictionary<string, List<Node>> names)
{
if (names.ContainsKey(NameNode.Name))
throw new Exception();
List<Node> records = new List<Node>();
records.Add(NameNode);
names.Add(NameNode.Name, records);
Dictionary<string, List<Node>> localnames = new Dictionary<string, List<Node>>();
localnames.Add(NameNode.Name, records);
}
}
public class ArgumentSignatureNode : Node
{
public ArgumentSignatureNode()
{
Arguments = new List<VarDeclNode>();
}
public List<VarDeclNode> Arguments { get; set; }
public void AddArgument(VarDeclNode arg)
{
Arguments.Add(arg);
}
public override IEnumerable<Node> getContingents()
{
List<Node> contingents = new List<Node>(Arguments);
return contingents;
}
public override void ConsolidateNames(ref Dictionary<string, List<Node>> names)
{
foreach (Node node in Arguments)
node.ConsolidateNames(ref(names));
}
}
public class CodeBlockNode : Node
{
public ProtoCore.DSASM.SymbolTable symbols { get; set; }
public ProtoCore.DSASM.ProcedureTable procTable { get; set; }
public CodeBlockNode()
{
Body = new List<Node>();
symbols = new ProtoCore.DSASM.SymbolTable("AST generated", ProtoCore.DSASM.Constants.kInvalidIndex);
procTable = new ProtoCore.DSASM.ProcedureTable(ProtoCore.DSASM.Constants.kInvalidIndex);
}
public List<Node> Body { get; set; }
public override IEnumerable<Node> getContingents()
{
return new List<Node>(Body);
}
public override void ConsolidateNames(ref Dictionary<string, List<Node>> names)
{
//todo make a decision whether to pass out the local names.
foreach (Node node in Body)
{
node.ConsolidateNames(ref(names));
}
}
}
public class ClassDeclNode : Node
{
public ClassDeclNode()
{
varlist = new List<Node>();
funclist = new List<Node>();
}
public string name { get; set; }
public List<string> superClass { get; set; }
public List<Node> varlist { get; set; }
public List<Node> funclist { get; set; }
}
public class ConstructorDefinitionNode : Node
{
public int localVars { get; set; }
public ArgumentSignatureNode Signature { get; set; }
public Node Pattern { get; set; }
public ProtoCore.Type ReturnType { get; set; }
public CodeBlockNode FunctionBody { get; set; }
public FunctionCallNode baseConstr { get; set; }
public ProtoCore.DSASM.AccessSpecifier access { get; set; }
}
public class FunctionDefinitionNode : Node
{
public CodeBlockNode FunctionBody { get; set; }
public ProtoCore.Type ReturnType { get; set; }
public ArgumentSignatureNode Singnature { get; set; }
public Node Pattern { get; set; }
public bool IsExternLib { get; set; }
public bool IsDNI { get; set; }
public string ExternLibName { get; set; }
public ProtoCore.DSASM.AccessSpecifier access { get; set; }
public override IEnumerable<Node> getContingents()
{
List<Node> contingents = new List<Node>();
contingents.Add(FunctionBody);
contingents.Add(Singnature);
contingents.Add(Pattern);
return contingents;
}
public override void ConsolidateNames(ref Dictionary<string, List<Node>> names)
{
Dictionary<string, List<Node>> localNames = new Dictionary<string, List<Node>>();
Singnature.ConsolidateNames(ref(localNames));
Pattern.ConsolidateNames(ref(localNames));
FunctionBody.ConsolidateNames(ref(localNames));
if (names.ContainsKey(Name))
{
throw new Exception();
}
List<Node> namelist = new List<Node>();
namelist.Add(this);
names.Add(Name, namelist);
}
}
public class IfStatementNode : Node
{
public Node ifExprNode { get; set; }
public List<Node> IfBody { get; set; }
public List<Node> ElseBody { get; set; }
}
public class InlineConditionalNode : Node
{
public Node ConditionExpression { get; set; }
public Node TrueExpression { get; set; }
public Node FalseExpression { get; set; }
}
public class BinaryExpressionNode : Node
{
public Node LeftNode { get; set; }
public ProtoCore.DSASM.Operator Optr { get; set; }
public Node RightNode { get; set; }
public override IEnumerable<Node> getContingents()
{
List<Node> contingents = new List<Node>();
if (Optr != ProtoCore.DSASM.Operator.assign)
{
contingents.Add(LeftNode);
}
//if we have enabled the '=' node to be a part of depencency, then we return RHS, no matter what
if (AssignNodeDependencyEnabled || Optr != ProtoCore.DSASM.Operator.assign)
{
contingents.Add(RightNode);
}
return contingents;
}
public override void GenerateDependencyGraph(DependencyTracker tracker)
{
base.GenerateDependencyGraph(tracker);
if (Optr == ProtoCore.DSASM.Operator.assign)
{
//so do we set dependency between LeftNode and '=' or LeftNode and RightNode : may be later is better
if (AssignNodeDependencyEnabled)
{
//if we have enabled the '=' node to be a part of depencency, then we already handled RHS as a contingent
//so skip it
tracker.AddNode(LeftNode);
tracker.AddDirectContingent(LeftNode, this);
tracker.AddDirectDependent(this, LeftNode);
}
else
{
//if(AssignNodeDependencyEnabledLame)
//{
// tracker.AddDirectContingent(this, RightNode); //? still keep in dependency?
// tracker.AddDirectContingent(LeftNode, RightNode);
//}
tracker.AddNode(RightNode);
tracker.AddNode(LeftNode);
tracker.AddDirectContingent(LeftNode, RightNode);
tracker.AddDirectDependent(RightNode, LeftNode);
RightNode.GenerateDependencyGraph(tracker);
}
}
}
public override void ConsolidateNames(ref Dictionary<string, List<Node>> names)
{
IdentifierNode rightTerminalNode = RightNode as IdentifierNode;
if (rightTerminalNode != null)
{
if (Optr != ProtoCore.DSASM.Operator.dot)
{
//replace RHS
Consolidate(ref(names), ref(rightTerminalNode));
RightNode = rightTerminalNode;
}
}
else
{
RightNode.ConsolidateNames(ref(names));
}
//left has to be done 2nd, because in case of modifiers, we dont want to
//replace the node on RHS by a node on LHS. So a modifier stack name is not unique.
IdentifierNode leftTerminalNode = LeftNode as IdentifierNode;
if (leftTerminalNode != null)
{
if (Optr != ProtoCore.DSASM.Operator.assign)
{
//replace LHS
Consolidate(ref(names), ref(leftTerminalNode));
LeftNode = leftTerminalNode;
}
else
{
if (leftTerminalNode.Name != null)
{
if (names.ContainsKey(leftTerminalNode.Name))
{
List<Node> candidates = names[leftTerminalNode.Name];
candidates.Add(leftTerminalNode);
}
else
{
//append LHS
List<Node> candidates = new List<Node>();
candidates.Add(leftTerminalNode);
names.Add(leftTerminalNode.Name, candidates);
}
}
}
}
else
{
LeftNode.ConsolidateNames(ref(names));
}
}
}
public class UnaryExpressionNode : Node
{
public ProtoCore.DSASM.UnaryOperator Operator { get; set; }
public Node Expression { get; set; }
public override IEnumerable<Node> getContingents()
{
List<Node> contingents = new List<Node>(1);
contingents.Add(Expression);
return contingents;
}
public override void ConsolidateNames(ref Dictionary<string, List<Node>> names)
{
Expression.ConsolidateNames(ref(names));
}
}
public class ModifierStackNode : Node
{
public ModifierStackNode ()
{
ElementNodes = new List<Node>();
AtNames = new Dictionary<string, Node>();
}
public void AddElementNode(Node n, string name)
{
ElementNodes.Add(n);
if ("" != name)
{
AtNames.Add(name, n);
BinaryExpressionNode o = n as BinaryExpressionNode;
IdentifierNode t = o.LeftNode as IdentifierNode;
BinaryExpressionNode e = new BinaryExpressionNode();
e.LeftNode = new IdentifierNode() { Value = name, Name = name, type = t.type, datatype = t.datatype };
e.RightNode = t;
e.Optr = ProtoCore.DSASM.Operator.assign;
ElementNodes.Add(e);
}
}
public List<Node> ElementNodes { get; private set; }
public Node ReturnNode { get; set; }
public Dictionary<string, Node> AtNames { get; private set; }
public override IEnumerable<Node> getContingents()
{
List<Node> contingents = new List<Node>(ElementNodes);
contingents.Add(ReturnNode);
return contingents;
}
}
public class RangeExprNode : Node
{
public RangeExprNode()
{
IntNode defaultStep = new IntNode();
defaultStep.value = "1";
StepNode = defaultStep;
}
public Node FromNode { get; set; }
public Node ToNode { get; set; }
public Node StepNode { get; set; }
public ProtoCore.DSASM.RangeStepOperator stepoperator { get; set; }
}
public class ExprListNode : Node
{
public ExprListNode()
{
list = new List<Node>();
}
public List<Node> list { get; set; }
}
public class ForLoopNode : Node
{
public Node id { get; set; }
public Node expression { get; set; }
public List<Node> body { get; set; }
}
public class ArrayNode : Node
{
public ArrayNode()
{
Expr = null;
Type = null;
}
public Node Expr { get; set; }
public Node Type { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace System.DirectoryServices.AccountManagement
{
#if TESTHOOK
public class AccountInfo
#else
internal class AccountInfo
#endif
{
//
// Properties exposed to the public through AuthenticablePrincipal
//
// AccountLockoutTime
private Nullable<DateTime> _accountLockoutTime = null;
private LoadState _accountLockoutTimeLoaded = LoadState.NotSet;
public Nullable<DateTime> AccountLockoutTime
{
get
{
return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _accountLockoutTime, PropertyNames.AcctInfoAcctLockoutTime, ref _accountLockoutTimeLoaded);
}
}
// LastLogon
private Nullable<DateTime> _lastLogon = null;
private LoadState _lastLogonLoaded = LoadState.NotSet;
public Nullable<DateTime> LastLogon
{
get
{
return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _lastLogon, PropertyNames.AcctInfoLastLogon, ref _lastLogonLoaded);
}
}
// PermittedWorkstations
private PrincipalValueCollection<string> _permittedWorkstations = new PrincipalValueCollection<string>();
private LoadState _permittedWorkstationsLoaded = LoadState.NotSet;
public PrincipalValueCollection<string> PermittedWorkstations
{
get
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoPermittedWorkstations))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
return _owningPrincipal.HandleGet<PrincipalValueCollection<string>>(ref _permittedWorkstations, PropertyNames.AcctInfoPermittedWorkstations, ref _permittedWorkstationsLoaded);
}
}
// PermittedLogonTimes
// We have to handle the change-tracking for this differently than for the other properties, because
// a byte[] is mutable. After calling the get accessor, the app can change the permittedLogonTimes,
// without needing to ever call the set accessor. Therefore, rather than a simple "changed" flag set
// by the set accessor, we need to track the original value of the property, and flag it as changed
// if current value != original value.
private byte[] _permittedLogonTimes = null;
private byte[] _permittedLogonTimesOriginal = null;
private LoadState _permittedLogonTimesLoaded = LoadState.NotSet;
public byte[] PermittedLogonTimes
{
get
{
return _owningPrincipal.HandleGet<byte[]>(ref _permittedLogonTimes, PropertyNames.AcctInfoPermittedLogonTimes, ref _permittedLogonTimesLoaded);
}
set
{
// We don't use HandleSet<T> here because of the slightly non-standard implementation of the change-tracking
// for this property.
// Check that we actually support this propery in our store
//this.owningPrincipal.CheckSupportedProperty(PropertyNames.AcctInfoPermittedLogonTimes);
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoPermittedLogonTimes))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
// If we get to this point we know that the value of the property has changed and we should not load it from the store.
// If value is retrived the state is set to loaded. Even if user modifies the reference we will
// not overwrite it because we mark it as loaded.
// If the user sets it before reading it we mark it as changed. When the users accesses it we just return the current
// value. All change tracking to the store is done off of an actual object comparison because users can change the value
// either through property set or modifying the reference returned.
_permittedLogonTimesLoaded = LoadState.Changed;
_permittedLogonTimes = value;
}
}
// AccountExpirationDate
private Nullable<DateTime> _expirationDate = null;
private LoadState _expirationDateChanged = LoadState.NotSet;
public Nullable<DateTime> AccountExpirationDate
{
get
{
return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _expirationDate, PropertyNames.AcctInfoExpirationDate, ref _expirationDateChanged);
}
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoExpirationDate))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
_owningPrincipal.HandleSet<Nullable<DateTime>>(ref _expirationDate, value, ref _expirationDateChanged,
PropertyNames.AcctInfoExpirationDate);
}
}
// SmartcardLogonRequired
private bool _smartcardLogonRequired = false;
private LoadState _smartcardLogonRequiredChanged = LoadState.NotSet;
public bool SmartcardLogonRequired
{
get
{
return _owningPrincipal.HandleGet<bool>(ref _smartcardLogonRequired, PropertyNames.AcctInfoSmartcardRequired, ref _smartcardLogonRequiredChanged);
}
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoSmartcardRequired))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
_owningPrincipal.HandleSet<bool>(ref _smartcardLogonRequired, value, ref _smartcardLogonRequiredChanged,
PropertyNames.AcctInfoSmartcardRequired);
}
}
// DelegationPermitted
private bool _delegationPermitted = false;
private LoadState _delegationPermittedChanged = LoadState.NotSet;
public bool DelegationPermitted
{
get
{
return _owningPrincipal.HandleGet<bool>(ref _delegationPermitted, PropertyNames.AcctInfoDelegationPermitted, ref _delegationPermittedChanged);
}
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoDelegationPermitted))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
_owningPrincipal.HandleSet<bool>(ref _delegationPermitted, value, ref _delegationPermittedChanged,
PropertyNames.AcctInfoDelegationPermitted);
}
}
// BadLogonCount
private int _badLogonCount = 0;
private LoadState _badLogonCountChanged = LoadState.NotSet;
public int BadLogonCount
{
get
{
return _owningPrincipal.HandleGet<int>(ref _badLogonCount, PropertyNames.AcctInfoBadLogonCount, ref _badLogonCountChanged);
}
}
// HomeDirectory
private string _homeDirectory = null;
private LoadState _homeDirectoryChanged = LoadState.NotSet;
public string HomeDirectory
{
get
{
return _owningPrincipal.HandleGet<string>(ref _homeDirectory, PropertyNames.AcctInfoHomeDirectory, ref _homeDirectoryChanged);
}
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoHomeDirectory))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
_owningPrincipal.HandleSet<string>(ref _homeDirectory, value, ref _homeDirectoryChanged,
PropertyNames.AcctInfoHomeDirectory);
}
}
// HomeDrive
private string _homeDrive = null;
private LoadState _homeDriveChanged = LoadState.NotSet;
public string HomeDrive
{
get
{
return _owningPrincipal.HandleGet<string>(ref _homeDrive, PropertyNames.AcctInfoHomeDrive, ref _homeDriveChanged);
}
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoHomeDrive))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
_owningPrincipal.HandleSet<string>(ref _homeDrive, value, ref _homeDriveChanged,
PropertyNames.AcctInfoHomeDrive);
}
}
// ScriptPath
private string _scriptPath = null;
private LoadState _scriptPathChanged = LoadState.NotSet;
public string ScriptPath
{
get
{
return _owningPrincipal.HandleGet<string>(ref _scriptPath, PropertyNames.AcctInfoScriptPath, ref _scriptPathChanged);
}
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoScriptPath))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
_owningPrincipal.HandleSet<string>(ref _scriptPath, value, ref _scriptPathChanged,
PropertyNames.AcctInfoScriptPath);
}
}
//
// Methods exposed to the public through AuthenticablePrincipal
//
public bool IsAccountLockedOut()
{
if (!_owningPrincipal.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "IsAccountLockedOut: sending lockout query");
Debug.Assert(_owningPrincipal.Context != null);
return _owningPrincipal.GetStoreCtxToUse().IsLockedOut(_owningPrincipal);
}
else
{
// A Principal that hasn't even been persisted can't be locked out
return false;
}
}
public void UnlockAccount()
{
if (!_owningPrincipal.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "UnlockAccount: sending unlock request");
Debug.Assert(_owningPrincipal.Context != null);
_owningPrincipal.GetStoreCtxToUse().UnlockAccount(_owningPrincipal);
}
// Since a Principal that's not persisted can't have been locked-out,
// there's nothing to do in that case
}
//
// Internal constructor
//
internal AccountInfo(AuthenticablePrincipal principal)
{
_owningPrincipal = principal;
}
//
// Private implementation
//
private AuthenticablePrincipal _owningPrincipal;
//
// Load/Store
//
//
// Loading with query results
//
internal void LoadValueIntoProperty(string propertyName, object value)
{
// GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "LoadValueIntoProperty: name=" + propertyName + " value=" + value.ToString());
switch (propertyName)
{
case (PropertyNames.AcctInfoAcctLockoutTime):
_accountLockoutTime = (Nullable<DateTime>)value;
_accountLockoutTimeLoaded = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoLastLogon):
_lastLogon = (Nullable<DateTime>)value;
_lastLogonLoaded = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoPermittedWorkstations):
_permittedWorkstations.Load((List<string>)value);
_permittedWorkstationsLoaded = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoPermittedLogonTimes):
_permittedLogonTimes = (byte[])value;
_permittedLogonTimesOriginal = (byte[])((byte[])value).Clone();
_permittedLogonTimesLoaded = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoExpirationDate):
_expirationDate = (Nullable<DateTime>)value;
_expirationDateChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoSmartcardRequired):
_smartcardLogonRequired = (bool)value;
_smartcardLogonRequiredChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoDelegationPermitted):
_delegationPermitted = (bool)value;
_delegationPermittedChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoBadLogonCount):
_badLogonCount = (int)value;
_badLogonCountChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoHomeDirectory):
_homeDirectory = (string)value;
_homeDirectoryChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoHomeDrive):
_homeDrive = (string)value;
_homeDriveChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoScriptPath):
_scriptPath = (string)value;
_scriptPathChanged = LoadState.Loaded;
break;
default:
Debug.Fail($"AccountInfo.LoadValueIntoProperty: fell off end looking for {propertyName}");
break;
}
}
//
// Getting changes to persist (or to build a query from a QBE filter)
//
// Given a property name, returns true if that property has changed since it was loaded, false otherwise.
internal bool GetChangeStatusForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "GetChangeStatusForProperty: name=" + propertyName);
switch (propertyName)
{
case (PropertyNames.AcctInfoPermittedWorkstations):
return _permittedWorkstations.Changed;
case (PropertyNames.AcctInfoPermittedLogonTimes):
// If they're equal, they have _not_ changed
if ((_permittedLogonTimes == null) && (_permittedLogonTimesOriginal == null))
return false;
if ((_permittedLogonTimes == null) || (_permittedLogonTimesOriginal == null))
return true;
return !Utils.AreBytesEqual(_permittedLogonTimes, _permittedLogonTimesOriginal);
case (PropertyNames.AcctInfoExpirationDate):
return _expirationDateChanged == LoadState.Changed;
case (PropertyNames.AcctInfoSmartcardRequired):
return _smartcardLogonRequiredChanged == LoadState.Changed;
case (PropertyNames.AcctInfoDelegationPermitted):
return _delegationPermittedChanged == LoadState.Changed;
case (PropertyNames.AcctInfoHomeDirectory):
return _homeDirectoryChanged == LoadState.Changed;
case (PropertyNames.AcctInfoHomeDrive):
return _homeDriveChanged == LoadState.Changed;
case (PropertyNames.AcctInfoScriptPath):
return _scriptPathChanged == LoadState.Changed;
default:
Debug.Fail($"AccountInfo.GetChangeStatusForProperty: fell off end looking for {propertyName}");
return false;
}
}
// Given a property name, returns the current value for the property.
internal object GetValueForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "GetValueForProperty: name=" + propertyName);
switch (propertyName)
{
case (PropertyNames.AcctInfoPermittedWorkstations):
return _permittedWorkstations;
case (PropertyNames.AcctInfoPermittedLogonTimes):
return _permittedLogonTimes;
case (PropertyNames.AcctInfoExpirationDate):
return _expirationDate;
case (PropertyNames.AcctInfoSmartcardRequired):
return _smartcardLogonRequired;
case (PropertyNames.AcctInfoDelegationPermitted):
return _delegationPermitted;
case (PropertyNames.AcctInfoHomeDirectory):
return _homeDirectory;
case (PropertyNames.AcctInfoHomeDrive):
return _homeDrive;
case (PropertyNames.AcctInfoScriptPath):
return _scriptPath;
default:
Debug.Fail($"AccountInfo.GetValueForProperty: fell off end looking for {propertyName}");
return null;
}
}
// Reset all change-tracking status for all properties on the object to "unchanged".
internal void ResetAllChangeStatus()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "ResetAllChangeStatus");
_permittedWorkstations.ResetTracking();
_permittedLogonTimesOriginal = (_permittedLogonTimes != null) ?
(byte[])_permittedLogonTimes.Clone() :
null;
_expirationDateChanged = (_expirationDateChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_smartcardLogonRequiredChanged = (_smartcardLogonRequiredChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_delegationPermittedChanged = (_delegationPermittedChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_homeDirectoryChanged = (_homeDirectoryChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_homeDriveChanged = (_homeDriveChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_scriptPathChanged = (_scriptPathChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
namespace OnlineGraph
{
public class SymbolCollection : SortableCollectionBase, ICustomTypeDescriptor
{
#region CollectionBase implementation
public SymbolCollection()
{
//In your collection class constructor add this line.
//set the SortObjectType for sorting.
base.SortObjectType = typeof(SymbolHelper);
}
public SymbolHelper this[int index]
{
get
{
return ((SymbolHelper)List[index]);
}
set
{
List[index] = value;
}
}
public int Add(SymbolHelper value)
{
return (List.Add(value));
}
public int IndexOf(SymbolHelper value)
{
return (List.IndexOf(value));
}
public void Insert(int index, SymbolHelper value)
{
List.Insert(index, value);
}
public void Remove(SymbolHelper value)
{
List.Remove(value);
}
public bool Contains(SymbolHelper value)
{
// If value is not of type Int16, this will return false.
return (List.Contains(value));
}
protected override void OnInsert(int index, Object value)
{
// Insert additional code to be run only when inserting values.
}
protected override void OnRemove(int index, Object value)
{
// Insert additional code to be run only when removing values.
}
protected override void OnSet(int index, Object oldValue, Object newValue)
{
// Insert additional code to be run only when setting values.
}
protected override void OnValidate(Object value)
{
}
#endregion
[TypeConverter(typeof(SymbolCollectionConverter))]
public SymbolCollection Symbols
{
get { return this; }
}
internal class SymbolConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is SymbolHelper)
{
// Cast the value to an Employee type
SymbolHelper pp = (SymbolHelper)value;
return pp.Varname + ", " + pp.Start_address + ", " + pp.Length;
}
return base.ConvertTo(context, culture, value, destType);
}
}
// This is a special type converter which will be associated with the EmployeeCollection class.
// It converts an EmployeeCollection object to a string representation for use in a property grid.
internal class SymbolCollectionConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is SymbolCollection)
{
// Return department and department role separated by comma.
return "Symbols";
}
return base.ConvertTo(context, culture, value, destType);
}
}
#region ICustomTypeDescriptor impl
public String GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
public AttributeCollection GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
public String GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
public TypeConverter GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
public EventDescriptor GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
public PropertyDescriptor GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(this, true);
}
public object GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
public EventDescriptorCollection GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
public object GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
/// <summary>
/// Called to get the properties of this type. Returns properties with certain
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
return GetProperties();
}
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{
// Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list of employees
for (int i = 0; i < this.List.Count; i++)
{
// Create a property descriptor for the employee item and add to the property descriptor collection
SymbolCollectionPropertyDescriptor pd = new SymbolCollectionPropertyDescriptor(this, i);
pds.Add(pd);
}
// return the property descriptor collection
return pds;
}
#endregion
public class SymbolCollectionPropertyDescriptor : PropertyDescriptor
{
private SymbolCollection collection = null;
private int index = -1;
public SymbolCollectionPropertyDescriptor(SymbolCollection coll, int idx)
:
base("#" + idx.ToString(), null)
{
this.collection = coll;
this.index = idx;
}
public override AttributeCollection Attributes
{
get
{
return new AttributeCollection(null);
}
}
public override bool CanResetValue(object component)
{
return true;
}
public override Type ComponentType
{
get
{
return this.collection.GetType();
}
}
public override string DisplayName
{
get
{
SymbolHelper emp = this.collection[index];
return (string)(emp.Varname);
}
}
public override string Description
{
get
{
SymbolHelper emp = this.collection[index];
StringBuilder sb = new StringBuilder();
sb.Append(emp.Varname);
sb.Append(", ");
sb.Append(emp.Start_address);
sb.Append(", ");
sb.Append(emp.Length);
return sb.ToString();
}
}
public override object GetValue(object component)
{
return this.collection[index];
}
public override bool IsReadOnly
{
get { return false; }
}
public override string Name
{
get { return "#" + index.ToString(); }
}
public override Type PropertyType
{
get { return this.collection[index].GetType(); }
}
public override void ResetValue(object component)
{
}
public override bool ShouldSerializeValue(object component)
{
return true;
}
public override void SetValue(object component, object value)
{
// this.collection[index] = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Should;
using Xunit;
namespace AutoMapper.UnitTests
{
namespace ConfigurationValidation
{
public class When_testing_a_dto_with_mismatched_members : NonValidatingSpecBase
{
public class ModelObject
{
public string Foo { get; set; }
public string Barr { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public string Bar { get; set; }
}
public class ModelObject2
{
public string Foo { get; set; }
public string Barr { get; set; }
}
public class ModelDto2
{
public string Foo { get; set; }
public string Bar { get; set; }
public string Bar1 { get; set; }
public string Bar2 { get; set; }
public string Bar3 { get; set; }
public string Bar4 { get; set; }
}
public class ModelObject3
{
public string Foo { get; set; }
public string Bar { get; set; }
public string Bar1 { get; set; }
public string Bar2 { get; set; }
public string Bar3 { get; set; }
public string Bar4 { get; set; }
}
public class ModelDto3
{
public string Foo { get; set; }
public string Bar { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ModelObject, ModelDto>();
cfg.CreateMap<ModelObject2, ModelDto2>();
cfg.CreateMap<ModelObject3, ModelDto3>(MemberList.Source);
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_fully_mapped_and_custom_matchers : NonValidatingSpecBase
{
public class ModelObject
{
public string Foo { get; set; }
public string Barr { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public string Bar { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ModelObject, ModelDto>()
.ForMember(dto => dto.Bar, opt => opt.MapFrom(m => m.Barr));
});
[Fact]
public void Should_pass_an_inspection_of_missing_mappings()
{
Configuration.AssertConfigurationIsValid();
}
}
public class When_testing_a_dto_with_matching_member_names_but_mismatched_types : NonValidatingSpecBase
{
public class Source
{
public decimal Value { get; set; }
}
public class Destination
{
public Type Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_member_type_mapped_mappings : AutoMapperSpecBase
{
private AutoMapperConfigurationException _exception;
public class Source
{
public int Value { get; set; }
public OtherSource Other { get; set; }
}
public class OtherSource
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
public OtherDest Other { get; set; }
}
public class OtherDest
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<OtherSource, OtherDest>();
});
protected override void Because_of()
{
try
{
Configuration.AssertConfigurationIsValid();
}
catch (AutoMapperConfigurationException ex)
{
_exception = ex;
}
}
[Fact]
public void Should_pass_a_configuration_check()
{
_exception.ShouldBeNull();
}
}
public class When_testing_a_dto_with_matched_members_but_mismatched_types_that_are_ignored : AutoMapperSpecBase
{
private AutoMapperConfigurationException _exception;
public class ModelObject
{
public string Foo { get; set; }
public string Bar { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public int Bar { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ModelObject, ModelDto>()
.ForMember(dest => dest.Bar, opt => opt.Ignore());
});
protected override void Because_of()
{
try
{
Configuration.AssertConfigurationIsValid();
}
catch (AutoMapperConfigurationException ex)
{
_exception = ex;
}
}
[Fact]
public void Should_pass_a_configuration_check()
{
_exception.ShouldBeNull();
}
}
public class When_testing_a_dto_with_array_types_with_mismatched_element_types : NonValidatingSpecBase
{
public class Source
{
public SourceItem[] Items;
}
public class Destination
{
public DestinationItem[] Items;
}
public class SourceItem
{
}
public class DestinationItem
{
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_list_types_with_mismatched_element_types : NonValidatingSpecBase
{
public class Source
{
public List<SourceItem> Items;
}
public class Destination
{
public List<DestinationItem> Items;
}
public class SourceItem
{
}
public class DestinationItem
{
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_readonly_members : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
public string ValuePlusOne { get { return (Value + 1).ToString(); } }
public int ValuePlusTwo { get { return Value + 2; } }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
Mapper.Map<Source, Destination>(new Source { Value = 5 });
}
[Fact]
public void Should_be_valid()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_in_a_specfic_profile : NonValidatingSpecBase
{
public class GoodSource
{
public int Value { get; set; }
}
public class GoodDest
{
public int Value { get; set; }
}
public class BadDest
{
public int Valufffff { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateProfile("Good", profile =>
{
profile.CreateMap<GoodSource, GoodDest>();
});
cfg.CreateProfile("Bad", profile =>
{
profile.CreateMap<GoodSource, BadDest>();
});
});
[Fact]
public void Should_ignore_bad_dtos_in_other_profiles()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Configuration.AssertConfigurationIsValid("Good"));
}
}
public class When_testing_a_dto_with_mismatched_custom_member_mapping : NonValidatingSpecBase
{
public class SubBarr { }
public class SubBar { }
public class ModelObject
{
public string Foo { get; set; }
public SubBarr Barr { get; set; }
}
public class ModelDto
{
public string Foo { get; set; }
public SubBar Bar { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ModelObject, ModelDto>()
.ForMember(dest => dest.Bar, opt => opt.MapFrom(src => src.Barr));
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_value_specified_members : NonValidatingSpecBase
{
public class Source { }
public class Destination
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
object i = 7;
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Value, opt => opt.UseValue(i));
});
[Fact]
public void Should_validate_successfully()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_setter_only_peroperty_member : NonValidatingSpecBase
{
public class Source
{
public string Value { set { } }
}
public class Destination
{
public string Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_testing_a_dto_with_matching_void_method_member : NonValidatingSpecBase
{
public class Source
{
public void Method()
{
}
}
public class Destination
{
public string Method { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
[Fact]
public void Should_fail_a_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_redirecting_types : NonValidatingSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ConcreteSource, ConcreteDest>()
.ForMember(d => d.DifferentName, opt => opt.MapFrom(s => s.Name));
cfg.CreateMap<ConcreteSource, IAbstractDest>().As<ConcreteDest>();
});
[Fact]
public void Should_pass_configuration_check()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
class ConcreteSource
{
public string Name { get; set; }
}
class ConcreteDest : IAbstractDest
{
public string DifferentName { get; set; }
}
interface IAbstractDest
{
string DifferentName { get; set; }
}
}
}
}
| |
#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.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Serialization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Schema
{
/// <summary>
/// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>.
/// </summary>
public class JsonSchemaGenerator
{
/// <summary>
/// Gets or sets how undefined schemas are handled by the serializer.
/// </summary>
public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; }
private IContractResolver _contractResolver;
/// <summary>
/// Gets or sets the contract resolver.
/// </summary>
/// <value>The contract resolver.</value>
public IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
return DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
private class TypeSchema
{
public Type Type { get; private set; }
public JsonSchema Schema { get; private set; }
public TypeSchema(Type type, JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(schema, "schema");
Type = type;
Schema = schema;
}
}
private JsonSchemaResolver _resolver;
private readonly IList<TypeSchema> _stack = new List<TypeSchema>();
private JsonSchema _currentSchema;
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
private void Push(TypeSchema typeSchema)
{
_currentSchema = typeSchema.Schema;
_stack.Add(typeSchema);
_resolver.LoadedSchemas.Add(typeSchema.Schema);
}
private TypeSchema Pop()
{
TypeSchema popped = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
TypeSchema newValue = _stack.LastOrDefault();
if (newValue != null)
{
_currentSchema = newValue.Schema;
}
else
{
_currentSchema = null;
}
return popped;
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type)
{
return Generate(type, new JsonSchemaResolver(), false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
{
return Generate(type, resolver, false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, bool rootSchemaNullable)
{
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
_resolver = resolver;
return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false);
}
private string GetTitle(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
return containerAttribute.Title;
return null;
}
private string GetDescription(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
return containerAttribute.Description;
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type);
if (descriptionAttribute != null)
return descriptionAttribute.Description;
#endif
return null;
}
private string GetTypeId(Type type, bool explicitOnly)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id))
return containerAttribute.Id;
if (explicitOnly)
return null;
switch (UndefinedSchemaIdHandling)
{
case UndefinedSchemaIdHandling.UseTypeName:
return type.FullName;
case UndefinedSchemaIdHandling.UseAssemblyQualifiedName:
return type.AssemblyQualifiedName;
default:
return null;
}
}
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
{
ValidationUtils.ArgumentNotNull(type, "type");
string resolvedId = GetTypeId(type, false);
string explicitId = GetTypeId(type, true);
if (!string.IsNullOrEmpty(resolvedId))
{
JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
if (resolvedSchema != null)
{
// resolved schema is not null but referencing member allows nulls
// change resolved schema to allow nulls. hacky but what are ya gonna do?
if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null))
resolvedSchema.Type |= JsonSchemaType.Null;
if (required && resolvedSchema.Required != true)
resolvedSchema.Required = true;
return resolvedSchema;
}
}
// test for unresolved circular reference
if (_stack.Any(tc => tc.Type == type))
{
throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
}
JsonContract contract = ContractResolver.ResolveContract(type);
JsonConverter converter;
if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null)
{
JsonSchema converterSchema = converter.GetSchema();
if (converterSchema != null)
return converterSchema;
}
Push(new TypeSchema(type, new JsonSchema()));
if (explicitId != null)
CurrentSchema.Id = explicitId;
if (required)
CurrentSchema.Required = true;
CurrentSchema.Title = GetTitle(type);
CurrentSchema.Description = GetDescription(type);
if (converter != null)
{
// todo: Add GetSchema to JsonConverter and use here?
CurrentSchema.Type = JsonSchemaType.Any;
}
else
{
switch (contract.ContractType)
{
case JsonContractType.Object:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateObjectSchema(type, (JsonObjectContract)contract);
break;
case JsonContractType.Array:
CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetCachedAttribute<JsonArrayAttribute>(type);
bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems);
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
if (collectionItemType != null)
{
CurrentSchema.Items = new List<JsonSchema>();
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false));
}
break;
case JsonContractType.Primitive:
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true))
{
CurrentSchema.Enum = new List<JToken>();
IList<EnumValue<long>> enumValues = EnumUtils.GetNamesAndValues<long>(type);
foreach (EnumValue<long> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
}
}
break;
case JsonContractType.String:
JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType))
? JsonSchemaType.String
: AddNullType(JsonSchemaType.String, valueRequired);
CurrentSchema.Type = schemaType;
break;
case JsonContractType.Dictionary:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
Type keyType;
Type valueType;
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
if (keyType != null)
{
JsonContract keyContract = ContractResolver.ResolveContract(keyType);
// can be converted to a string
if (keyContract.ContractType == JsonContractType.Primitive)
{
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
}
}
break;
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
case JsonContractType.Serializable:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateISerializableContract(type, (JsonISerializableContract)contract);
break;
#endif
#if !(NET35 || NET20 || PORTABLE40)
case JsonContractType.Dynamic:
#endif
case JsonContractType.Linq:
CurrentSchema.Type = JsonSchemaType.Any;
break;
default:
throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
}
}
return Pop().Schema;
}
private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired)
{
if (valueRequired != Required.Always)
return type | JsonSchemaType.Null;
return type;
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private void GenerateObjectSchema(Type type, JsonObjectContract contract)
{
CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
foreach (JsonProperty property in contract.Properties)
{
if (!property.Ignored)
{
bool optional = property.NullValueHandling == NullValueHandling.Ignore ||
HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) ||
property.ShouldSerialize != null ||
property.GetIsSpecified != null;
JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional);
if (property.DefaultValue != null)
propertySchema.Default = JToken.FromObject(property.DefaultValue);
CurrentSchema.Properties.Add(property.PropertyName, propertySchema);
}
}
if (type.IsSealed())
CurrentSchema.AllowAdditionalProperties = false;
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
private void GenerateISerializableContract(Type type, JsonISerializableContract contract)
{
CurrentSchema.AllowAdditionalProperties = true;
}
#endif
internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
{
// default value is Any
if (value == null)
return true;
bool match = ((value & flag) == flag);
if (match)
return true;
// integer is a subset of float
if (flag == JsonSchemaType.Integer && (value & JsonSchemaType.Float) == JsonSchemaType.Float)
return true;
return false;
}
private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired)
{
JsonSchemaType schemaType = JsonSchemaType.None;
if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type))
{
schemaType = JsonSchemaType.Null;
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
}
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type);
switch (typeCode)
{
case PrimitiveTypeCode.Empty:
case PrimitiveTypeCode.Object:
return schemaType | JsonSchemaType.String;
#if !(NETFX_CORE || PORTABLE)
case PrimitiveTypeCode.DBNull:
return schemaType | JsonSchemaType.Null;
#endif
case PrimitiveTypeCode.Boolean:
return schemaType | JsonSchemaType.Boolean;
case PrimitiveTypeCode.Char:
return schemaType | JsonSchemaType.String;
case PrimitiveTypeCode.SByte:
case PrimitiveTypeCode.Byte:
case PrimitiveTypeCode.Int16:
case PrimitiveTypeCode.UInt16:
case PrimitiveTypeCode.Int32:
case PrimitiveTypeCode.UInt32:
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt64:
#if !(PORTABLE || NET35 || NET20)
case PrimitiveTypeCode.BigInteger:
#endif
return schemaType | JsonSchemaType.Integer;
case PrimitiveTypeCode.Single:
case PrimitiveTypeCode.Double:
case PrimitiveTypeCode.Decimal:
return schemaType | JsonSchemaType.Float;
// convert to string?
case PrimitiveTypeCode.DateTime:
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
#endif
return schemaType | JsonSchemaType.String;
case PrimitiveTypeCode.String:
case PrimitiveTypeCode.Uri:
case PrimitiveTypeCode.Guid:
case PrimitiveTypeCode.TimeSpan:
case PrimitiveTypeCode.Bytes:
return schemaType | JsonSchemaType.String;
default:
throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
}
}
}
}
| |
namespace Microsoft.Azure.Management.StorSimple8000Series
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VolumeContainersOperations operations.
/// </summary>
internal partial class VolumeContainersOperations : IServiceOperations<StorSimple8000SeriesManagementClient>, IVolumeContainersOperations
{
/// <summary>
/// Initializes a new instance of the VolumeContainersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal VolumeContainersOperations(StorSimple8000SeriesManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the StorSimple8000SeriesManagementClient
/// </summary>
public StorSimple8000SeriesManagementClient Client { get; private set; }
/// <summary>
/// Gets all the volume containers in a device.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<VolumeContainer>>> ListByDeviceWithHttpMessagesAsync(string deviceName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (deviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "deviceName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (managerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "managerName");
}
if (managerName != null)
{
if (managerName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "managerName", 50);
}
if (managerName.Length < 2)
{
throw new ValidationException(ValidationRules.MinLength, "managerName", 2);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deviceName", deviceName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("managerName", managerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByDevice", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/volumeContainers").ToString();
_url = _url.Replace("{deviceName}", deviceName);
_url = _url.Replace("{subscriptionId}", Client.SubscriptionId);
_url = _url.Replace("{resourceGroupName}", resourceGroupName);
_url = _url.Replace("{managerName}", managerName);
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Client.ApiVersion));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<VolumeContainer>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<VolumeContainer>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the properties of the specified volume container name.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The name of the volume container.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VolumeContainer>> GetWithHttpMessagesAsync(string deviceName, string volumeContainerName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (deviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "deviceName");
}
if (volumeContainerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "volumeContainerName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (managerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "managerName");
}
if (managerName != null)
{
if (managerName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "managerName", 50);
}
if (managerName.Length < 2)
{
throw new ValidationException(ValidationRules.MinLength, "managerName", 2);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deviceName", deviceName);
tracingParameters.Add("volumeContainerName", volumeContainerName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("managerName", managerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/volumeContainers/{volumeContainerName}").ToString();
_url = _url.Replace("{deviceName}", deviceName);
_url = _url.Replace("{volumeContainerName}", volumeContainerName);
_url = _url.Replace("{subscriptionId}", Client.SubscriptionId);
_url = _url.Replace("{resourceGroupName}", resourceGroupName);
_url = _url.Replace("{managerName}", managerName);
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Client.ApiVersion));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VolumeContainer>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VolumeContainer>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates the volume container.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The name of the volume container.
/// </param>
/// <param name='parameters'>
/// The volume container to be added or updated.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<VolumeContainer>> CreateOrUpdateWithHttpMessagesAsync(string deviceName, string volumeContainerName, VolumeContainer parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<VolumeContainer> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(deviceName, volumeContainerName, parameters, resourceGroupName, managerName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes the volume container.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The name of the volume container.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string deviceName, string volumeContainerName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(deviceName, volumeContainerName, resourceGroupName, managerName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the metrics for the specified volume container.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The volume container name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Metrics>>> ListMetricsWithHttpMessagesAsync(ODataQuery<MetricFilter> odataQuery, string deviceName, string volumeContainerName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (odataQuery == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "odataQuery");
}
if (deviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "deviceName");
}
if (volumeContainerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "volumeContainerName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (managerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "managerName");
}
if (managerName != null)
{
if (managerName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "managerName", 50);
}
if (managerName.Length < 2)
{
throw new ValidationException(ValidationRules.MinLength, "managerName", 2);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("deviceName", deviceName);
tracingParameters.Add("volumeContainerName", volumeContainerName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("managerName", managerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListMetrics", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/volumeContainers/{volumeContainerName}/metrics").ToString();
_url = _url.Replace("{deviceName}", deviceName);
_url = _url.Replace("{volumeContainerName}", volumeContainerName);
_url = _url.Replace("{subscriptionId}", Client.SubscriptionId);
_url = _url.Replace("{resourceGroupName}", resourceGroupName);
_url = _url.Replace("{managerName}", managerName);
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Client.ApiVersion));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<Metrics>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Metrics>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the metric definitions for the specified volume container.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The volume container name.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<MetricDefinition>>> ListMetricDefinitionWithHttpMessagesAsync(string deviceName, string volumeContainerName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (deviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "deviceName");
}
if (volumeContainerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "volumeContainerName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (managerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "managerName");
}
if (managerName != null)
{
if (managerName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "managerName", 50);
}
if (managerName.Length < 2)
{
throw new ValidationException(ValidationRules.MinLength, "managerName", 2);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deviceName", deviceName);
tracingParameters.Add("volumeContainerName", volumeContainerName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("managerName", managerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListMetricDefinition", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/volumeContainers/{volumeContainerName}/metricsDefinitions").ToString();
_url = _url.Replace("{deviceName}", deviceName);
_url = _url.Replace("{volumeContainerName}", volumeContainerName);
_url = _url.Replace("{subscriptionId}", Client.SubscriptionId);
_url = _url.Replace("{resourceGroupName}", resourceGroupName);
_url = _url.Replace("{managerName}", managerName);
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Client.ApiVersion));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<MetricDefinition>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<MetricDefinition>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates the volume container.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The name of the volume container.
/// </param>
/// <param name='parameters'>
/// The volume container to be added or updated.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VolumeContainer>> BeginCreateOrUpdateWithHttpMessagesAsync(string deviceName, string volumeContainerName, VolumeContainer parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (deviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "deviceName");
}
if (volumeContainerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "volumeContainerName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (managerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "managerName");
}
if (managerName != null)
{
if (managerName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "managerName", 50);
}
if (managerName.Length < 2)
{
throw new ValidationException(ValidationRules.MinLength, "managerName", 2);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deviceName", deviceName);
tracingParameters.Add("volumeContainerName", volumeContainerName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("managerName", managerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/volumeContainers/{volumeContainerName}").ToString();
_url = _url.Replace("{deviceName}", deviceName);
_url = _url.Replace("{volumeContainerName}", volumeContainerName);
_url = _url.Replace("{subscriptionId}", Client.SubscriptionId);
_url = _url.Replace("{resourceGroupName}", resourceGroupName);
_url = _url.Replace("{managerName}", managerName);
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Client.ApiVersion));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VolumeContainer>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VolumeContainer>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the volume container.
/// </summary>
/// <param name='deviceName'>
/// The device name
/// </param>
/// <param name='volumeContainerName'>
/// The name of the volume container.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string deviceName, string volumeContainerName, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (deviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "deviceName");
}
if (volumeContainerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "volumeContainerName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (managerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "managerName");
}
if (managerName != null)
{
if (managerName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "managerName", 50);
}
if (managerName.Length < 2)
{
throw new ValidationException(ValidationRules.MinLength, "managerName", 2);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deviceName", deviceName);
tracingParameters.Add("volumeContainerName", volumeContainerName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("managerName", managerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/volumeContainers/{volumeContainerName}").ToString();
_url = _url.Replace("{deviceName}", deviceName);
_url = _url.Replace("{volumeContainerName}", volumeContainerName);
_url = _url.Replace("{subscriptionId}", Client.SubscriptionId);
_url = _url.Replace("{resourceGroupName}", resourceGroupName);
_url = _url.Replace("{managerName}", managerName);
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Client.ApiVersion));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
namespace android.hardware
{
[global::MonoJavaBridge.JavaClass()]
public partial class Camera : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Camera(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.hardware.Camera.AutoFocusCallback_))]
public partial interface AutoFocusCallback : global::MonoJavaBridge.IJavaObject
{
void onAutoFocus(bool arg0, android.hardware.Camera arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.hardware.Camera.AutoFocusCallback))]
internal sealed partial class AutoFocusCallback_ : java.lang.Object, AutoFocusCallback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal AutoFocusCallback_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.hardware.Camera.AutoFocusCallback.onAutoFocus(bool arg0, android.hardware.Camera arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.AutoFocusCallback_.staticClass, "onAutoFocus", "(ZLandroid/hardware/Camera;)V", ref global::android.hardware.Camera.AutoFocusCallback_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
static AutoFocusCallback_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.AutoFocusCallback_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera$AutoFocusCallback"));
}
}
public delegate void AutoFocusCallbackDelegate(bool arg0, android.hardware.Camera arg1);
internal partial class AutoFocusCallbackDelegateWrapper : java.lang.Object, AutoFocusCallback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected AutoFocusCallbackDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public AutoFocusCallbackDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.hardware.Camera.AutoFocusCallbackDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.hardware.Camera.AutoFocusCallbackDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.hardware.Camera.AutoFocusCallbackDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.hardware.Camera.AutoFocusCallbackDelegateWrapper.staticClass, global::android.hardware.Camera.AutoFocusCallbackDelegateWrapper._m0);
Init(@__env, handle);
}
static AutoFocusCallbackDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.AutoFocusCallbackDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera_AutoFocusCallbackDelegateWrapper"));
}
}
internal partial class AutoFocusCallbackDelegateWrapper
{
private AutoFocusCallbackDelegate myDelegate;
public void onAutoFocus(bool arg0, android.hardware.Camera arg1)
{
myDelegate(arg0, arg1);
}
public static implicit operator AutoFocusCallbackDelegateWrapper(AutoFocusCallbackDelegate d)
{
global::android.hardware.Camera.AutoFocusCallbackDelegateWrapper ret = new global::android.hardware.Camera.AutoFocusCallbackDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.hardware.Camera.ErrorCallback_))]
public partial interface ErrorCallback : global::MonoJavaBridge.IJavaObject
{
void onError(int arg0, android.hardware.Camera arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.hardware.Camera.ErrorCallback))]
internal sealed partial class ErrorCallback_ : java.lang.Object, ErrorCallback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal ErrorCallback_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.hardware.Camera.ErrorCallback.onError(int arg0, android.hardware.Camera arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.ErrorCallback_.staticClass, "onError", "(ILandroid/hardware/Camera;)V", ref global::android.hardware.Camera.ErrorCallback_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
static ErrorCallback_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.ErrorCallback_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera$ErrorCallback"));
}
}
public delegate void ErrorCallbackDelegate(int arg0, android.hardware.Camera arg1);
internal partial class ErrorCallbackDelegateWrapper : java.lang.Object, ErrorCallback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected ErrorCallbackDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public ErrorCallbackDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.hardware.Camera.ErrorCallbackDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.hardware.Camera.ErrorCallbackDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.hardware.Camera.ErrorCallbackDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.hardware.Camera.ErrorCallbackDelegateWrapper.staticClass, global::android.hardware.Camera.ErrorCallbackDelegateWrapper._m0);
Init(@__env, handle);
}
static ErrorCallbackDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.ErrorCallbackDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera_ErrorCallbackDelegateWrapper"));
}
}
internal partial class ErrorCallbackDelegateWrapper
{
private ErrorCallbackDelegate myDelegate;
public void onError(int arg0, android.hardware.Camera arg1)
{
myDelegate(arg0, arg1);
}
public static implicit operator ErrorCallbackDelegateWrapper(ErrorCallbackDelegate d)
{
global::android.hardware.Camera.ErrorCallbackDelegateWrapper ret = new global::android.hardware.Camera.ErrorCallbackDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.hardware.Camera.OnZoomChangeListener_))]
public partial interface OnZoomChangeListener : global::MonoJavaBridge.IJavaObject
{
void onZoomChange(int arg0, bool arg1, android.hardware.Camera arg2);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.hardware.Camera.OnZoomChangeListener))]
internal sealed partial class OnZoomChangeListener_ : java.lang.Object, OnZoomChangeListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnZoomChangeListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.hardware.Camera.OnZoomChangeListener.onZoomChange(int arg0, bool arg1, android.hardware.Camera arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.OnZoomChangeListener_.staticClass, "onZoomChange", "(IZLandroid/hardware/Camera;)V", ref global::android.hardware.Camera.OnZoomChangeListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
static OnZoomChangeListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.OnZoomChangeListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera$OnZoomChangeListener"));
}
}
public delegate void OnZoomChangeListenerDelegate(int arg0, bool arg1, android.hardware.Camera arg2);
internal partial class OnZoomChangeListenerDelegateWrapper : java.lang.Object, OnZoomChangeListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected OnZoomChangeListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public OnZoomChangeListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.hardware.Camera.OnZoomChangeListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.hardware.Camera.OnZoomChangeListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.hardware.Camera.OnZoomChangeListenerDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.hardware.Camera.OnZoomChangeListenerDelegateWrapper.staticClass, global::android.hardware.Camera.OnZoomChangeListenerDelegateWrapper._m0);
Init(@__env, handle);
}
static OnZoomChangeListenerDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.OnZoomChangeListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera_OnZoomChangeListenerDelegateWrapper"));
}
}
internal partial class OnZoomChangeListenerDelegateWrapper
{
private OnZoomChangeListenerDelegate myDelegate;
public void onZoomChange(int arg0, bool arg1, android.hardware.Camera arg2)
{
myDelegate(arg0, arg1, arg2);
}
public static implicit operator OnZoomChangeListenerDelegateWrapper(OnZoomChangeListenerDelegate d)
{
global::android.hardware.Camera.OnZoomChangeListenerDelegateWrapper ret = new global::android.hardware.Camera.OnZoomChangeListenerDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaClass()]
public partial class Parameters : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Parameters(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual global::java.lang.String get(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.hardware.Camera.Parameters.staticClass, "get", "(Ljava/lang/String;)Ljava/lang/String;", ref global::android.hardware.Camera.Parameters._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual int getInt(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getInt", "(Ljava/lang/String;)I", ref global::android.hardware.Camera.Parameters._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual void remove(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "remove", "(Ljava/lang/String;)V", ref global::android.hardware.Camera.Parameters._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual void set(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "set", "(Ljava/lang/String;Ljava/lang/String;)V", ref global::android.hardware.Camera.Parameters._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual void set(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "set", "(Ljava/lang/String;I)V", ref global::android.hardware.Camera.Parameters._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual global::java.lang.String flatten()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.hardware.Camera.Parameters.staticClass, "flatten", "()Ljava/lang/String;", ref global::android.hardware.Camera.Parameters._m5) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual void unflatten(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "unflatten", "(Ljava/lang/String;)V", ref global::android.hardware.Camera.Parameters._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void setPreviewSize(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setPreviewSize", "(II)V", ref global::android.hardware.Camera.Parameters._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public new global::android.hardware.Camera.Size PreviewSize
{
get
{
return getPreviewSize();
}
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual global::android.hardware.Camera.Size getPreviewSize()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getPreviewSize", "()Landroid/hardware/Camera$Size;", ref global::android.hardware.Camera.Parameters._m8) as android.hardware.Camera.Size;
}
public new global::java.util.List SupportedPreviewSizes
{
get
{
return getSupportedPreviewSizes();
}
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual global::java.util.List getSupportedPreviewSizes()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getSupportedPreviewSizes", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m9) as java.util.List;
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual void setJpegThumbnailSize(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setJpegThumbnailSize", "(II)V", ref global::android.hardware.Camera.Parameters._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public new global::android.hardware.Camera.Size JpegThumbnailSize
{
get
{
return getJpegThumbnailSize();
}
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual global::android.hardware.Camera.Size getJpegThumbnailSize()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getJpegThumbnailSize", "()Landroid/hardware/Camera$Size;", ref global::android.hardware.Camera.Parameters._m11) as android.hardware.Camera.Size;
}
public new global::java.util.List SupportedJpegThumbnailSizes
{
get
{
return getSupportedJpegThumbnailSizes();
}
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual global::java.util.List getSupportedJpegThumbnailSizes()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getSupportedJpegThumbnailSizes", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m12) as java.util.List;
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual void setJpegThumbnailQuality(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setJpegThumbnailQuality", "(I)V", ref global::android.hardware.Camera.Parameters._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int JpegThumbnailQuality
{
get
{
return getJpegThumbnailQuality();
}
set
{
setJpegThumbnailQuality(value);
}
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual int getJpegThumbnailQuality()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getJpegThumbnailQuality", "()I", ref global::android.hardware.Camera.Parameters._m14);
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void setJpegQuality(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setJpegQuality", "(I)V", ref global::android.hardware.Camera.Parameters._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int JpegQuality
{
get
{
return getJpegQuality();
}
set
{
setJpegQuality(value);
}
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual int getJpegQuality()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getJpegQuality", "()I", ref global::android.hardware.Camera.Parameters._m16);
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void setPreviewFrameRate(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setPreviewFrameRate", "(I)V", ref global::android.hardware.Camera.Parameters._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int PreviewFrameRate
{
get
{
return getPreviewFrameRate();
}
set
{
setPreviewFrameRate(value);
}
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual int getPreviewFrameRate()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getPreviewFrameRate", "()I", ref global::android.hardware.Camera.Parameters._m18);
}
public new global::java.util.List SupportedPreviewFrameRates
{
get
{
return getSupportedPreviewFrameRates();
}
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual global::java.util.List getSupportedPreviewFrameRates()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getSupportedPreviewFrameRates", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m19) as java.util.List;
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void setPreviewFormat(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setPreviewFormat", "(I)V", ref global::android.hardware.Camera.Parameters._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int PreviewFormat
{
get
{
return getPreviewFormat();
}
set
{
setPreviewFormat(value);
}
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual int getPreviewFormat()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getPreviewFormat", "()I", ref global::android.hardware.Camera.Parameters._m21);
}
public new global::java.util.List SupportedPreviewFormats
{
get
{
return getSupportedPreviewFormats();
}
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual global::java.util.List getSupportedPreviewFormats()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getSupportedPreviewFormats", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m22) as java.util.List;
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual void setPictureSize(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setPictureSize", "(II)V", ref global::android.hardware.Camera.Parameters._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public new global::android.hardware.Camera.Size PictureSize
{
get
{
return getPictureSize();
}
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual global::android.hardware.Camera.Size getPictureSize()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getPictureSize", "()Landroid/hardware/Camera$Size;", ref global::android.hardware.Camera.Parameters._m24) as android.hardware.Camera.Size;
}
public new global::java.util.List SupportedPictureSizes
{
get
{
return getSupportedPictureSizes();
}
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual global::java.util.List getSupportedPictureSizes()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getSupportedPictureSizes", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m25) as java.util.List;
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual void setPictureFormat(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setPictureFormat", "(I)V", ref global::android.hardware.Camera.Parameters._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int PictureFormat
{
get
{
return getPictureFormat();
}
set
{
setPictureFormat(value);
}
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual int getPictureFormat()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getPictureFormat", "()I", ref global::android.hardware.Camera.Parameters._m27);
}
public new global::java.util.List SupportedPictureFormats
{
get
{
return getSupportedPictureFormats();
}
}
private static global::MonoJavaBridge.MethodId _m28;
public virtual global::java.util.List getSupportedPictureFormats()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getSupportedPictureFormats", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m28) as java.util.List;
}
public new int Rotation
{
set
{
setRotation(value);
}
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual void setRotation(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setRotation", "(I)V", ref global::android.hardware.Camera.Parameters._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new double GpsLatitude
{
set
{
setGpsLatitude(value);
}
}
private static global::MonoJavaBridge.MethodId _m30;
public virtual void setGpsLatitude(double arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setGpsLatitude", "(D)V", ref global::android.hardware.Camera.Parameters._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new double GpsLongitude
{
set
{
setGpsLongitude(value);
}
}
private static global::MonoJavaBridge.MethodId _m31;
public virtual void setGpsLongitude(double arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setGpsLongitude", "(D)V", ref global::android.hardware.Camera.Parameters._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new double GpsAltitude
{
set
{
setGpsAltitude(value);
}
}
private static global::MonoJavaBridge.MethodId _m32;
public virtual void setGpsAltitude(double arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setGpsAltitude", "(D)V", ref global::android.hardware.Camera.Parameters._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new long GpsTimestamp
{
set
{
setGpsTimestamp(value);
}
}
private static global::MonoJavaBridge.MethodId _m33;
public virtual void setGpsTimestamp(long arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setGpsTimestamp", "(J)V", ref global::android.hardware.Camera.Parameters._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.lang.String GpsProcessingMethod
{
set
{
setGpsProcessingMethod(value);
}
}
private static global::MonoJavaBridge.MethodId _m34;
public virtual void setGpsProcessingMethod(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setGpsProcessingMethod", "(Ljava/lang/String;)V", ref global::android.hardware.Camera.Parameters._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m35;
public virtual void removeGpsData()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "removeGpsData", "()V", ref global::android.hardware.Camera.Parameters._m35);
}
public new global::java.lang.String WhiteBalance
{
get
{
return getWhiteBalance();
}
set
{
setWhiteBalance(value);
}
}
private static global::MonoJavaBridge.MethodId _m36;
public virtual global::java.lang.String getWhiteBalance()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.hardware.Camera.Parameters.staticClass, "getWhiteBalance", "()Ljava/lang/String;", ref global::android.hardware.Camera.Parameters._m36) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m37;
public virtual void setWhiteBalance(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setWhiteBalance", "(Ljava/lang/String;)V", ref global::android.hardware.Camera.Parameters._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.util.List SupportedWhiteBalance
{
get
{
return getSupportedWhiteBalance();
}
}
private static global::MonoJavaBridge.MethodId _m38;
public virtual global::java.util.List getSupportedWhiteBalance()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getSupportedWhiteBalance", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m38) as java.util.List;
}
public new global::java.lang.String ColorEffect
{
get
{
return getColorEffect();
}
set
{
setColorEffect(value);
}
}
private static global::MonoJavaBridge.MethodId _m39;
public virtual global::java.lang.String getColorEffect()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.hardware.Camera.Parameters.staticClass, "getColorEffect", "()Ljava/lang/String;", ref global::android.hardware.Camera.Parameters._m39) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m40;
public virtual void setColorEffect(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setColorEffect", "(Ljava/lang/String;)V", ref global::android.hardware.Camera.Parameters._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.util.List SupportedColorEffects
{
get
{
return getSupportedColorEffects();
}
}
private static global::MonoJavaBridge.MethodId _m41;
public virtual global::java.util.List getSupportedColorEffects()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getSupportedColorEffects", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m41) as java.util.List;
}
public new global::java.lang.String Antibanding
{
get
{
return getAntibanding();
}
set
{
setAntibanding(value);
}
}
private static global::MonoJavaBridge.MethodId _m42;
public virtual global::java.lang.String getAntibanding()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.hardware.Camera.Parameters.staticClass, "getAntibanding", "()Ljava/lang/String;", ref global::android.hardware.Camera.Parameters._m42) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m43;
public virtual void setAntibanding(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setAntibanding", "(Ljava/lang/String;)V", ref global::android.hardware.Camera.Parameters._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.util.List SupportedAntibanding
{
get
{
return getSupportedAntibanding();
}
}
private static global::MonoJavaBridge.MethodId _m44;
public virtual global::java.util.List getSupportedAntibanding()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getSupportedAntibanding", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m44) as java.util.List;
}
public new global::java.lang.String SceneMode
{
get
{
return getSceneMode();
}
set
{
setSceneMode(value);
}
}
private static global::MonoJavaBridge.MethodId _m45;
public virtual global::java.lang.String getSceneMode()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.hardware.Camera.Parameters.staticClass, "getSceneMode", "()Ljava/lang/String;", ref global::android.hardware.Camera.Parameters._m45) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m46;
public virtual void setSceneMode(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setSceneMode", "(Ljava/lang/String;)V", ref global::android.hardware.Camera.Parameters._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.util.List SupportedSceneModes
{
get
{
return getSupportedSceneModes();
}
}
private static global::MonoJavaBridge.MethodId _m47;
public virtual global::java.util.List getSupportedSceneModes()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getSupportedSceneModes", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m47) as java.util.List;
}
public new global::java.lang.String FlashMode
{
get
{
return getFlashMode();
}
set
{
setFlashMode(value);
}
}
private static global::MonoJavaBridge.MethodId _m48;
public virtual global::java.lang.String getFlashMode()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.hardware.Camera.Parameters.staticClass, "getFlashMode", "()Ljava/lang/String;", ref global::android.hardware.Camera.Parameters._m48) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m49;
public virtual void setFlashMode(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setFlashMode", "(Ljava/lang/String;)V", ref global::android.hardware.Camera.Parameters._m49, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.util.List SupportedFlashModes
{
get
{
return getSupportedFlashModes();
}
}
private static global::MonoJavaBridge.MethodId _m50;
public virtual global::java.util.List getSupportedFlashModes()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getSupportedFlashModes", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m50) as java.util.List;
}
public new global::java.lang.String FocusMode
{
get
{
return getFocusMode();
}
set
{
setFocusMode(value);
}
}
private static global::MonoJavaBridge.MethodId _m51;
public virtual global::java.lang.String getFocusMode()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.hardware.Camera.Parameters.staticClass, "getFocusMode", "()Ljava/lang/String;", ref global::android.hardware.Camera.Parameters._m51) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m52;
public virtual void setFocusMode(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setFocusMode", "(Ljava/lang/String;)V", ref global::android.hardware.Camera.Parameters._m52, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.util.List SupportedFocusModes
{
get
{
return getSupportedFocusModes();
}
}
private static global::MonoJavaBridge.MethodId _m53;
public virtual global::java.util.List getSupportedFocusModes()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getSupportedFocusModes", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m53) as java.util.List;
}
public new float FocalLength
{
get
{
return getFocalLength();
}
}
private static global::MonoJavaBridge.MethodId _m54;
public virtual float getFocalLength()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getFocalLength", "()F", ref global::android.hardware.Camera.Parameters._m54);
}
public new float HorizontalViewAngle
{
get
{
return getHorizontalViewAngle();
}
}
private static global::MonoJavaBridge.MethodId _m55;
public virtual float getHorizontalViewAngle()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getHorizontalViewAngle", "()F", ref global::android.hardware.Camera.Parameters._m55);
}
public new float VerticalViewAngle
{
get
{
return getVerticalViewAngle();
}
}
private static global::MonoJavaBridge.MethodId _m56;
public virtual float getVerticalViewAngle()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getVerticalViewAngle", "()F", ref global::android.hardware.Camera.Parameters._m56);
}
public new int ExposureCompensation
{
get
{
return getExposureCompensation();
}
set
{
setExposureCompensation(value);
}
}
private static global::MonoJavaBridge.MethodId _m57;
public virtual int getExposureCompensation()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getExposureCompensation", "()I", ref global::android.hardware.Camera.Parameters._m57);
}
private static global::MonoJavaBridge.MethodId _m58;
public virtual void setExposureCompensation(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setExposureCompensation", "(I)V", ref global::android.hardware.Camera.Parameters._m58, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int MaxExposureCompensation
{
get
{
return getMaxExposureCompensation();
}
}
private static global::MonoJavaBridge.MethodId _m59;
public virtual int getMaxExposureCompensation()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getMaxExposureCompensation", "()I", ref global::android.hardware.Camera.Parameters._m59);
}
public new int MinExposureCompensation
{
get
{
return getMinExposureCompensation();
}
}
private static global::MonoJavaBridge.MethodId _m60;
public virtual int getMinExposureCompensation()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getMinExposureCompensation", "()I", ref global::android.hardware.Camera.Parameters._m60);
}
public new float ExposureCompensationStep
{
get
{
return getExposureCompensationStep();
}
}
private static global::MonoJavaBridge.MethodId _m61;
public virtual float getExposureCompensationStep()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getExposureCompensationStep", "()F", ref global::android.hardware.Camera.Parameters._m61);
}
public new int Zoom
{
get
{
return getZoom();
}
set
{
setZoom(value);
}
}
private static global::MonoJavaBridge.MethodId _m62;
public virtual int getZoom()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getZoom", "()I", ref global::android.hardware.Camera.Parameters._m62);
}
private static global::MonoJavaBridge.MethodId _m63;
public virtual void setZoom(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.Parameters.staticClass, "setZoom", "(I)V", ref global::android.hardware.Camera.Parameters._m63, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m64;
public virtual bool isZoomSupported()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.hardware.Camera.Parameters.staticClass, "isZoomSupported", "()Z", ref global::android.hardware.Camera.Parameters._m64);
}
public new int MaxZoom
{
get
{
return getMaxZoom();
}
}
private static global::MonoJavaBridge.MethodId _m65;
public virtual int getMaxZoom()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.hardware.Camera.Parameters.staticClass, "getMaxZoom", "()I", ref global::android.hardware.Camera.Parameters._m65);
}
public new global::java.util.List ZoomRatios
{
get
{
return getZoomRatios();
}
}
private static global::MonoJavaBridge.MethodId _m66;
public virtual global::java.util.List getZoomRatios()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.hardware.Camera.Parameters.staticClass, "getZoomRatios", "()Ljava/util/List;", ref global::android.hardware.Camera.Parameters._m66) as java.util.List;
}
private static global::MonoJavaBridge.MethodId _m67;
public virtual bool isSmoothZoomSupported()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.hardware.Camera.Parameters.staticClass, "isSmoothZoomSupported", "()Z", ref global::android.hardware.Camera.Parameters._m67);
}
public static global::java.lang.String WHITE_BALANCE_AUTO
{
get
{
return "auto";
}
}
public static global::java.lang.String WHITE_BALANCE_INCANDESCENT
{
get
{
return "incandescent";
}
}
public static global::java.lang.String WHITE_BALANCE_FLUORESCENT
{
get
{
return "fluorescent";
}
}
public static global::java.lang.String WHITE_BALANCE_WARM_FLUORESCENT
{
get
{
return "warm-fluorescent";
}
}
public static global::java.lang.String WHITE_BALANCE_DAYLIGHT
{
get
{
return "daylight";
}
}
public static global::java.lang.String WHITE_BALANCE_CLOUDY_DAYLIGHT
{
get
{
return "cloudy-daylight";
}
}
public static global::java.lang.String WHITE_BALANCE_TWILIGHT
{
get
{
return "twilight";
}
}
public static global::java.lang.String WHITE_BALANCE_SHADE
{
get
{
return "shade";
}
}
public static global::java.lang.String EFFECT_NONE
{
get
{
return "none";
}
}
public static global::java.lang.String EFFECT_MONO
{
get
{
return "mono";
}
}
public static global::java.lang.String EFFECT_NEGATIVE
{
get
{
return "negative";
}
}
public static global::java.lang.String EFFECT_SOLARIZE
{
get
{
return "solarize";
}
}
public static global::java.lang.String EFFECT_SEPIA
{
get
{
return "sepia";
}
}
public static global::java.lang.String EFFECT_POSTERIZE
{
get
{
return "posterize";
}
}
public static global::java.lang.String EFFECT_WHITEBOARD
{
get
{
return "whiteboard";
}
}
public static global::java.lang.String EFFECT_BLACKBOARD
{
get
{
return "blackboard";
}
}
public static global::java.lang.String EFFECT_AQUA
{
get
{
return "aqua";
}
}
public static global::java.lang.String ANTIBANDING_AUTO
{
get
{
return "auto";
}
}
public static global::java.lang.String ANTIBANDING_50HZ
{
get
{
return "50hz";
}
}
public static global::java.lang.String ANTIBANDING_60HZ
{
get
{
return "60hz";
}
}
public static global::java.lang.String ANTIBANDING_OFF
{
get
{
return "off";
}
}
public static global::java.lang.String FLASH_MODE_OFF
{
get
{
return "off";
}
}
public static global::java.lang.String FLASH_MODE_AUTO
{
get
{
return "auto";
}
}
public static global::java.lang.String FLASH_MODE_ON
{
get
{
return "on";
}
}
public static global::java.lang.String FLASH_MODE_RED_EYE
{
get
{
return "red-eye";
}
}
public static global::java.lang.String FLASH_MODE_TORCH
{
get
{
return "torch";
}
}
public static global::java.lang.String SCENE_MODE_AUTO
{
get
{
return "auto";
}
}
public static global::java.lang.String SCENE_MODE_ACTION
{
get
{
return "action";
}
}
public static global::java.lang.String SCENE_MODE_PORTRAIT
{
get
{
return "portrait";
}
}
public static global::java.lang.String SCENE_MODE_LANDSCAPE
{
get
{
return "landscape";
}
}
public static global::java.lang.String SCENE_MODE_NIGHT
{
get
{
return "night";
}
}
public static global::java.lang.String SCENE_MODE_NIGHT_PORTRAIT
{
get
{
return "night-portrait";
}
}
public static global::java.lang.String SCENE_MODE_THEATRE
{
get
{
return "theatre";
}
}
public static global::java.lang.String SCENE_MODE_BEACH
{
get
{
return "beach";
}
}
public static global::java.lang.String SCENE_MODE_SNOW
{
get
{
return "snow";
}
}
public static global::java.lang.String SCENE_MODE_SUNSET
{
get
{
return "sunset";
}
}
public static global::java.lang.String SCENE_MODE_STEADYPHOTO
{
get
{
return "steadyphoto";
}
}
public static global::java.lang.String SCENE_MODE_FIREWORKS
{
get
{
return "fireworks";
}
}
public static global::java.lang.String SCENE_MODE_SPORTS
{
get
{
return "sports";
}
}
public static global::java.lang.String SCENE_MODE_PARTY
{
get
{
return "party";
}
}
public static global::java.lang.String SCENE_MODE_CANDLELIGHT
{
get
{
return "candlelight";
}
}
public static global::java.lang.String SCENE_MODE_BARCODE
{
get
{
return "barcode";
}
}
public static global::java.lang.String FOCUS_MODE_AUTO
{
get
{
return "auto";
}
}
public static global::java.lang.String FOCUS_MODE_INFINITY
{
get
{
return "infinity";
}
}
public static global::java.lang.String FOCUS_MODE_MACRO
{
get
{
return "macro";
}
}
public static global::java.lang.String FOCUS_MODE_FIXED
{
get
{
return "fixed";
}
}
public static global::java.lang.String FOCUS_MODE_EDOF
{
get
{
return "edof";
}
}
static Parameters()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.Parameters.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera$Parameters"));
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.hardware.Camera.PictureCallback_))]
public partial interface PictureCallback : global::MonoJavaBridge.IJavaObject
{
void onPictureTaken(byte[] arg0, android.hardware.Camera arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.hardware.Camera.PictureCallback))]
internal sealed partial class PictureCallback_ : java.lang.Object, PictureCallback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal PictureCallback_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.hardware.Camera.PictureCallback.onPictureTaken(byte[] arg0, android.hardware.Camera arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.PictureCallback_.staticClass, "onPictureTaken", "([BLandroid/hardware/Camera;)V", ref global::android.hardware.Camera.PictureCallback_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
static PictureCallback_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.PictureCallback_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera$PictureCallback"));
}
}
public delegate void PictureCallbackDelegate(byte[] arg0, android.hardware.Camera arg1);
internal partial class PictureCallbackDelegateWrapper : java.lang.Object, PictureCallback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected PictureCallbackDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public PictureCallbackDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.hardware.Camera.PictureCallbackDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.hardware.Camera.PictureCallbackDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.hardware.Camera.PictureCallbackDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.hardware.Camera.PictureCallbackDelegateWrapper.staticClass, global::android.hardware.Camera.PictureCallbackDelegateWrapper._m0);
Init(@__env, handle);
}
static PictureCallbackDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.PictureCallbackDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera_PictureCallbackDelegateWrapper"));
}
}
internal partial class PictureCallbackDelegateWrapper
{
private PictureCallbackDelegate myDelegate;
public void onPictureTaken(byte[] arg0, android.hardware.Camera arg1)
{
myDelegate(arg0, arg1);
}
public static implicit operator PictureCallbackDelegateWrapper(PictureCallbackDelegate d)
{
global::android.hardware.Camera.PictureCallbackDelegateWrapper ret = new global::android.hardware.Camera.PictureCallbackDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.hardware.Camera.PreviewCallback_))]
public partial interface PreviewCallback : global::MonoJavaBridge.IJavaObject
{
void onPreviewFrame(byte[] arg0, android.hardware.Camera arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.hardware.Camera.PreviewCallback))]
internal sealed partial class PreviewCallback_ : java.lang.Object, PreviewCallback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal PreviewCallback_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.hardware.Camera.PreviewCallback.onPreviewFrame(byte[] arg0, android.hardware.Camera arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.PreviewCallback_.staticClass, "onPreviewFrame", "([BLandroid/hardware/Camera;)V", ref global::android.hardware.Camera.PreviewCallback_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
static PreviewCallback_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.PreviewCallback_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera$PreviewCallback"));
}
}
public delegate void PreviewCallbackDelegate(byte[] arg0, android.hardware.Camera arg1);
internal partial class PreviewCallbackDelegateWrapper : java.lang.Object, PreviewCallback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected PreviewCallbackDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public PreviewCallbackDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.hardware.Camera.PreviewCallbackDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.hardware.Camera.PreviewCallbackDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.hardware.Camera.PreviewCallbackDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.hardware.Camera.PreviewCallbackDelegateWrapper.staticClass, global::android.hardware.Camera.PreviewCallbackDelegateWrapper._m0);
Init(@__env, handle);
}
static PreviewCallbackDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.PreviewCallbackDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera_PreviewCallbackDelegateWrapper"));
}
}
internal partial class PreviewCallbackDelegateWrapper
{
private PreviewCallbackDelegate myDelegate;
public void onPreviewFrame(byte[] arg0, android.hardware.Camera arg1)
{
myDelegate(arg0, arg1);
}
public static implicit operator PreviewCallbackDelegateWrapper(PreviewCallbackDelegate d)
{
global::android.hardware.Camera.PreviewCallbackDelegateWrapper ret = new global::android.hardware.Camera.PreviewCallbackDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.hardware.Camera.ShutterCallback_))]
public partial interface ShutterCallback : global::MonoJavaBridge.IJavaObject
{
void onShutter();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.hardware.Camera.ShutterCallback))]
internal sealed partial class ShutterCallback_ : java.lang.Object, ShutterCallback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal ShutterCallback_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.hardware.Camera.ShutterCallback.onShutter()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.ShutterCallback_.staticClass, "onShutter", "()V", ref global::android.hardware.Camera.ShutterCallback_._m0);
}
static ShutterCallback_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.ShutterCallback_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera$ShutterCallback"));
}
}
public delegate void ShutterCallbackDelegate();
internal partial class ShutterCallbackDelegateWrapper : java.lang.Object, ShutterCallback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected ShutterCallbackDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public ShutterCallbackDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.hardware.Camera.ShutterCallbackDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.hardware.Camera.ShutterCallbackDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.hardware.Camera.ShutterCallbackDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.hardware.Camera.ShutterCallbackDelegateWrapper.staticClass, global::android.hardware.Camera.ShutterCallbackDelegateWrapper._m0);
Init(@__env, handle);
}
static ShutterCallbackDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.ShutterCallbackDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera_ShutterCallbackDelegateWrapper"));
}
}
internal partial class ShutterCallbackDelegateWrapper
{
private ShutterCallbackDelegate myDelegate;
public void onShutter()
{
myDelegate();
}
public static implicit operator ShutterCallbackDelegateWrapper(ShutterCallbackDelegate d)
{
global::android.hardware.Camera.ShutterCallbackDelegateWrapper ret = new global::android.hardware.Camera.ShutterCallbackDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaClass()]
public partial class Size : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Size(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override bool equals(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.hardware.Camera.Size.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::android.hardware.Camera.Size._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public override int hashCode()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.hardware.Camera.Size.staticClass, "hashCode", "()I", ref global::android.hardware.Camera.Size._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
public Size(android.hardware.Camera arg0, int arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.hardware.Camera.Size._m2.native == global::System.IntPtr.Zero)
global::android.hardware.Camera.Size._m2 = @__env.GetMethodIDNoThrow(global::android.hardware.Camera.Size.staticClass, "<init>", "(Landroid/hardware/Camera;II)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.hardware.Camera.Size.staticClass, global::android.hardware.Camera.Size._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _width2484;
public int width
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.GetIntField(this.JvmHandle, _width2484);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _height2485;
public int height
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.GetIntField(this.JvmHandle, _height2485);
}
set
{
}
}
static Size()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.Size.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera$Size"));
global::android.hardware.Camera.Size._width2484 = @__env.GetFieldIDNoThrow(global::android.hardware.Camera.Size.staticClass, "width", "I");
global::android.hardware.Camera.Size._height2485 = @__env.GetFieldIDNoThrow(global::android.hardware.Camera.Size.staticClass, "height", "I");
}
}
private static global::MonoJavaBridge.MethodId _m0;
protected override void finalize()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "finalize", "()V", ref global::android.hardware.Camera._m0);
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual void @lock()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "@lock", "()V", ref global::android.hardware.Camera._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual void release()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "release", "()V", ref global::android.hardware.Camera._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public static global::android.hardware.Camera open()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.hardware.Camera._m3.native == global::System.IntPtr.Zero)
global::android.hardware.Camera._m3 = @__env.GetStaticMethodIDNoThrow(global::android.hardware.Camera.staticClass, "open", "()Landroid/hardware/Camera;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.hardware.Camera.staticClass, global::android.hardware.Camera._m3)) as android.hardware.Camera;
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual void unlock()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "unlock", "()V", ref global::android.hardware.Camera._m4);
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual global::android.hardware.Camera.Parameters getParameters()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.hardware.Camera.staticClass, "getParameters", "()Landroid/hardware/Camera$Parameters;", ref global::android.hardware.Camera._m5) as android.hardware.Camera.Parameters;
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual void reconnect()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "reconnect", "()V", ref global::android.hardware.Camera._m6);
}
public new global::android.view.SurfaceHolder PreviewDisplay
{
set
{
setPreviewDisplay(value);
}
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void setPreviewDisplay(android.view.SurfaceHolder arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "setPreviewDisplay", "(Landroid/view/SurfaceHolder;)V", ref global::android.hardware.Camera._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual void startPreview()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "startPreview", "()V", ref global::android.hardware.Camera._m8);
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual void stopPreview()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "stopPreview", "()V", ref global::android.hardware.Camera._m9);
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual void setPreviewCallback(android.hardware.Camera.PreviewCallback arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "setPreviewCallback", "(Landroid/hardware/Camera$PreviewCallback;)V", ref global::android.hardware.Camera._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setPreviewCallback(global::android.hardware.Camera.PreviewCallbackDelegate arg0)
{
setPreviewCallback((global::android.hardware.Camera.PreviewCallbackDelegateWrapper)arg0);
}
public new global::android.hardware.Camera.PreviewCallback OneShotPreviewCallback
{
set
{
setOneShotPreviewCallback(value);
}
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual void setOneShotPreviewCallback(android.hardware.Camera.PreviewCallback arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "setOneShotPreviewCallback", "(Landroid/hardware/Camera$PreviewCallback;)V", ref global::android.hardware.Camera._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setOneShotPreviewCallback(global::android.hardware.Camera.PreviewCallbackDelegate arg0)
{
setOneShotPreviewCallback((global::android.hardware.Camera.PreviewCallbackDelegateWrapper)arg0);
}
public new global::android.hardware.Camera.PreviewCallback PreviewCallbackWithBuffer
{
set
{
setPreviewCallbackWithBuffer(value);
}
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual void setPreviewCallbackWithBuffer(android.hardware.Camera.PreviewCallback arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "setPreviewCallbackWithBuffer", "(Landroid/hardware/Camera$PreviewCallback;)V", ref global::android.hardware.Camera._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setPreviewCallbackWithBuffer(global::android.hardware.Camera.PreviewCallbackDelegate arg0)
{
setPreviewCallbackWithBuffer((global::android.hardware.Camera.PreviewCallbackDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual void addCallbackBuffer(byte[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "addCallbackBuffer", "([B)V", ref global::android.hardware.Camera._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual void autoFocus(android.hardware.Camera.AutoFocusCallback arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "autoFocus", "(Landroid/hardware/Camera$AutoFocusCallback;)V", ref global::android.hardware.Camera._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void autoFocus(global::android.hardware.Camera.AutoFocusCallbackDelegate arg0)
{
autoFocus((global::android.hardware.Camera.AutoFocusCallbackDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void cancelAutoFocus()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "cancelAutoFocus", "()V", ref global::android.hardware.Camera._m15);
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void takePicture(android.hardware.Camera.ShutterCallback arg0, android.hardware.Camera.PictureCallback arg1, android.hardware.Camera.PictureCallback arg2, android.hardware.Camera.PictureCallback arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "takePicture", "(Landroid/hardware/Camera$ShutterCallback;Landroid/hardware/Camera$PictureCallback;Landroid/hardware/Camera$PictureCallback;Landroid/hardware/Camera$PictureCallback;)V", ref global::android.hardware.Camera._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
public void takePicture(global::android.hardware.Camera.ShutterCallbackDelegate arg0, global::android.hardware.Camera.PictureCallbackDelegate arg1, global::android.hardware.Camera.PictureCallbackDelegate arg2, global::android.hardware.Camera.PictureCallbackDelegate arg3)
{
takePicture((global::android.hardware.Camera.ShutterCallbackDelegateWrapper)arg0, (global::android.hardware.Camera.PictureCallbackDelegateWrapper)arg1, (global::android.hardware.Camera.PictureCallbackDelegateWrapper)arg2, (global::android.hardware.Camera.PictureCallbackDelegateWrapper)arg3);
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void takePicture(android.hardware.Camera.ShutterCallback arg0, android.hardware.Camera.PictureCallback arg1, android.hardware.Camera.PictureCallback arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "takePicture", "(Landroid/hardware/Camera$ShutterCallback;Landroid/hardware/Camera$PictureCallback;Landroid/hardware/Camera$PictureCallback;)V", ref global::android.hardware.Camera._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
public void takePicture(global::android.hardware.Camera.ShutterCallbackDelegate arg0, global::android.hardware.Camera.PictureCallbackDelegate arg1, global::android.hardware.Camera.PictureCallbackDelegate arg2)
{
takePicture((global::android.hardware.Camera.ShutterCallbackDelegateWrapper)arg0, (global::android.hardware.Camera.PictureCallbackDelegateWrapper)arg1, (global::android.hardware.Camera.PictureCallbackDelegateWrapper)arg2);
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual void startSmoothZoom(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "startSmoothZoom", "(I)V", ref global::android.hardware.Camera._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual void stopSmoothZoom()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "stopSmoothZoom", "()V", ref global::android.hardware.Camera._m19);
}
public new int DisplayOrientation
{
set
{
setDisplayOrientation(value);
}
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void setDisplayOrientation(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "setDisplayOrientation", "(I)V", ref global::android.hardware.Camera._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::android.hardware.Camera.OnZoomChangeListener ZoomChangeListener
{
set
{
setZoomChangeListener(value);
}
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual void setZoomChangeListener(android.hardware.Camera.OnZoomChangeListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "setZoomChangeListener", "(Landroid/hardware/Camera$OnZoomChangeListener;)V", ref global::android.hardware.Camera._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setZoomChangeListener(global::android.hardware.Camera.OnZoomChangeListenerDelegate arg0)
{
setZoomChangeListener((global::android.hardware.Camera.OnZoomChangeListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual void setErrorCallback(android.hardware.Camera.ErrorCallback arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "setErrorCallback", "(Landroid/hardware/Camera$ErrorCallback;)V", ref global::android.hardware.Camera._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setErrorCallback(global::android.hardware.Camera.ErrorCallbackDelegate arg0)
{
setErrorCallback((global::android.hardware.Camera.ErrorCallbackDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual void setParameters(android.hardware.Camera.Parameters arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.hardware.Camera.staticClass, "setParameters", "(Landroid/hardware/Camera$Parameters;)V", ref global::android.hardware.Camera._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public static int CAMERA_ERROR_UNKNOWN
{
get
{
return 1;
}
}
public static int CAMERA_ERROR_SERVER_DIED
{
get
{
return 100;
}
}
static Camera()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.hardware.Camera.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/hardware/Camera"));
}
}
}
| |
using Signum.Engine.Maps;
using Signum.Entities.DynamicQuery;
using Signum.Utilities.Reflection;
using System.Data;
using System.Data.Common;
using System.Globalization;
namespace Signum.Engine.Linq;
/// <summary>
/// QueryFormatter is a visitor that converts an bound expression tree into SQL query text
/// </summary>
internal class QueryFormatter : DbExpressionVisitor
{
public static readonly ThreadVariable<Func<SqlPreCommandSimple, SqlPreCommandSimple>?> PostFormatter = Statics.ThreadVariable<Func<SqlPreCommandSimple, SqlPreCommandSimple>?>("QueryFormatterPostFormatter");
Schema schema = Schema.Current;
bool isPostgres = Schema.Current.Settings.IsPostgres;
StringBuilder sb = new StringBuilder();
int indent = 2;
int depth;
class DbParameterPair
{
internal DbParameter Parameter;
internal string Name;
public DbParameterPair(DbParameter parameter, string name)
{
Parameter = parameter;
Name = name;
}
}
Dictionary<Expression, DbParameterPair> parameterExpressions = new Dictionary<Expression, DbParameterPair>();
int parameter = 0;
public string GetNextParamAlias()
{
return "@p" + (parameter++);
}
DbParameterPair CreateParameter(ConstantExpression value)
{
string name = GetNextParamAlias();
bool nullable = value.Type.IsClass || value.Type.IsNullable();
object? val = value.Value;
Type clrType = value.Type.UnNullify();
if (clrType.IsEnum)
{
clrType = typeof(int);
val = val == null ? (int?)null : Convert.ToInt32(val);
}
var typePair = Schema.Current.Settings.GetSqlDbTypePair(clrType);
var pb = Connector.Current.ParameterBuilder;
var param = pb.CreateParameter(name, typePair.DbType, typePair.UserDefinedTypeName, nullable, val ?? DBNull.Value);
return new DbParameterPair(param, name);
}
static internal SqlPreCommandSimple Format(Expression expression)
{
QueryFormatter qf = new QueryFormatter();
qf.Visit(expression);
var parameters = qf.parameterExpressions.Values.Select(pi => pi.Parameter).ToList();
var sqlpc = new SqlPreCommandSimple(qf.sb.ToString(), parameters);
return PostFormatter.Value == null ? sqlpc : PostFormatter.Value.Invoke(sqlpc);
}
protected enum Indentation
{
Same,
Inner,
Outer
}
internal int IndentationWidth
{
get { return this.indent; }
set { this.indent = value; }
}
private void AppendNewLine(Indentation style)
{
sb.AppendLine();
this.Indent(style);
for (int i = 0, n = this.depth * this.indent; i < n; i++)
{
sb.Append(' ');
}
}
private void Indent(Indentation style)
{
if (style == Indentation.Inner)
{
this.depth++;
}
else if (style == Indentation.Outer)
{
this.depth--;
System.Diagnostics.Debug.Assert(this.depth >= 0);
}
}
protected override Expression VisitUnary(UnaryExpression u)
{
switch (u.NodeType)
{
case ExpressionType.Not:
sb.Append(" NOT ");
this.Visit(u.Operand);
break;
case ExpressionType.Negate:
sb.Append(" - ");
this.Visit(u.Operand);
break;
case ExpressionType.UnaryPlus:
sb.Append(" + ");
this.Visit(u.Operand);
break;
case ExpressionType.Convert:
//Las unicas conversiones explicitas son a Binary y desde datetime a numeros
this.Visit(u.Operand);
break;
default:
throw new NotSupportedException(string.Format("The unary perator {0} is not supported", u.NodeType));
}
return u;
}
protected override Expression VisitBinary(BinaryExpression b)
{
if (b.NodeType == ExpressionType.Coalesce)
{
sb.Append("COALESCE(");
Visit(b.Left);
sb.Append(',');
Visit(b.Right);
sb.Append(')');
}
else if (b.NodeType == ExpressionType.Equal || b.NodeType == ExpressionType.NotEqual)
{
sb.Append('(');
Visit(b.Left);
sb.Append(b.NodeType == ExpressionType.Equal ? " = " : " <> ");
Visit(b.Right);
sb.Append(')');
}
else if (b.NodeType == ExpressionType.ArrayIndex)
{
Visit(b.Left);
sb.Append('[');
Visit(b.Right);
sb.Append(']');
}
else
{
sb.Append('(');
this.Visit(b.Left);
switch (b.NodeType)
{
case ExpressionType.And:
case ExpressionType.AndAlso:
sb.Append(b.Type.UnNullify() == typeof(bool) ? " AND " : " & ");
break;
case ExpressionType.Or:
case ExpressionType.OrElse:
sb.Append(b.Type.UnNullify() == typeof(bool) ? " OR " : " | ");
break;
case ExpressionType.ExclusiveOr:
sb.Append(" ^ ");
break;
case ExpressionType.LessThan:
sb.Append(" < ");
break;
case ExpressionType.LessThanOrEqual:
sb.Append(" <= ");
break;
case ExpressionType.GreaterThan:
sb.Append(" > ");
break;
case ExpressionType.GreaterThanOrEqual:
sb.Append(" >= ");
break;
case ExpressionType.Add:
case ExpressionType.AddChecked:
if (this.isPostgres && (b.Left.Type == typeof(string) || b.Right.Type == typeof(string)))
sb.Append(" || ");
else
sb.Append(" + ");
break;
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
sb.Append(" - ");
break;
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
sb.Append(" * ");
break;
case ExpressionType.Divide:
sb.Append(" / ");
break;
case ExpressionType.Modulo:
sb.Append(" % ");
break;
default:
throw new NotSupportedException(string.Format("The binary operator {0} is not supported", b.NodeType));
}
this.Visit(b.Right);
sb.Append(')');
}
return b;
}
protected internal override Expression VisitRowNumber(RowNumberExpression rowNumber)
{
sb.Append("ROW_NUMBER() OVER(ORDER BY ");
for (int i = 0, n = rowNumber.OrderBy.Count; i < n; i++)
{
OrderExpression exp = rowNumber.OrderBy[i];
if (i > 0)
sb.Append(", ");
this.Visit(exp.Expression);
if (exp.OrderType != OrderType.Ascending)
sb.Append(" DESC");
}
sb.Append(')');
return rowNumber;
}
protected internal override Expression VisitCase(CaseExpression cex)
{
AppendNewLine(Indentation.Inner);
sb.Append("CASE");
AppendNewLine(Indentation.Inner);
for (int i = 0, n = cex.Whens.Count; i < n; i++)
{
When when = cex.Whens[i];
sb.Append("WHEN ");
Visit(when.Condition);
sb.Append(" THEN ");
Visit(when.Value);
AppendNewLine(Indentation.Same);
}
if (cex.DefaultValue != null)
{
sb.Append("ELSE ");
Visit(cex.DefaultValue);
AppendNewLine(Indentation.Outer);
}
sb.Append("END");
AppendNewLine(Indentation.Outer);
return cex;
}
protected internal override Expression VisitLike(LikeExpression like)
{
Visit(like.Expression);
sb.Append(" LIKE ");
Visit(like.Pattern);
return like;
}
protected internal override Expression VisitExists(ExistsExpression exists)
{
sb.Append("EXISTS(");
this.Visit(exists.Select);
sb.Append(')');
return exists;
}
protected internal override Expression VisitScalar(ScalarExpression exists)
{
sb.Append('(');
this.Visit(exists.Select);
sb.Append(')');
return exists;
}
protected internal override Expression VisitIsNull(IsNullExpression isNull)
{
sb.Append('(');
this.Visit(isNull.Expression);
sb.Append(") IS NULL");
return isNull;
}
protected internal override Expression VisitIsNotNull(IsNotNullExpression isNotNull)
{
sb.Append('(');
this.Visit(isNotNull.Expression);
sb.Append(") IS NOT NULL");
return isNotNull;
}
protected internal override Expression VisitIn(InExpression inExpression)
{
Visit(inExpression.Expression);
sb.Append(" IN (");
if (inExpression.Select == null)
{
bool any = false;
foreach (var obj in inExpression.Values!)
{
VisitConstant(Expression.Constant(obj));
sb.Append(',');
any = true;
}
if (any)
sb.Remove(sb.Length - 1, 1);
}
else
{
Visit(inExpression.Select);
}
sb.Append(" )");
return inExpression;
}
protected internal override Expression VisitSqlLiteral(SqlLiteralExpression sqlEnum)
{
sb.Append(sqlEnum.Value);
return sqlEnum;
}
protected internal override Expression VisitSqlCast(SqlCastExpression castExpr)
{
sb.Append("CAST(");
Visit(castExpr.Expression);
sb.Append(" as ");
sb.Append(castExpr.DbType.ToString(schema.Settings.IsPostgres));
if (!schema.Settings.IsPostgres && (castExpr.DbType.SqlServer == SqlDbType.NVarChar || castExpr.DbType.SqlServer == SqlDbType.VarChar))
sb.Append("(MAX)");
sb.Append(')');
return castExpr;
}
protected override Expression VisitConstant(ConstantExpression c)
{
if (c.Value == null)
sb.Append("NULL");
else
{
if (!schema.Settings.IsDbType(c.Value.GetType().UnNullify()))
throw new NotSupportedException(string.Format("The constant for {0} is not supported", c.Value));
var pi = parameterExpressions.GetOrCreate(c, () => this.CreateParameter(c));
sb.Append(pi.Name);
}
return c;
}
protected internal override Expression VisitSqlConstant(SqlConstantExpression c)
{
if (c.Value == null)
sb.Append("NULL");
else
{
if (!schema.Settings.IsDbType(c.Value.GetType().UnNullify()))
throw new NotSupportedException(string.Format("The constant for {0} is not supported", c.Value));
if (!isPostgres && c.Value.Equals(true))
sb.Append('1');
else if (!isPostgres && c.Value.Equals(false))
sb.Append('0');
else if (c.Value is string s)
sb.Append(s == "" ? "''" : ("'" + s + "'"));
else if (c.Value is TimeSpan ts)
sb.Append(@$"CONVERT(time, '{ts}')");
else if (ReflectionTools.IsDecimalNumber(c.Value.GetType()))
sb.Append(((IFormattable)c.Value).ToString("0.00####", CultureInfo.InvariantCulture));
else
sb.Append(c.ToString());
}
return c;
}
protected internal override Expression VisitSqlVariable(SqlVariableExpression sve)
{
sb.Append(sve.VariableName);
return sve;
}
protected internal override Expression VisitColumn(ColumnExpression column)
{
sb.Append(column.Alias.ToString());
if (column.Name != null) //Is null for PostgressFunctions.unnest and friends (IQueryable<int> table-valued function)
{
sb.Append('.');
sb.Append(column.Name.SqlEscape(isPostgres));
}
return column;
}
protected internal override Expression VisitSelect(SelectExpression select)
{
bool isFirst = sb.Length == 0;
if (!isFirst)
{
AppendNewLine(Indentation.Inner);
sb.Append('(');
}
sb.Append("SELECT ");
if (select.IsDistinct)
sb.Append("DISTINCT ");
if (select.Top != null && !this.isPostgres)
{
sb.Append("TOP (");
Visit(select.Top);
sb.Append(") ");
}
if (select.Columns.Count == 0)
sb.Append("0 as Dummy");
else
{
this.AppendNewLine(Indentation.Inner);
for (int i = 0, n = select.Columns.Count; i < n; i++)
{
ColumnDeclaration column = select.Columns[i];
AppendColumn(column);
if (i < (n - 1))
{
sb.Append(", ");
this.AppendNewLine(Indentation.Same);
}
else
{
this.Indent(Indentation.Outer);
}
}
}
if (select.From != null)
{
this.AppendNewLine(Indentation.Same);
sb.Append("FROM ");
this.VisitSource(select.From);
}
if (select.Where != null)
{
this.AppendNewLine(Indentation.Same);
sb.Append("WHERE ");
this.Visit(select.Where);
}
if (select.GroupBy.Count > 0)
{
this.AppendNewLine(Indentation.Same);
sb.Append("GROUP BY ");
for (int i = 0, n = select.GroupBy.Count; i < n; i++)
{
Expression exp = select.GroupBy[i];
if (i > 0)
{
sb.Append(", ");
}
this.Visit(exp);
}
}
if (select.OrderBy.Count > 0)
{
this.AppendNewLine(Indentation.Same);
sb.Append("ORDER BY ");
for (int i = 0, n = select.OrderBy.Count; i < n; i++)
{
OrderExpression exp = select.OrderBy[i];
if (i > 0)
{
sb.Append(", ");
}
this.Visit(exp.Expression);
if (exp.OrderType != OrderType.Ascending)
{
sb.Append(" DESC");
}
}
}
if (select.Top != null && this.isPostgres)
{
this.AppendNewLine(Indentation.Same);
sb.Append("LIMIT ");
Visit(select.Top);
}
if (select.IsForXmlPathEmpty)
{
this.AppendNewLine(Indentation.Same);
sb.Append("FOR XML PATH('')");
}
if (!isFirst)
{
sb.Append(')');
AppendNewLine(Indentation.Outer);
}
return select;
}
string GetAggregateFunction(AggregateSqlFunction agg)
{
return agg switch
{
AggregateSqlFunction.Average => "AVG",
AggregateSqlFunction.StdDev => !isPostgres ? "STDEV" : "stddev_samp",
AggregateSqlFunction.StdDevP => !isPostgres? "STDEVP" : "stddev_pop",
AggregateSqlFunction.Count => "COUNT",
AggregateSqlFunction.CountDistinct => "COUNT",
AggregateSqlFunction.Max => "MAX",
AggregateSqlFunction.Min => "MIN",
AggregateSqlFunction.Sum => "SUM",
AggregateSqlFunction.string_agg => "string_agg",
_ => throw new UnexpectedValueException(agg)
};
}
protected internal override Expression VisitAggregate(AggregateExpression aggregate)
{
sb.Append(GetAggregateFunction(aggregate.AggregateFunction));
sb.Append('(');
if (aggregate.AggregateFunction == AggregateSqlFunction.CountDistinct)
sb.Append("DISTINCT ");
if (aggregate.Arguments.Count == 1 && aggregate.Arguments[0] == null && aggregate.AggregateFunction == AggregateSqlFunction.Count)
{
sb.Append('*');
}
else
{
for (int i = 0, n = aggregate.Arguments.Count; i < n; i++)
{
Expression exp = aggregate.Arguments[i];
if (i > 0)
sb.Append(", ");
this.Visit(exp);
}
}
sb.Append(')');
return aggregate;
}
protected internal override Expression VisitSqlFunction(SqlFunctionExpression sqlFunction)
{
if (isPostgres && sqlFunction.SqlFunction == PostgresFunction.EXTRACT.ToString())
{
sb.Append(sqlFunction.SqlFunction);
sb.Append('(');
this.Visit(sqlFunction.Arguments[0]);
sb.Append(" from ");
this.Visit(sqlFunction.Arguments[1]);
sb.Append(')');
}
else if(isPostgres && PostgressOperator.All.Contains(sqlFunction.SqlFunction))
{
sb.Append('(');
this.Visit(sqlFunction.Arguments[0]);
sb.Append(" " + sqlFunction.SqlFunction + " ");
this.Visit(sqlFunction.Arguments[1]);
sb.Append(')');
}
else if (sqlFunction.SqlFunction == SqlFunction.COLLATE.ToString())
{
this.Visit(sqlFunction.Arguments[0]);
sb.Append(" COLLATE ");
if (sqlFunction.Arguments[1] is SqlConstantExpression ce)
sb.Append((string)ce.Value!);
}
else
{
if (sqlFunction.Object != null)
{
Visit(sqlFunction.Object);
sb.Append('.');
}
sb.Append(sqlFunction.SqlFunction);
sb.Append('(');
for (int i = 0, n = sqlFunction.Arguments.Count; i < n; i++)
{
Expression exp = sqlFunction.Arguments[i];
if (i > 0)
sb.Append(", ");
this.Visit(exp);
}
sb.Append(')');
}
return sqlFunction;
}
protected internal override Expression VisitSqlTableValuedFunction(SqlTableValuedFunctionExpression sqlFunction)
{
sb.Append(sqlFunction.SqlFunction.ToString());
sb.Append('(');
for (int i = 0, n = sqlFunction.Arguments.Count; i < n; i++)
{
Expression exp = sqlFunction.Arguments[i];
if (i > 0)
sb.Append(", ");
this.Visit(exp);
}
sb.Append(')');
return sqlFunction;
}
private void AppendColumn(ColumnDeclaration column)
{
ColumnExpression? c = column.Expression as ColumnExpression;
if (column.Name.HasText() && (c == null || c.Name != column.Name))
{
this.Visit(column.Expression);
sb.Append(" as ");
sb.Append(column.Name.SqlEscape(isPostgres));
}
else
{
this.Visit(column.Expression);
}
}
protected internal override Expression VisitTable(TableExpression table)
{
sb.Append(table.Name.ToString());
if (table.SystemTime != null && !(table.SystemTime is SystemTime.HistoryTable))
{
sb.Append(' ');
WriteSystemTime(table.SystemTime);
}
return table;
}
private void WriteSystemTime(SystemTime st)
{
sb.Append("FOR SYSTEM_TIME ");
switch (st)
{
case SystemTime.AsOf asOf:
{
sb.Append("AS OF ");
this.VisitSystemTimeConstant(asOf.DateTime);
break;
}
case SystemTime.Between between:
{
sb.Append("BETWEEN ");
this.VisitSystemTimeConstant(between.StartDateTime);
sb.Append(" AND ");
this.VisitSystemTimeConstant(between.EndtDateTime);
break;
}
case SystemTime.ContainedIn contained:
{
sb.Append("CONTAINED IN (");
this.VisitSystemTimeConstant(contained.StartDateTime);
sb.Append(", ");
this.VisitSystemTimeConstant(contained.EndtDateTime);
sb.Append(')');
break;
}
case SystemTime.All:
{
sb.Append("ALL");
break;
}
default:
throw new UnexpectedValueException(st);
}
}
Dictionary<DateTimeOffset, ConstantExpression> systemTimeConstants = new Dictionary<DateTimeOffset, ConstantExpression>();
void VisitSystemTimeConstant(DateTimeOffset datetime)
{
var c = systemTimeConstants.GetOrCreate(datetime, dt => Expression.Constant(dt));
VisitConstant(c);
}
protected internal override SourceExpression VisitSource(SourceExpression source)
{
if (source is SourceWithAliasExpression swae)
{
if (source is TableExpression || source is SqlTableValuedFunctionExpression)
Visit(source);
else
{
sb.Append('(');
Visit(source);
sb.Append(')');
}
sb.Append(" AS ");
sb.Append(swae.Alias.ToString());
if (source is TableExpression ta && ta.WithHint != null)
{
sb.Append(" WITH(" + ta.WithHint + ")");
}
}
else
this.VisitJoin((JoinExpression)source);
return source;
}
protected internal override Expression VisitJoin(JoinExpression join)
{
this.VisitSource(join.Left);
this.AppendNewLine(Indentation.Same);
switch (join.JoinType)
{
case JoinType.CrossJoin:
sb.Append("CROSS JOIN ");
break;
case JoinType.InnerJoin:
sb.Append("INNER JOIN ");
break;
case JoinType.LeftOuterJoin:
case JoinType.SingleRowLeftOuterJoin:
sb.Append("LEFT OUTER JOIN ");
break;
case JoinType.RightOuterJoin:
sb.Append("RIGHT OUTER JOIN ");
break;
case JoinType.FullOuterJoin:
sb.Append("FULL OUTER JOIN ");
break;
case JoinType.CrossApply:
sb.Append(isPostgres ? "JOIN LATERAL " : "CROSS APPLY ");
break;
case JoinType.OuterApply:
sb.Append(isPostgres ? "LEFT JOIN LATERAL " : "OUTER APPLY ");
break;
}
bool needsMoreParenthesis = (join.JoinType == JoinType.CrossApply || join.JoinType == JoinType.OuterApply) && join.Right is JoinExpression;
if (needsMoreParenthesis)
sb.Append('(');
this.VisitSource(join.Right);
if (needsMoreParenthesis)
sb.Append(')');
if (join.Condition != null)
{
this.AppendNewLine(Indentation.Inner);
sb.Append("ON ");
this.Visit(join.Condition);
this.Indent(Indentation.Outer);
}
else if (isPostgres && join.JoinType != JoinType.CrossJoin)
{
this.AppendNewLine(Indentation.Inner);
sb.Append("ON true");
this.Indent(Indentation.Outer);
}
return join;
}
protected internal override Expression VisitSetOperator(SetOperatorExpression set)
{
VisitSetPart(set.Left);
switch (set.Operator)
{
case SetOperator.Union: sb.Append("UNION"); break;
case SetOperator.UnionAll: sb.Append("UNION ALL"); break;
case SetOperator.Intersect: sb.Append("INTERSECT"); break;
case SetOperator.Except: sb.Append("EXCEPT"); break;
default:
throw new InvalidOperationException("Unexpected SetOperator {0}".FormatWith(set.Operator));
}
VisitSetPart(set.Right);
return set;
}
void VisitSetPart(SourceWithAliasExpression source)
{
if (source is SelectExpression se)
{
this.Indent(Indentation.Inner);
VisitSelect(se);
this.Indent(Indentation.Outer);
}
else if (source is SetOperatorExpression soe)
{
VisitSetOperator(soe);
}
else
throw new InvalidOperationException("{0} not expected in SetOperatorExpression".FormatWith(source.ToString()));
}
protected internal override Expression VisitDelete(DeleteExpression delete)
{
using (this.PrintSelectRowCount(delete.ReturnRowCount))
{
sb.Append("DELETE FROM ");
sb.Append(delete.Name.ToString());
this.AppendNewLine(Indentation.Same);
if (isPostgres)
sb.Append("USING ");
else
sb.Append("FROM ");
VisitSource(delete.Source);
if (delete.Where != null)
{
this.AppendNewLine(Indentation.Same);
sb.Append("WHERE ");
Visit(delete.Where);
}
return delete;
}
}
protected internal override Expression VisitUpdate(UpdateExpression update)
{
using (this.PrintSelectRowCount(update.ReturnRowCount))
{
sb.Append("UPDATE ");
sb.Append(update.Name.ToString());
sb.Append(" SET");
this.AppendNewLine(Indentation.Inner);
for (int i = 0, n = update.Assigments.Count; i < n; i++)
{
ColumnAssignment assignment = update.Assigments[i];
if (i > 0)
{
sb.Append(',');
this.AppendNewLine(Indentation.Same);
}
sb.Append(assignment.Column.SqlEscape(isPostgres));
sb.Append(" = ");
this.Visit(assignment.Expression);
}
this.AppendNewLine(Indentation.Outer);
sb.Append("FROM ");
VisitSource(update.Source);
if (update.Where != null)
{
this.AppendNewLine(Indentation.Same);
sb.Append("WHERE ");
Visit(update.Where);
}
return update;
}
}
protected internal override Expression VisitInsertSelect(InsertSelectExpression insertSelect)
{
using (this.PrintSelectRowCount(insertSelect.ReturnRowCount))
{
sb.Append("INSERT INTO ");
sb.Append(insertSelect.Name.ToString());
sb.Append('(');
for (int i = 0, n = insertSelect.Assigments.Count; i < n; i++)
{
ColumnAssignment assignment = insertSelect.Assigments[i];
if (i > 0)
{
sb.Append(", ");
if (i % 4 == 0)
this.AppendNewLine(Indentation.Same);
}
sb.Append(assignment.Column.SqlEscape(isPostgres));
}
sb.Append(')');
this.AppendNewLine(Indentation.Same);
if(this.isPostgres && Administrator.IsIdentityBehaviourDisabled(insertSelect.Table))
{
sb.Append("OVERRIDING SYSTEM VALUE");
this.AppendNewLine(Indentation.Same);
}
sb.Append("SELECT ");
for (int i = 0, n = insertSelect.Assigments.Count; i < n; i++)
{
ColumnAssignment assignment = insertSelect.Assigments[i];
if (i > 0)
{
sb.Append(", ");
if (i % 4 == 0)
this.AppendNewLine(Indentation.Same);
}
this.Visit(assignment.Expression);
}
sb.Append(" FROM ");
VisitSource(insertSelect.Source);
return insertSelect;
}
}
protected internal IDisposable? PrintSelectRowCount(bool returnRowCount)
{
if (returnRowCount == false)
return null;
if (!this.isPostgres)
{
return new Disposable(() =>
{
sb.AppendLine();
sb.AppendLine("SELECT @@rowcount");
});
}
else
{
sb.Append("WITH rows AS (");
this.AppendNewLine(Indentation.Inner);
return new Disposable(() =>
{
this.AppendNewLine(Indentation.Same);
sb.Append("RETURNING 1");
this.AppendNewLine(Indentation.Outer);
sb.Append(')');
this.AppendNewLine(Indentation.Same);
sb.Append("SELECT CAST(COUNT(*) AS INTEGER) FROM rows");
});
}
}
protected internal override Expression VisitCommandAggregate(CommandAggregateExpression cea)
{
for (int i = 0, n = cea.Commands.Count; i < n; i++)
{
CommandExpression command = cea.Commands[i];
if (i > 0)
{
sb.Append(';');
this.AppendNewLine(Indentation.Same);
}
this.Visit(command);
}
return cea;
}
protected internal override Expression VisitAggregateRequest(AggregateRequestsExpression aggregate)
{
throw InvalidSqlExpression(aggregate);
}
protected internal override Expression VisitChildProjection(ChildProjectionExpression child)
{
throw InvalidSqlExpression(child);
}
protected override Expression VisitConditional(ConditionalExpression c)
{
throw InvalidSqlExpression(c);
}
protected internal override Expression VisitEmbeddedEntity(EmbeddedEntityExpression eee)
{
throw InvalidSqlExpression(eee);
}
protected internal override Expression VisitImplementedBy(ImplementedByExpression reference)
{
throw InvalidSqlExpression(reference);
}
protected internal override Expression VisitImplementedByAll(ImplementedByAllExpression reference)
{
throw InvalidSqlExpression(reference);
}
protected internal override Expression VisitEntity(EntityExpression ee)
{
throw InvalidSqlExpression(ee);
}
protected override Expression VisitLambda<T>(Expression<T> lambda)
{
throw InvalidSqlExpression(lambda);
}
protected override Expression VisitListInit(ListInitExpression init)
{
throw InvalidSqlExpression(init);
}
protected internal override Expression VisitLiteValue(LiteValueExpression lite)
{
throw InvalidSqlExpression(lite);
}
protected internal override Expression VisitLiteReference(LiteReferenceExpression lite)
{
return base.VisitLiteReference(lite);
}
protected override Expression VisitInvocation(InvocationExpression iv)
{
throw InvalidSqlExpression(iv);
}
protected override Expression VisitMember(MemberExpression m)
{
throw InvalidSqlExpression(m);
}
protected override Expression VisitMemberInit(MemberInitExpression init)
{
throw InvalidSqlExpression(init);
}
protected override Expression VisitMethodCall(MethodCallExpression m)
{
throw InvalidSqlExpression(m);
}
protected internal override Expression VisitMList(MListExpression ml)
{
throw InvalidSqlExpression(ml);
}
protected internal override Expression VisitMListElement(MListElementExpression mle)
{
throw InvalidSqlExpression(mle);
}
protected override Expression VisitNew(NewExpression nex)
{
throw InvalidSqlExpression(nex);
}
protected override Expression VisitNewArray(NewArrayExpression na)
{
throw InvalidSqlExpression(na);
}
protected override Expression VisitParameter(ParameterExpression p)
{
throw InvalidSqlExpression(p);
}
protected internal override Expression VisitTypeEntity(TypeEntityExpression typeFie)
{
throw InvalidSqlExpression(typeFie);
}
protected internal override Expression VisitProjection(ProjectionExpression proj)
{
throw InvalidSqlExpression(proj);
}
protected internal override Expression VisitTypeImplementedBy(TypeImplementedByExpression typeIb)
{
throw InvalidSqlExpression(typeIb);
}
protected internal override Expression VisitTypeImplementedByAll(TypeImplementedByAllExpression typeIba)
{
throw InvalidSqlExpression(typeIba);
}
protected override Expression VisitTypeBinary(TypeBinaryExpression b)
{
throw InvalidSqlExpression(b);
}
private static InvalidOperationException InvalidSqlExpression(Expression expression)
{
return new InvalidOperationException("Unexepected expression on sql {0}".FormatWith(expression.ToString()));
}
}
public class QueryPostFormatter : IDisposable
{
Func<SqlPreCommandSimple, SqlPreCommandSimple>? prePostFormatter = null;
public QueryPostFormatter(Func<SqlPreCommandSimple, SqlPreCommandSimple> postFormatter)
{
prePostFormatter = QueryFormatter.PostFormatter.Value;
QueryFormatter.PostFormatter.Value = postFormatter;
}
#pragma warning disable CA1816 // Dispose methods should call SuppressFinalize
public void Dispose()
{
QueryFormatter.PostFormatter.Value = prePostFormatter;
}
#pragma warning restore CA1816 // Dispose methods should call SuppressFinalize
}
| |
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace XmlStore
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ListBox tablesListbox;
private System.Windows.Forms.TextBox tableNameTextbox;
private System.Windows.Forms.Button addTableButton;
private System.Windows.Forms.Button removeTableButton;
private System.Windows.Forms.Button changeTableNameButton;
private System.Windows.Forms.TextBox columnNameTextbox;
private System.Windows.Forms.ComboBox columnTypeCombobox;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button changeColumnButton;
private System.Windows.Forms.Button removeColumnButton;
private System.Windows.Forms.Button addColumnButton;
private System.Windows.Forms.ListView columnsListbox;
private System.Windows.Forms.ColumnHeader columnName;
private System.Windows.Forms.ColumnHeader columnType;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuFile;
private System.Windows.Forms.MenuItem menuNew;
private System.Windows.Forms.MenuItem menuOpen;
private System.Windows.Forms.MenuItem menuItem5;
private System.Windows.Forms.MenuItem menuSave;
private System.Windows.Forms.MenuItem menuSaveAs;
private System.Windows.Forms.MenuItem menuItem8;
private System.Windows.Forms.MenuItem menuExit;
private DataTable currentTable;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.MenuItem menuAbout;
private string fileNameSchema=null;
private DataSet dataSet = new DataSet();
private MenuItem menuTools;
private MenuItem menuXMLDocValidator;
private TabControl mainTabControl;
private TabPage tabPage1;
private TabPage tabPage2;
private StatusStrip statusStrip1;
private GroupBox groupBoxExistingTables;
private DataGrid dataDatagrid;
private GroupBox groupBox3;
private GroupBox groupBox5;
private GroupBox groupBox4;
private MenuItem xpathLocatorMenuItem;
private MenuItem saveSchemaMenuItem;
private MenuItem saveXMLDataMenuItem;
private IContainer components;
public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <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()
{
this.components = new System.ComponentModel.Container();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.tableNameTextbox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.addTableButton = new System.Windows.Forms.Button();
this.groupBoxExistingTables = new System.Windows.Forms.GroupBox();
this.changeTableNameButton = new System.Windows.Forms.Button();
this.tablesListbox = new System.Windows.Forms.ListBox();
this.removeTableButton = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.columnsListbox = new System.Windows.Forms.ListView();
this.columnName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnType = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.removeColumnButton = new System.Windows.Forms.Button();
this.changeColumnButton = new System.Windows.Forms.Button();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.addColumnButton = new System.Windows.Forms.Button();
this.columnNameTextbox = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.columnTypeCombobox = new System.Windows.Forms.ComboBox();
this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
this.menuFile = new System.Windows.Forms.MenuItem();
this.menuNew = new System.Windows.Forms.MenuItem();
this.menuOpen = new System.Windows.Forms.MenuItem();
this.menuItem5 = new System.Windows.Forms.MenuItem();
this.menuSave = new System.Windows.Forms.MenuItem();
this.menuSaveAs = new System.Windows.Forms.MenuItem();
this.menuItem8 = new System.Windows.Forms.MenuItem();
this.menuExit = new System.Windows.Forms.MenuItem();
this.menuTools = new System.Windows.Forms.MenuItem();
this.saveXMLDataMenuItem = new System.Windows.Forms.MenuItem();
this.saveSchemaMenuItem = new System.Windows.Forms.MenuItem();
this.menuXMLDocValidator = new System.Windows.Forms.MenuItem();
this.xpathLocatorMenuItem = new System.Windows.Forms.MenuItem();
this.menuAbout = new System.Windows.Forms.MenuItem();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.mainTabControl = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.dataDatagrid = new System.Windows.Forms.DataGrid();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.groupBox1.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBoxExistingTables.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox5.SuspendLayout();
this.groupBox4.SuspendLayout();
this.mainTabControl.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataDatagrid)).BeginInit();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.groupBox3);
this.groupBox1.Controls.Add(this.groupBoxExistingTables);
this.groupBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.groupBox1.Location = new System.Drawing.Point(8, 6);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(388, 531);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Tables";
//
// groupBox3
//
this.groupBox3.Controls.Add(this.tableNameTextbox);
this.groupBox3.Controls.Add(this.label1);
this.groupBox3.Controls.Add(this.addTableButton);
this.groupBox3.Location = new System.Drawing.Point(6, 19);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(373, 100);
this.groupBox3.TabIndex = 6;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "New Table:";
//
// tableNameTextbox
//
this.tableNameTextbox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tableNameTextbox.Location = new System.Drawing.Point(135, 21);
this.tableNameTextbox.Name = "tableNameTextbox";
this.tableNameTextbox.Size = new System.Drawing.Size(232, 20);
this.tableNameTextbox.TabIndex = 0;
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(89, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(40, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Na&me:";
//
// addTableButton
//
this.addTableButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.addTableButton.Location = new System.Drawing.Point(263, 47);
this.addTableButton.Name = "addTableButton";
this.addTableButton.Size = new System.Drawing.Size(104, 24);
this.addTableButton.TabIndex = 1;
this.addTableButton.Text = "&Add Table";
this.addTableButton.Click += new System.EventHandler(this.btnAddTable_Click);
//
// groupBoxExistingTables
//
this.groupBoxExistingTables.Controls.Add(this.changeTableNameButton);
this.groupBoxExistingTables.Controls.Add(this.tablesListbox);
this.groupBoxExistingTables.Controls.Add(this.removeTableButton);
this.groupBoxExistingTables.Location = new System.Drawing.Point(6, 125);
this.groupBoxExistingTables.Name = "groupBoxExistingTables";
this.groupBoxExistingTables.Size = new System.Drawing.Size(373, 400);
this.groupBoxExistingTables.TabIndex = 5;
this.groupBoxExistingTables.TabStop = false;
this.groupBoxExistingTables.Text = "Existing tables:";
//
// changeTableNameButton
//
this.changeTableNameButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.changeTableNameButton.Location = new System.Drawing.Point(144, 370);
this.changeTableNameButton.Name = "changeTableNameButton";
this.changeTableNameButton.Size = new System.Drawing.Size(104, 24);
this.changeTableNameButton.TabIndex = 2;
this.changeTableNameButton.Text = "&Change Name";
this.changeTableNameButton.Click += new System.EventHandler(this.changeTableNameButton_Click);
//
// tablesListbox
//
this.tablesListbox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tablesListbox.Location = new System.Drawing.Point(6, 19);
this.tablesListbox.Name = "tablesListbox";
this.tablesListbox.Size = new System.Drawing.Size(361, 342);
this.tablesListbox.TabIndex = 4;
this.tablesListbox.TabStop = false;
this.tablesListbox.SelectedIndexChanged += new System.EventHandler(this.tablesListBox_SelectedIndexChanged);
//
// removeTableButton
//
this.removeTableButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.removeTableButton.Location = new System.Drawing.Point(263, 370);
this.removeTableButton.Name = "removeTableButton";
this.removeTableButton.Size = new System.Drawing.Size(104, 24);
this.removeTableButton.TabIndex = 3;
this.removeTableButton.Text = "&Remove Table";
this.removeTableButton.Click += new System.EventHandler(this.removeButtonTable_Click);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.groupBox5);
this.groupBox2.Controls.Add(this.groupBox4);
this.groupBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.groupBox2.Location = new System.Drawing.Point(399, 6);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(379, 531);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Columns";
//
// groupBox5
//
this.groupBox5.Controls.Add(this.columnsListbox);
this.groupBox5.Controls.Add(this.removeColumnButton);
this.groupBox5.Controls.Add(this.changeColumnButton);
this.groupBox5.Location = new System.Drawing.Point(6, 125);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(367, 400);
this.groupBox5.TabIndex = 11;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Existing Columns:";
//
// columnsListbox
//
this.columnsListbox.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnName,
this.columnType});
this.columnsListbox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.columnsListbox.FullRowSelect = true;
this.columnsListbox.HideSelection = false;
this.columnsListbox.Location = new System.Drawing.Point(4, 19);
this.columnsListbox.Name = "columnsListbox";
this.columnsListbox.Size = new System.Drawing.Size(357, 342);
this.columnsListbox.TabIndex = 5;
this.columnsListbox.TabStop = false;
this.columnsListbox.UseCompatibleStateImageBehavior = false;
this.columnsListbox.View = System.Windows.Forms.View.Details;
this.columnsListbox.SelectedIndexChanged += new System.EventHandler(this.columnsListbox_SelectedIndexChanged);
//
// columnName
//
this.columnName.Text = "Name";
this.columnName.Width = 260;
//
// columnType
//
this.columnType.Text = "Type";
this.columnType.Width = 90;
//
// removeColumnButton
//
this.removeColumnButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.removeColumnButton.Location = new System.Drawing.Point(257, 370);
this.removeColumnButton.Name = "removeColumnButton";
this.removeColumnButton.Size = new System.Drawing.Size(104, 24);
this.removeColumnButton.TabIndex = 4;
this.removeColumnButton.Text = "Remo&ve Column";
this.removeColumnButton.Click += new System.EventHandler(this.removeColumnButton_Click);
//
// changeColumnButton
//
this.changeColumnButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.changeColumnButton.Location = new System.Drawing.Point(147, 370);
this.changeColumnButton.Name = "changeColumnButton";
this.changeColumnButton.Size = new System.Drawing.Size(104, 24);
this.changeColumnButton.TabIndex = 3;
this.changeColumnButton.Text = "Change &Name";
this.changeColumnButton.Click += new System.EventHandler(this.changeColumnButton_Click);
//
// groupBox4
//
this.groupBox4.Controls.Add(this.addColumnButton);
this.groupBox4.Controls.Add(this.columnNameTextbox);
this.groupBox4.Controls.Add(this.label4);
this.groupBox4.Controls.Add(this.label2);
this.groupBox4.Controls.Add(this.columnTypeCombobox);
this.groupBox4.Location = new System.Drawing.Point(6, 19);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(367, 100);
this.groupBox4.TabIndex = 10;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "New Column:";
//
// addColumnButton
//
this.addColumnButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.addColumnButton.Location = new System.Drawing.Point(257, 70);
this.addColumnButton.Name = "addColumnButton";
this.addColumnButton.Size = new System.Drawing.Size(104, 24);
this.addColumnButton.TabIndex = 2;
this.addColumnButton.Text = "Add C&olumn";
this.addColumnButton.Click += new System.EventHandler(this.addColumnButton_Click);
//
// columnNameTextbox
//
this.columnNameTextbox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.columnNameTextbox.Location = new System.Drawing.Point(135, 19);
this.columnNameTextbox.Name = "columnNameTextbox";
this.columnNameTextbox.Size = new System.Drawing.Size(226, 20);
this.columnNameTextbox.TabIndex = 0;
//
// label4
//
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(76, 43);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(40, 16);
this.label4.TabIndex = 9;
this.label4.Text = "&Type:";
//
// label2
//
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(76, 19);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(40, 16);
this.label2.TabIndex = 0;
this.label2.Text = "Nam&e:";
//
// columnTypeCombobox
//
this.columnTypeCombobox.CausesValidation = false;
this.columnTypeCombobox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.columnTypeCombobox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.columnTypeCombobox.Items.AddRange(new object[] {
"Boolean",
"Byte",
"Char",
"DateTime",
"Decimal",
"Double",
"Int16",
"Int32",
"Int64",
"String"});
this.columnTypeCombobox.Location = new System.Drawing.Point(135, 43);
this.columnTypeCombobox.Name = "columnTypeCombobox";
this.columnTypeCombobox.Size = new System.Drawing.Size(226, 21);
this.columnTypeCombobox.TabIndex = 1;
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuFile,
this.menuTools,
this.menuAbout});
//
// menuFile
//
this.menuFile.Index = 0;
this.menuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuNew,
this.menuOpen,
this.menuItem5,
this.menuSave,
this.menuSaveAs,
this.menuItem8,
this.menuExit});
this.menuFile.Text = "&File";
//
// menuNew
//
this.menuNew.Index = 0;
this.menuNew.Shortcut = System.Windows.Forms.Shortcut.CtrlN;
this.menuNew.Text = "&New";
this.menuNew.Click += new System.EventHandler(this.newMenu_Click);
//
// menuOpen
//
this.menuOpen.Index = 1;
this.menuOpen.Shortcut = System.Windows.Forms.Shortcut.CtrlO;
this.menuOpen.Text = "Open";
this.menuOpen.Click += new System.EventHandler(this.openMenu_Click);
//
// menuItem5
//
this.menuItem5.Index = 2;
this.menuItem5.Text = "-";
//
// menuSave
//
this.menuSave.Index = 3;
this.menuSave.Shortcut = System.Windows.Forms.Shortcut.CtrlS;
this.menuSave.Text = "&Save";
this.menuSave.Click += new System.EventHandler(this.saveMenu_Click);
//
// menuSaveAs
//
this.menuSaveAs.Index = 4;
this.menuSaveAs.Shortcut = System.Windows.Forms.Shortcut.CtrlA;
this.menuSaveAs.Text = "Save &As...";
this.menuSaveAs.Click += new System.EventHandler(this.saveAsMenu_Click);
//
// menuItem8
//
this.menuItem8.Index = 5;
this.menuItem8.Text = "-";
//
// menuExit
//
this.menuExit.Index = 6;
this.menuExit.Shortcut = System.Windows.Forms.Shortcut.CtrlX;
this.menuExit.Text = "E&xit";
this.menuExit.Click += new System.EventHandler(this.exitMenu_Click);
//
// menuTools
//
this.menuTools.Index = 1;
this.menuTools.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.saveXMLDataMenuItem,
this.saveSchemaMenuItem,
this.xpathLocatorMenuItem,
this.menuXMLDocValidator});
this.menuTools.Text = "&Tools";
//
// saveXMLDataMenuItem
//
this.saveXMLDataMenuItem.Index = 0;
this.saveXMLDataMenuItem.Text = "Save XML Data";
this.saveXMLDataMenuItem.Click += new System.EventHandler(this.saveXMLDataMenuItem_Click);
//
// saveSchemaMenuItem
//
this.saveSchemaMenuItem.Index = 1;
this.saveSchemaMenuItem.Text = "Save XML Schema";
this.saveSchemaMenuItem.Click += new System.EventHandler(this.saveSchemaMenuItem_Click);
//
// menuXMLDocValidator
//
this.menuXMLDocValidator.Index = 3;
this.menuXMLDocValidator.Text = "XML Doc Validator";
this.menuXMLDocValidator.Click += new System.EventHandler(this.menuXMLDocValidator_Click);
//
// xpathLocatorMenuItem
//
this.xpathLocatorMenuItem.Index = 2;
this.xpathLocatorMenuItem.Text = "XPath Validator";
this.xpathLocatorMenuItem.Click += new System.EventHandler(this.xpathLocatorMenuItem_Click);
//
// menuAbout
//
this.menuAbout.Index = 2;
this.menuAbout.Text = "&About!";
this.menuAbout.Click += new System.EventHandler(this.aboutMenu_Click);
//
// saveFileDialog
//
this.saveFileDialog.DefaultExt = "xml";
this.saveFileDialog.Filter = "XML Files|*.xml";
this.saveFileDialog.InitialDirectory = ".\\";
this.saveFileDialog.Title = "Save Database As...";
//
// openFileDialog
//
this.openFileDialog.DefaultExt = "xml";
this.openFileDialog.Filter = "\"XML Files|*.xml";
//
// mainTabControl
//
this.mainTabControl.Controls.Add(this.tabPage1);
this.mainTabControl.Controls.Add(this.tabPage2);
this.mainTabControl.Location = new System.Drawing.Point(0, 2);
this.mainTabControl.Name = "mainTabControl";
this.mainTabControl.SelectedIndex = 0;
this.mainTabControl.Size = new System.Drawing.Size(842, 687);
this.mainTabControl.TabIndex = 3;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.groupBox1);
this.tabPage1.Controls.Add(this.groupBox2);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(834, 661);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Schema";
this.tabPage1.UseVisualStyleBackColor = true;
//
// tabPage2
//
this.tabPage2.Controls.Add(this.dataDatagrid);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(831, 661);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Data";
this.tabPage2.UseVisualStyleBackColor = true;
//
// dataDatagrid
//
this.dataDatagrid.DataMember = "";
this.dataDatagrid.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.dataDatagrid.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataDatagrid.Location = new System.Drawing.Point(0, 3);
this.dataDatagrid.Name = "dataDatagrid";
this.dataDatagrid.Size = new System.Drawing.Size(781, 544);
this.dataDatagrid.TabIndex = 0;
//
// statusStrip1
//
this.statusStrip1.AutoSize = false;
this.statusStrip1.Location = new System.Drawing.Point(0, 568);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(785, 21);
this.statusStrip1.SizingGrip = false;
this.statusStrip1.Stretch = false;
this.statusStrip1.TabIndex = 4;
this.statusStrip1.Text = "statusStrip1";
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(785, 589);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.mainTabControl);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.Menu = this.mainMenu1;
this.Name = "MainForm";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "XML Store v1.0";
this.groupBox1.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.groupBoxExistingTables.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox5.ResumeLayout(false);
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.mainTabControl.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataDatagrid)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new MainForm());
}
// ========================== MENU COMMANDS =========================
/// <summary>
/// Hanles New menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void newMenu_Click(object sender, System.EventArgs e)
{
fileNameSchema=null;
tablesListbox.Items.Clear();
columnsListbox.Items.Clear();
tableNameTextbox.Text = "";
columnNameTextbox.Text = "";
columnTypeCombobox.Text = "";
this.Text = "XML Store";
dataSet = new DataSet();
dataDatagrid.SetDataBinding(dataSet, null);
}
/// <summary>
/// Handles Open menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void openMenu_Click(object sender, System.EventArgs e)
{
openFileDialog.Title = "Select file to open the store...";
DialogResult dialogResult = openFileDialog.ShowDialog(this);
if (dialogResult == DialogResult.OK)
{
string fileName = openFileDialog.FileName;
DataSet ds = new DataSet();
ds.ReadXml(fileName);
tablesListbox.Items.Clear();
foreach (DataTable dt in ds.Tables)
{
tablesListbox.Items.Add(dt.TableName);
}
dataSet = ds;
tablesListbox.SelectedIndex = 0;
fileNameSchema = fileName;
this.Text="XML Store - "+fileNameSchema;
}
}
/// <summary>
/// Handles Save menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveMenu_Click(object sender, System.EventArgs e)
{
if (fileNameSchema == null)
saveAsMenu_Click(sender, e);
else
{
SaveXml(fileNameSchema, true);
tablesListbox.SelectedIndex=tablesListbox.SelectedIndex; // reselect
}
}
/// <summary>
/// Handles SaveAs menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveAsMenu_Click(object sender, System.EventArgs e)
{
DialogResult res = saveFileDialog.ShowDialog(this);
if (res == DialogResult.OK)
{
fileNameSchema = saveFileDialog.FileName;
SaveXml(fileNameSchema, true);
this.Text="XML Store - "+fileNameSchema;
tablesListbox.SelectedIndex=tablesListbox.SelectedIndex; // reselect
}
}
/// <summary>
/// Handles About menu
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void aboutMenu_Click(object sender, System.EventArgs e)
{
MessageBox.Show("XML Store v1.0\nShikha Agrawal & Deeti Shah\[email protected]", "XML Store & Database v1.0",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
/// <summary>
/// Handles exit menu command
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void exitMenu_Click(object sender, System.EventArgs e)
{
Application.Exit();
}
// ========================= TABLE MANIPULATION ========================
/// <summary>
/// Handles table add
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAddTable_Click(object sender, System.EventArgs e)
{
string tblName=tableNameTextbox.Text;
if (!ValidateTableName(tblName))
{
return;
}
DataTable dt = new DataTable(tblName);
currentTable = dt;
tablesListbox.Items.Add(tblName);
dataSet.Tables.Add(dt);
tablesListbox.SelectedItem = tablesListbox.Items[tablesListbox.FindStringExact(tblName)];
}
/// <summary>
/// Handles table name change
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void changeTableNameButton_Click(object sender, System.EventArgs e)
{
string tableName = tableNameTextbox.Text;
if (!ValidateSelectedTable() || !ValidateTableName(tableNameTextbox.Text))
return;
int n = tablesListbox.Items.IndexOf(tablesListbox.SelectedItem);
string oldTableName = tablesListbox.Items[n].ToString();
dataSet.Tables[oldTableName].TableName = tableName;
tablesListbox.Items[n] = tableName;
dataDatagrid.SetDataBinding(dataSet, tableName);
}
/// <summary>
/// Removes tables name from the list
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void removeButtonTable_Click(object sender, System.EventArgs e)
{
if ( !ValidateSelectedTable())
{
return;
}
int n = tablesListbox.Items.IndexOf(tablesListbox.SelectedItem);
string tableName = tablesListbox.Items[n].ToString();
tablesListbox.Items.Remove(tablesListbox.SelectedItem);
DataTable dt = dataSet.Tables[tableName];
dt.Clear();
dt.Columns.Clear();
dataSet.Tables.Remove(tableName);
currentTable = null;
dataDatagrid.SetDataBinding(dataSet, null);
}
/// <summary>
/// Handles selection change in the table list
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tablesListBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
string tableName = tablesListbox.Text;
tableNameTextbox.Text = tableName;
currentTable=dataSet.Tables[tableName];
ShowColumns();
dataDatagrid.SetDataBinding(dataSet, tableName);
dataDatagrid.CaptionText = "Table: "+tableName;
mainTabControl.TabPages[1].Text = "Data: " + tableName;
}
// ========================= COLUMN MANIPULATION ========================
/// <summary>
/// Handles new column add to the table
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void addColumnButton_Click(object sender, System.EventArgs e)
{
string columnName = columnNameTextbox.Text;
string columnType = columnTypeCombobox.Text;
if ( (!ValidateColumnNameAndType(columnName, columnType)) || (!ValidateSelectedTable()) )
{
return;
}
ListViewItem listViewItem=columnsListbox.Items.Add(columnName);
listViewItem.SubItems.Add(columnType);
currentTable.Columns.Add(columnName, Type.GetType("System."+columnType));
}
/// <summary>
/// Handles name change for the column in a table
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void changeColumnButton_Click(object sender, System.EventArgs e)
{
ListViewItem listViewItem = columnsListbox.SelectedItems[0];
if (!ValidateSelectedColumn() ||
!ValidateColumnNameAndType(columnNameTextbox.Text, listViewItem.SubItems[1].Text))
{
return;
}
string prevColumnName = listViewItem.Text;
listViewItem.Text = columnNameTextbox.Text;
currentTable.Columns[prevColumnName].ColumnName = columnNameTextbox.Text;
if (dataSet.Tables[0].Rows.Count != 0 &&
listViewItem.SubItems[1].Text != columnTypeCombobox.Text)
{
if (DialogResult.OK == MessageBox.Show("Column type change will result in data from that column to be dropped. \n Do you want to go ahead?",
"Xml Store v1.0", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
{
// can't change the data type once data exists
listViewItem.SubItems[1].Text = columnTypeCombobox.Text;
int indexOf = currentTable.Columns.IndexOf(columnNameTextbox.Text);
currentTable.Columns.Remove(columnNameTextbox.Text);
DataColumn column = new DataColumn(listViewItem.SubItems[0].Text, Type.GetType("System." + columnTypeCombobox.Text));
currentTable.Columns.Add(column);
column.SetOrdinal(indexOf);
}
else
return;
}
}
/// <summary>
/// Removes column from the list and table
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void removeColumnButton_Click(object sender, System.EventArgs e)
{
if (!ValidateSelectedColumn())
{
return;
}
ListViewItem listViewItem = columnsListbox.SelectedItems[0];
columnsListbox.Items.Remove(listViewItem);
currentTable.Columns.Remove(listViewItem.Text);
}
// ========================= HELPERS ========================
/// <summary>
/// Validates table name
/// </summary>
/// <param name="tableName">Name of the table</param>
/// <returns></returns>
bool ValidateTableName(string tableName)
{
if (tableName == "")
{
MessageBox.Show("Please enter a name for the table.", "Missing Information");
return false;
}
int ret=tablesListbox.FindStringExact(tableName);
if (ret!=ListBox.NoMatches)
{
MessageBox.Show("This table is already defined.", "Duplicate Name");
return false;
}
return true;
}
/// <summary>
/// Validates selected table for errors
/// </summary>
/// <returns></returns>
bool ValidateSelectedTable()
{
if (tablesListbox.SelectedItem == null)
{
MessageBox.Show("Please select a table from the table list.", "No Selection");
return false;
}
return true;
}
/// <summary>
/// Validates column name and type
/// </summary>
/// <param name="columnName">Name of the column</param>
/// <param name="columnType">Name of the type</param>
/// <returns></returns>
bool ValidateColumnNameAndType(string columnName, string columnType)
{
if (columnName == "")
{
MessageBox.Show("Please enter a name for the column.", "Missing Information");
return false;
}
if (columnType == "")
{
MessageBox.Show("Please select a type for the column.", "Missing Information");
return false;
}
if (GetListViewItem(columnName)!=null)
{
MessageBox.Show("This column is already defined.", "Duplicate Name");
return false;
}
return true;
}
/// <summary>
/// Validates selected column for errors
/// </summary>
/// <returns></returns>
bool ValidateSelectedColumn()
{
if (columnsListbox.SelectedItems.Count == 0)
{
MessageBox.Show("Please select a column from the column list.", "No Selection");
return false;
}
return true;
}
/// <summary>
/// Gets list view item for given column name
/// </summary>
/// <param name="columnName"></param>
/// <returns></returns>
ListViewItem GetListViewItem(string columnName)
{
ListView.ListViewItemCollection lvItems=columnsListbox.Items;
foreach (ListViewItem listViewItem in lvItems)
{
if (listViewItem.Text == columnName)
{
return listViewItem;
}
}
return null;
}
/// <summary>
/// Shows all the columns for loaded store in the list
/// </summary>
void ShowColumns()
{
columnsListbox.Items.Clear();
if (currentTable != null)
{
foreach (DataColumn dc in currentTable.Columns)
{
ListViewItem listViewItem=columnsListbox.Items.Add(dc.ColumnName);
string s=dc.DataType.ToString();
s=s.Split(new Char[] {'.'})[1];
listViewItem.SubItems.Add(s);
}
}
if(this.columnsListbox.Items.Count > 0)
this.columnsListbox.Items[0].Selected = true;
}
/// <summary>
/// Saves data and schema to the file
/// </summary>
/// <param name="fileName">File name to which data and schema will be saved</param>
/// <param name="includeSchema">
/// True: Schema is saved in the file with data
/// False: Only data is saved to the file
/// </param>
void SaveXml(string fileName, bool includeSchema)
{
if (includeSchema)
{
dataSet.WriteXml(fileName, XmlWriteMode.WriteSchema);
MessageBox.Show("XML schema and data saved", "XML Store v1.0");
}
else
{
dataSet.WriteXml(fileName, XmlWriteMode.IgnoreSchema);
MessageBox.Show("XML data saved", "XML Store v1.0");
}
}
/// <summary>
/// Saves schema to the file
/// </summary>
/// <param name="fileName">File name where schema will be saved</param>
void SaveSchema(String fileName)
{
dataSet.WriteXmlSchema(fileName);
MessageBox.Show("XML Schema saved", "XML Store v1.0");
}
/// <summary>
/// Updates controls when column selection changes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void columnsListbox_SelectedIndexChanged(object sender, EventArgs e)
{
if (columnsListbox.SelectedItems.Count > 0)
{
ListViewItem listViewItem = columnsListbox.SelectedItems[0];
columnNameTextbox.Text = listViewItem.SubItems[0].Text;
columnTypeCombobox.Text = listViewItem.SubItems[1].Text;
}
}
/// <summary>
/// Validates XML document
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuXMLDocValidator_Click(object sender, EventArgs e)
{
MessageBox.Show("This feature is coming with next version of XML Store.", "XML Store v1.0",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
/// <summary>
/// Handles error and warning found in xml document validation
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void xmlDocValidatorEventHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
MessageBox.Show(String.Format("Error: {0}", e.Message), "XML validation error");
break;
case XmlSeverityType.Warning:
MessageBox.Show(String.Format("Warning {0}", e.Message), "XML validation warning");
break;
}
}
/// <summary>
/// Saves scehama for loaded XML to file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveSchemaMenuItem_Click(object sender, EventArgs e)
{
DialogResult res = saveFileDialog.ShowDialog(this);
if (res == DialogResult.OK)
{
fileNameSchema = saveFileDialog.FileName;
SaveSchema(fileNameSchema);
}
}
/// <summary>
/// Saves xml data to the file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveXMLDataMenuItem_Click(object sender, EventArgs e)
{
DialogResult res = saveFileDialog.ShowDialog(this);
if (res == DialogResult.OK)
{
fileNameSchema = saveFileDialog.FileName;
SaveXml(fileNameSchema, false);
}
}
private void xpathLocatorMenuItem_Click(object sender, EventArgs e)
{
openFileDialog.Title = "Select XML file to load...";
DialogResult dialogResult = openFileDialog.ShowDialog(this);
if (dialogResult == DialogResult.OK)
{
XPathForm xPathForm = new XPathForm(openFileDialog.FileName);
xPathForm.ShowDialog(this);
}
}
}
}
| |
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PoolOperations operations.
/// </summary>
public partial interface IPoolOperations
{
/// <summary>
/// Lists the usage metrics, aggregated by pool across individual time
/// intervals, for the specified account.
/// </summary>
/// <param name='poolListPoolUsageMetricsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<PoolUsageMetrics>,PoolListPoolUsageMetricsHeaders>> ListPoolUsageMetricsWithHttpMessagesAsync(PoolListPoolUsageMetricsOptions poolListPoolUsageMetricsOptions = default(PoolListPoolUsageMetricsOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets lifetime summary statistics for all of the pools in the
/// specified account.
/// </summary>
/// <remarks>
/// Statistics are aggregated across all pools that have ever existed
/// in the account, from account creation to the last update time of
/// the statistics.
/// </remarks>
/// <param name='poolGetAllPoolsLifetimeStatisticsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PoolStatistics,PoolGetAllPoolsLifetimeStatisticsHeaders>> GetAllPoolsLifetimeStatisticsWithHttpMessagesAsync(PoolGetAllPoolsLifetimeStatisticsOptions poolGetAllPoolsLifetimeStatisticsOptions = default(PoolGetAllPoolsLifetimeStatisticsOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Adds a pool to the specified account.
/// </summary>
/// <param name='pool'>
/// The pool to be added.
/// </param>
/// <param name='poolAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<PoolAddHeaders>> AddWithHttpMessagesAsync(PoolAddParameter pool, PoolAddOptions poolAddOptions = default(PoolAddOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the pools in the specified account.
/// </summary>
/// <param name='poolListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudPool>,PoolListHeaders>> ListWithHttpMessagesAsync(PoolListOptions poolListOptions = default(PoolListOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes a pool from the specified account.
/// </summary>
/// <param name='poolId'>
/// The id of the pool to delete.
/// </param>
/// <param name='poolDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<PoolDeleteHeaders>> DeleteWithHttpMessagesAsync(string poolId, PoolDeleteOptions poolDeleteOptions = default(PoolDeleteOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets basic properties of a pool.
/// </summary>
/// <param name='poolId'>
/// The id of the pool to get.
/// </param>
/// <param name='poolExistsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<bool,PoolExistsHeaders>> ExistsWithHttpMessagesAsync(string poolId, PoolExistsOptions poolExistsOptions = default(PoolExistsOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets information about the specified pool.
/// </summary>
/// <param name='poolId'>
/// The id of the pool to get.
/// </param>
/// <param name='poolGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CloudPool,PoolGetHeaders>> GetWithHttpMessagesAsync(string poolId, PoolGetOptions poolGetOptions = default(PoolGetOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates the properties of a pool.
/// </summary>
/// <param name='poolId'>
/// The id of the pool to update.
/// </param>
/// <param name='poolPatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolPatchOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<PoolPatchHeaders>> PatchWithHttpMessagesAsync(string poolId, PoolPatchParameter poolPatchParameter, PoolPatchOptions poolPatchOptions = default(PoolPatchOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Disables automatic scaling for a pool.
/// </summary>
/// <param name='poolId'>
/// The id of the pool on which to disable automatic scaling.
/// </param>
/// <param name='poolDisableAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<PoolDisableAutoScaleHeaders>> DisableAutoScaleWithHttpMessagesAsync(string poolId, PoolDisableAutoScaleOptions poolDisableAutoScaleOptions = default(PoolDisableAutoScaleOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Enables automatic scaling for a pool.
/// </summary>
/// <param name='poolId'>
/// The id of the pool on which to enable automatic scaling.
/// </param>
/// <param name='poolEnableAutoScaleParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolEnableAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<PoolEnableAutoScaleHeaders>> EnableAutoScaleWithHttpMessagesAsync(string poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions = default(PoolEnableAutoScaleOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the result of evaluating an automatic scaling formula on the
/// pool.
/// </summary>
/// <param name='poolId'>
/// The id of the pool on which to evaluate the automatic scaling
/// formula.
/// </param>
/// <param name='autoScaleFormula'>
/// A formula for the desired number of compute nodes in the pool.
/// </param>
/// <param name='poolEvaluateAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<AutoScaleRun,PoolEvaluateAutoScaleHeaders>> EvaluateAutoScaleWithHttpMessagesAsync(string poolId, string autoScaleFormula, PoolEvaluateAutoScaleOptions poolEvaluateAutoScaleOptions = default(PoolEvaluateAutoScaleOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Changes the number of compute nodes that are assigned to a pool.
/// </summary>
/// <param name='poolId'>
/// The id of the pool to resize.
/// </param>
/// <param name='poolResizeParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolResizeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<PoolResizeHeaders>> ResizeWithHttpMessagesAsync(string poolId, PoolResizeParameter poolResizeParameter, PoolResizeOptions poolResizeOptions = default(PoolResizeOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Stops an ongoing resize operation on the pool.
/// </summary>
/// <remarks>
/// This does not restore the pool to its previous state before the
/// resize operation: it only stops any further changes being made,
/// and the pool maintains its current state.
/// </remarks>
/// <param name='poolId'>
/// The id of the pool whose resizing you want to stop.
/// </param>
/// <param name='poolStopResizeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<PoolStopResizeHeaders>> StopResizeWithHttpMessagesAsync(string poolId, PoolStopResizeOptions poolStopResizeOptions = default(PoolStopResizeOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates the properties of a pool.
/// </summary>
/// <param name='poolId'>
/// The id of the pool to update.
/// </param>
/// <param name='poolUpdatePropertiesParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolUpdatePropertiesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<PoolUpdatePropertiesHeaders>> UpdatePropertiesWithHttpMessagesAsync(string poolId, PoolUpdatePropertiesParameter poolUpdatePropertiesParameter, PoolUpdatePropertiesOptions poolUpdatePropertiesOptions = default(PoolUpdatePropertiesOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Upgrades the operating system of the specified pool.
/// </summary>
/// <param name='poolId'>
/// The id of the pool to upgrade.
/// </param>
/// <param name='targetOSVersion'>
/// The Azure Guest OS version to be installed on the virtual machines
/// in the pool.
/// </param>
/// <param name='poolUpgradeOSOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<PoolUpgradeOSHeaders>> UpgradeOSWithHttpMessagesAsync(string poolId, string targetOSVersion, PoolUpgradeOSOptions poolUpgradeOSOptions = default(PoolUpgradeOSOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Removes compute nodes from the specified pool.
/// </summary>
/// <param name='poolId'>
/// The id of the pool from which you want to remove nodes.
/// </param>
/// <param name='nodeRemoveParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolRemoveNodesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<PoolRemoveNodesHeaders>> RemoveNodesWithHttpMessagesAsync(string poolId, NodeRemoveParameter nodeRemoveParameter, PoolRemoveNodesOptions poolRemoveNodesOptions = default(PoolRemoveNodesOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the usage metrics, aggregated by pool across individual time
/// intervals, for the specified account.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='poolListPoolUsageMetricsNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<PoolUsageMetrics>,PoolListPoolUsageMetricsHeaders>> ListPoolUsageMetricsNextWithHttpMessagesAsync(string nextPageLink, PoolListPoolUsageMetricsNextOptions poolListPoolUsageMetricsNextOptions = default(PoolListPoolUsageMetricsNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the pools in the specified account.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='poolListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudPool>,PoolListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, PoolListNextOptions poolListNextOptions = default(PoolListNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
// --------------------------------------------------------------------------------------------
#region // Copyright (c) 2020, SIL International. All Rights Reserved.
// <copyright from='2011' to='2020' company='SIL International'>
// Copyright (c) 2020, SIL International. All Rights Reserved.
//
// Distributable under the terms of the MIT License (https://sil.mit-license.org/)
// </copyright>
#endregion
// --------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using HearThis.Properties;
using HearThis.Publishing;
namespace HearThis.Script
{
public class Project : ISkippedStyleInfoProvider, IPublishingInfoProvider
{
public const string InfoTxtFileName = "info.txt";
private BookInfo _selectedBook;
private ChapterInfo _selectedChapterInfo;
public List<BookInfo> Books { get; }
private readonly ScriptProviderBase _scriptProvider;
private int _selectedScriptLine;
public event EventHandler SelectedBookChanged;
public event ScriptBlockChangedHandler ScriptBlockRecordingRestored;
public delegate void ScriptBlockChangedHandler(Project sender, int book, int chapter, ScriptLine scriptBlock);
public Project(ScriptProviderBase scriptProvider)
{
_scriptProvider = scriptProvider;
ProjectSettings = _scriptProvider.ProjectSettings;
VersificationInfo = _scriptProvider.VersificationInfo;
_scriptProvider.ScriptBlockUnskipped += OnScriptBlockUnskipped;
Name = _scriptProvider.ProjectFolderName;
Books = new List<BookInfo>(_scriptProvider.VersificationInfo.BookCount);
if (Settings.Default.Book < 0 || Settings.Default.Book >= BibleStatsBase.kCanonicalBookCount)
Settings.Default.Book = 0;
for (int bookNumber = 0; bookNumber < _scriptProvider.VersificationInfo.BookCount; ++bookNumber)
{
var bookInfo = new BookInfo(Name, bookNumber, _scriptProvider);
Books.Add(bookInfo);
if (bookNumber == Settings.Default.Book)
SelectedBook = bookInfo;
}
}
public ProjectSettings ProjectSettings { get; }
public BookInfo SelectedBook
{
get { return _selectedBook; }
set
{
if (_selectedBook != value)
{
_selectedBook = value;
_scriptProvider.LoadBook(_selectedBook.BookNumber);
GoToInitialChapter();
Settings.Default.Book = value.BookNumber;
SelectedBookChanged?.Invoke(this, new EventArgs());
}
}
}
internal void SaveProjectSettings()
{
_scriptProvider.SaveProjectSettings();
}
/// <summary>
/// Return the content of the info.txt file we create to help HearThisAndroid.
/// It contains a line for each book.
/// Each line contains BookName;blockcount:recordedCount,... for each chapter
/// (Not filtered by character.)
/// </summary>
/// <returns></returns>
internal string GetProjectRecordingStatusInfoFileContent()
{
var sb = new StringBuilder();
for (int ibook = 0; ibook < Books.Count; ibook++)
{
var book = Books[ibook];
var bookName = book.Name;
sb.Append(bookName);
sb.Append(";");
//sb.Append(book.ChapterCount);
//sb.Append(";");
//sb.Append(book.HasVerses ? "y" : "n");
//sb.Append(";");
if (!book.HasVerses)
{
sb.AppendLine("");
continue;
}
for (int ichap = 0; ichap <= _scriptProvider.VersificationInfo.GetChaptersInBook(ibook); ichap++)
{
var chap = book.GetChapter(ichap);
var lines = chap.GetUnfilteredScriptBlockCount();
if (ichap != 0)
sb.Append(',');
sb.Append(lines);
sb.Append(":");
sb.Append(chap.CalculateUnfilteredPercentageTranslated());
//for (int iline = 0; iline < lines; iline++)
// _lineRecordingRepository.WriteLineText(projectName, bookName, ichap, iline,
// chap.GetScriptLine(iline).Text);
}
sb.AppendLine("");
}
return sb.ToString();
}
/// <summary>
/// Where we will store the info.txt file we create to help HearThisAndroid
/// </summary>
/// <returns></returns>
public string GetProjectRecordingStatusInfoFilePath()
{
return Path.Combine(Program.GetApplicationDataFolder(Name), InfoTxtFileName);
}
public bool IsRealProject
{
get { return !(_scriptProvider is SampleScriptProvider); }
}
public string EthnologueCode
{
get { return _scriptProvider.EthnologueCode; }
}
public bool RightToLeft
{
get { return _scriptProvider.RightToLeft; }
}
public string FontName
{
get { return _scriptProvider.FontName; }
}
public string CurrentBookName => _selectedBook.Name;
public bool IncludeBook(string bookName)
{
int bookIndex = _scriptProvider.VersificationInfo.GetBookNumber(bookName);
if (bookIndex < 0)
return false;
for (int iChapter = 0; iChapter < _scriptProvider.VersificationInfo.GetChaptersInBook(bookIndex); iChapter++)
{
if (_scriptProvider.GetUnfilteredTranslatedVerseCount(bookIndex, iChapter) > 0)
return true;
}
return false;
}
public ScriptLine GetUnfilteredBlock(string bookName, int chapterNumber, int lineNumber0Based)
{
return _scriptProvider.GetUnfilteredBlock(_scriptProvider.VersificationInfo.GetBookNumber(bookName), chapterNumber, lineNumber0Based);
}
public IBibleStats VersificationInfo { get; private set; }
public int BookNameComparer(string x, string y)
{
return Comparer.Default.Compare(_scriptProvider.VersificationInfo.GetBookNumber(x),
_scriptProvider.VersificationInfo.GetBookNumber(y));
}
public bool BreakQuotesIntoBlocks => ProjectSettings.BreakQuotesIntoBlocks;
/// <summary>
/// Note that this is NOT the same as ProjectSettings.AdditionalBlockBreakCharacters.
/// This property is implemented especially to support publishing and may include
/// additional characters not stored in the project setting by the same name.
/// </summary>
string IPublishingInfoProvider.AdditionalBlockBreakCharacters
{
get
{
var bldr = new StringBuilder(ProjectSettings.AdditionalBlockBreakCharacters);
var firstLevelStartQuotationMark = ScrProjectSettings?.FirstLevelStartQuotationMark;
if (BreakQuotesIntoBlocks && !String.IsNullOrEmpty(firstLevelStartQuotationMark))
{
if (bldr.Length > 0)
bldr.Append(" ");
bldr.Append(firstLevelStartQuotationMark);
var firstLevelEndQuotationMark = ScrProjectSettings.FirstLevelEndQuotationMark;
if (firstLevelStartQuotationMark != firstLevelEndQuotationMark)
bldr.Append(" ").Append(firstLevelEndQuotationMark);
}
return bldr.ToString();
}
}
public void GoToInitialChapter()
{
if (_selectedChapterInfo == null &&
Settings.Default.Chapter >= SelectedBook.FirstChapterNumber && Settings.Default.Chapter <= SelectedBook.ChapterCount)
{
// This is the very first time for this project. In this case rather than going to the start of the book,
// we want to go back to the chapter the user was in when they left off last time.
SelectedChapterInfo = SelectedBook.GetChapter(Settings.Default.Chapter);
}
else
{
SelectedChapterInfo = _selectedBook.GetFirstChapter();
}
}
public ChapterInfo SelectedChapterInfo
{
get { return _selectedChapterInfo; }
set
{
if (_selectedChapterInfo != value)
{
_selectedChapterInfo = value;
Settings.Default.Chapter = value.ChapterNumber1Based;
SelectedScriptBlock = 0;
}
}
}
/// <summary>
/// This is a portion of the Scripture text that is to be recorded as a single clip. Blocks are broken up by paragraph breaks and
/// sentence-final punctuation, not verses. This is a 0-based index.
/// Project.SelectedScriptBlock is unfiltered (that is, an index into all the blocks in the chapter, not into
/// the current-character list).
/// </summary>
public int SelectedScriptBlock
{
get { return _selectedScriptLine; }
set
{
_selectedScriptLine = value;
SendFocus();
}
}
private void SendFocus()
{
if (SelectedBook == null || SelectedBook.BookNumber >= _scriptProvider.VersificationInfo.BookCount
|| SelectedChapterInfo == null || SelectedScriptBlock >= SelectedChapterInfo.GetUnfilteredScriptBlockCount())
return;
var abbr = _scriptProvider.VersificationInfo.GetBookCode(SelectedBook.BookNumber);
var block = SelectedBook.GetUnfilteredBlock(SelectedChapterInfo.ChapterNumber1Based, SelectedScriptBlock);
var verse = block.Verse ?? "";
int i = verse.IndexOfAny(new[] {'-', '~'});
if (i > 0)
verse = verse.Substring(0, i);
var targetRef = string.Format("{0} {1}:{2}", abbr, SelectedChapterInfo.ChapterNumber1Based, verse);
ParatextFocusHandler.SendFocusMessage(targetRef);
}
public string Name { get; }
public IScrProjectSettings ScrProjectSettings
{
get
{
var paratextScriptProvider = _scriptProvider as IScrProjectSettingsProvider;
return paratextScriptProvider?.ScrProjectSettings;
}
}
public bool HasNestedQuotes
{
get { return _scriptProvider.NestedQuotesEncountered; }
}
public bool HaveSelectedScript
{
get { return SelectedScriptBlock >= 0; }
}
public IEnumerable<string> AllEncounteredParagraphStyleNames
{
get { return _scriptProvider.AllEncounteredParagraphStyleNames; }
}
public IActorCharacterProvider ActorCharacterProvider => _scriptProvider as IActorCharacterProvider;
public string CurrentCharacter => ActorCharacterProvider?.Character;
// Unfiltered by character
public int GetLineCountForChapter(bool includeSkipped)
{
if (includeSkipped)
return _scriptProvider.GetUnfilteredScriptBlockCount(_selectedBook.BookNumber, _selectedChapterInfo.ChapterNumber1Based);
return _scriptProvider.GetUnskippedScriptBlockCount(_selectedBook.BookNumber,
_selectedChapterInfo.ChapterNumber1Based);
}
public void LoadBook(int bookNumber0Based)
{
_scriptProvider.LoadBook(bookNumber0Based);
}
internal ChapterInfo GetNextChapterInfo()
{
var currentChapNum = SelectedChapterInfo.ChapterNumber1Based;
if (currentChapNum == SelectedBook.ChapterCount)
throw new ArgumentOutOfRangeException("Tried to get too high a chapter number.");
return SelectedBook.GetChapter(currentChapNum + 1);
}
internal int GetNextChapterNum()
{
return GetNextChapterInfo().ChapterNumber1Based;
}
internal string GetPathToRecordingForSelectedLine()
{
return ClipRepository.GetPathToLineRecordingUnfiltered(Name, SelectedBook.Name,
SelectedChapterInfo.ChapterNumber1Based, SelectedScriptBlock);
}
internal string ProjectFolder => ClipRepository.GetProjectFolder(Name);
public void SetSkippedStyle(string style, bool skipped)
{
_scriptProvider.SetSkippedStyle(style, skipped);
}
public bool IsSkippedStyle(string style) => _scriptProvider.IsSkippedStyle(style);
public IReadOnlyList<string> StylesToSkipByDefault => _scriptProvider.StylesToSkipByDefault;
public void ClearAllSkippedBlocks()
{
_scriptProvider.ClearAllSkippedBlocks(Books);
}
public IScriptProvider ScriptProvider => _scriptProvider;
private void OnScriptBlockUnskipped(IScriptProvider sender, int bookNumber, int chapterNumber, ScriptLine scriptBlock)
{
// passing an unfiltered scriptBlockNumber, so do NOT pass a script provider so it won't be adjusted
if (ClipRepository.RestoreBackedUpClip(Name, Books[bookNumber].Name, chapterNumber, scriptBlock.Number - 1))
ScriptBlockRecordingRestored?.Invoke(this, bookNumber, chapterNumber, scriptBlock);
}
/// <summary>
/// Strictly speaking, skipped lines are not recordable, but we leave the button semi-enabled (grayed out
/// and doesn't actually allow recording, but it does give the user a message if clicked),
/// so we want to treat them as "recordable" if skipping is the only thing standing in the way.
/// Similarly, if we're in overview mode, nothing can currently be recorded, but we want to show things that could be
/// if we were in the right character as recordable.
/// </summary>
/// <param name="book"></param>
/// <param name="chapterNumber1Based"></param>
/// <param name="lineNo0Based"></param>
/// <returns></returns>
public bool IsLineCurrentlyRecordable(int book, int chapterNumber1Based, int lineNo0Based)
{
var line = _scriptProvider.GetUnfilteredBlock(book, chapterNumber1Based, lineNo0Based);
if (string.IsNullOrEmpty(line?.Text))
return false;
if (ActorCharacterProvider == null || ActorCharacterProvider.Character == null)
return true; // no filtering (or overview mode).
return line.Character == ActorCharacterProvider.Character && line.Actor == ActorCharacterProvider.Actor;
}
}
}
| |
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using NUnit.Framework;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using OpenMode_e = Lucene.Net.Index.IndexWriterConfig.OpenMode_e;
[TestFixture]
public class TestIndexWriterMergePolicy : LuceneTestCase
{
// Test the normal case
[Test]
public virtual void TestNormalCase()
{
Directory dir = NewDirectory();
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(10).SetMergePolicy(new LogDocMergePolicy()));
for (int i = 0; i < 100; i++)
{
AddDoc(writer);
CheckInvariants(writer);
}
writer.Dispose();
dir.Dispose();
}
// Test to see if there is over merge
[Test]
public virtual void TestNoOverMerge()
{
Directory dir = NewDirectory();
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(10).SetMergePolicy(new LogDocMergePolicy()));
bool noOverMerge = false;
for (int i = 0; i < 100; i++)
{
AddDoc(writer);
CheckInvariants(writer);
if (writer.NumBufferedDocuments + writer.SegmentCount >= 18)
{
noOverMerge = true;
}
}
Assert.IsTrue(noOverMerge);
writer.Dispose();
dir.Dispose();
}
// Test the case where flush is forced after every addDoc
[Test]
public virtual void TestForceFlush()
{
Directory dir = NewDirectory();
LogDocMergePolicy mp = new LogDocMergePolicy();
mp.MinMergeDocs = 100;
mp.MergeFactor = 10;
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(10).SetMergePolicy(mp));
for (int i = 0; i < 100; i++)
{
AddDoc(writer);
writer.Dispose();
mp = new LogDocMergePolicy();
mp.MergeFactor = 10;
writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.APPEND).SetMaxBufferedDocs(10).SetMergePolicy(mp));
mp.MinMergeDocs = 100;
CheckInvariants(writer);
}
writer.Dispose();
dir.Dispose();
}
// Test the case where mergeFactor changes
[Test]
public virtual void TestMergeFactorChange()
{
Directory dir = NewDirectory();
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(10).SetMergePolicy(NewLogMergePolicy()).SetMergeScheduler(new SerialMergeScheduler()));
for (int i = 0; i < 250; i++)
{
AddDoc(writer);
CheckInvariants(writer);
}
((LogMergePolicy)writer.Config.MergePolicy).MergeFactor = 5;
// merge policy only fixes segments on levels where merges
// have been triggered, so check invariants after all adds
for (int i = 0; i < 10; i++)
{
AddDoc(writer);
}
CheckInvariants(writer);
writer.Dispose();
dir.Dispose();
}
// Test the case where both mergeFactor and maxBufferedDocs change
[Test]
public virtual void TestMaxBufferedDocsChange()
{
Directory dir = NewDirectory();
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(101).SetMergePolicy(new LogDocMergePolicy()).SetMergeScheduler(new SerialMergeScheduler()));
// leftmost* segment has 1 doc
// rightmost* segment has 100 docs
for (int i = 1; i <= 100; i++)
{
for (int j = 0; j < i; j++)
{
AddDoc(writer);
CheckInvariants(writer);
}
writer.Dispose();
writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.APPEND).SetMaxBufferedDocs(101).SetMergePolicy(new LogDocMergePolicy()).SetMergeScheduler(new SerialMergeScheduler()));
}
writer.Dispose();
LogDocMergePolicy ldmp = new LogDocMergePolicy();
ldmp.MergeFactor = 10;
writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.APPEND).SetMaxBufferedDocs(10).SetMergePolicy(ldmp).SetMergeScheduler(new SerialMergeScheduler()));
// merge policy only fixes segments on levels where merges
// have been triggered, so check invariants after all adds
for (int i = 0; i < 100; i++)
{
AddDoc(writer);
}
CheckInvariants(writer);
for (int i = 100; i < 1000; i++)
{
AddDoc(writer);
}
writer.Commit();
writer.WaitForMerges();
writer.Commit();
CheckInvariants(writer);
writer.Dispose();
dir.Dispose();
}
// Test the case where a merge results in no doc at all
[Test]
public virtual void TestMergeDocCount0([ValueSource(typeof(ConcurrentMergeSchedulers), "Values")]IConcurrentMergeScheduler scheduler)
{
Directory dir = NewDirectory();
LogDocMergePolicy ldmp = new LogDocMergePolicy();
ldmp.MergeFactor = 100;
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(10).SetMergePolicy(ldmp));
for (int i = 0; i < 250; i++)
{
AddDoc(writer);
CheckInvariants(writer);
}
writer.Dispose();
// delete some docs without merging
writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES));
writer.DeleteDocuments(new Term("content", "aaa"));
writer.Dispose();
ldmp = new LogDocMergePolicy();
ldmp.MergeFactor = 5;
var config = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))
.SetOpenMode(OpenMode_e.APPEND)
.SetMaxBufferedDocs(10)
.SetMergePolicy(ldmp)
.SetMergeScheduler(scheduler);
writer = new IndexWriter(dir, config);
// merge factor is changed, so check invariants after all adds
for (int i = 0; i < 10; i++)
{
AddDoc(writer);
}
writer.Commit();
writer.WaitForMerges();
writer.Commit();
CheckInvariants(writer);
Assert.AreEqual(10, writer.MaxDoc);
writer.Dispose();
dir.Dispose();
}
private void AddDoc(IndexWriter writer)
{
Document doc = new Document();
doc.Add(NewTextField("content", "aaa", Field.Store.NO));
writer.AddDocument(doc);
}
private void CheckInvariants(IndexWriter writer)
{
writer.WaitForMerges();
int maxBufferedDocs = writer.Config.MaxBufferedDocs;
int mergeFactor = ((LogMergePolicy)writer.Config.MergePolicy).MergeFactor;
int maxMergeDocs = ((LogMergePolicy)writer.Config.MergePolicy).MaxMergeDocs;
int ramSegmentCount = writer.NumBufferedDocuments;
Assert.IsTrue(ramSegmentCount < maxBufferedDocs);
int lowerBound = -1;
int upperBound = maxBufferedDocs;
int numSegments = 0;
int segmentCount = writer.SegmentCount;
for (int i = segmentCount - 1; i >= 0; i--)
{
int docCount = writer.GetDocCount(i);
Assert.IsTrue(docCount > lowerBound, "docCount=" + docCount + " lowerBound=" + lowerBound + " upperBound=" + upperBound + " i=" + i + " segmentCount=" + segmentCount + " index=" + writer.SegString() + " config=" + writer.Config);
if (docCount <= upperBound)
{
numSegments++;
}
else
{
if (upperBound * mergeFactor <= maxMergeDocs)
{
Assert.IsTrue(numSegments < mergeFactor, "maxMergeDocs=" + maxMergeDocs + "; numSegments=" + numSegments + "; upperBound=" + upperBound + "; mergeFactor=" + mergeFactor + "; segs=" + writer.SegString() + " config=" + writer.Config);
}
do
{
lowerBound = upperBound;
upperBound *= mergeFactor;
} while (docCount > upperBound);
numSegments = 1;
}
}
if (upperBound * mergeFactor <= maxMergeDocs)
{
Assert.IsTrue(numSegments < mergeFactor);
}
}
private const double EPSILON = 1E-14;
[Test]
public virtual void TestSetters()
{
AssertSetters(new LogByteSizeMergePolicy());
AssertSetters(new LogDocMergePolicy());
}
private void AssertSetters(MergePolicy lmp)
{
lmp.MaxCFSSegmentSizeMB = 2.0;
Assert.AreEqual(2.0, lmp.MaxCFSSegmentSizeMB, EPSILON);
lmp.MaxCFSSegmentSizeMB = double.PositiveInfinity;
Assert.AreEqual(long.MaxValue / 1024 / 1024.0, lmp.MaxCFSSegmentSizeMB, EPSILON * long.MaxValue);
lmp.MaxCFSSegmentSizeMB = long.MaxValue / 1024 / 1024.0;
Assert.AreEqual(long.MaxValue / 1024 / 1024.0, lmp.MaxCFSSegmentSizeMB, EPSILON * long.MaxValue);
try
{
lmp.MaxCFSSegmentSizeMB = -2.0;
Assert.Fail("Didn't throw IllegalArgumentException");
}
catch (System.ArgumentException iae)
{
// pass
}
// TODO: Add more checks for other non-double setters!
}
}
}
| |
// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace Microsoft.Xbox.Services.Privacy
{
using global::AOT;
using global::Microsoft.Xbox.Services.System;
using global::System;
using global::System.Collections.Generic;
using global::System.Runtime.InteropServices;
using global::System.Threading.Tasks;
public class PrivacyService : IPrivacyService
{
internal IntPtr pCXboxLiveContext;
internal PrivacyService(IntPtr pCXboxLiveContext)
{
this.pCXboxLiveContext = pCXboxLiveContext;
}
public Task<IList<string>> GetAvoidListAsync()
{
var tcs = new TaskCompletionSource<IList<string>>();
Task.Run(() =>
{
int contextKey = XsapiCallbackContext<object, IList<string>>.CreateContext(null, tcs);
var xsapiResult = PrivacyGetAvoidList(this.pCXboxLiveContext, GetPrivacyUserListComplete, (IntPtr)contextKey, XboxLive.DefaultTaskGroupId);
if (xsapiResult != XSAPI_RESULT.XSAPI_RESULT_OK)
{
tcs.SetException(new XboxException(xsapiResult));
}
});
return tcs.Task;
}
public Task<IList<string>> GetMuteListAsync()
{
var tcs = new TaskCompletionSource<IList<string>>();
Task.Run(() =>
{
int contextKey = XsapiCallbackContext<object, IList<string>>.CreateContext(null, tcs);
var xsapiResult = PrivacyGetMuteList(this.pCXboxLiveContext, GetPrivacyUserListComplete, (IntPtr)contextKey, XboxLive.DefaultTaskGroupId);
if (xsapiResult != XSAPI_RESULT.XSAPI_RESULT_OK)
{
tcs.SetException(new XboxException(xsapiResult));
}
});
return tcs.Task;
}
[MonoPInvokeCallback(typeof(XSAPI_PRIVACY_GET_USER_LIST_COMPLETION_ROUTINE))]
private void GetPrivacyUserListComplete(XSAPI_RESULT_INFO result, IntPtr xboxUserIdList, UInt32 count, IntPtr contextKey)
{
XsapiCallbackContext<object, IList<string>> context;
if (XsapiCallbackContext<object, IList<string>>.TryRemove(contextKey.ToInt32(), out context))
{
if (result.errorCode == XSAPI_RESULT.XSAPI_RESULT_OK)
{
context.TaskCompletionSource.SetResult(MarshalingHelpers.Utf8StringArrayToStringList(xboxUserIdList, count));
}
else
{
context.TaskCompletionSource.SetException(new XboxException(result));
}
context.Dispose();
}
}
public Task<PermissionCheckResult> CheckPermissionWithTargetUserAsync(string permissionId, string targetXboxUserId)
{
var tcs = new TaskCompletionSource<PermissionCheckResult>();
Task.Run(() =>
{
var permissionIdPtr = MarshalingHelpers.StringToHGlobalUtf8(permissionId);
var xuidPtr = MarshalingHelpers.StringToHGlobalUtf8(targetXboxUserId);
int contextKey;
var context = XsapiCallbackContext<object, PermissionCheckResult>.CreateContext(null, tcs, out contextKey);
context.PointersToFree = new List<IntPtr> { permissionIdPtr, xuidPtr };
var xsapiResult = PrivacyCheckPermissionWithTargetUser(
this.pCXboxLiveContext, permissionIdPtr, xuidPtr, CheckPermissionWithTargetUserComplete,
(IntPtr)contextKey, XboxLive.DefaultTaskGroupId);
if (xsapiResult != XSAPI_RESULT.XSAPI_RESULT_OK)
{
tcs.SetException(new XboxException(xsapiResult));
}
});
return tcs.Task;
}
[MonoPInvokeCallback(typeof(XSAPI_PRIVACY_CHECK_PERMISSION_WITH_TARGET_USER_COMPLETION_ROUTINE))]
private void CheckPermissionWithTargetUserComplete(XSAPI_RESULT_INFO result, XSAPI_PRIVACY_PERMISSION_CHECK_RESULT payload, IntPtr contextKey)
{
XsapiCallbackContext<object, PermissionCheckResult> context;
if (XsapiCallbackContext<object, PermissionCheckResult>.TryRemove(contextKey.ToInt32(), out context))
{
if (result.errorCode == XSAPI_RESULT.XSAPI_RESULT_OK)
{
context.TaskCompletionSource.SetResult(new PermissionCheckResult(payload));
}
else
{
context.TaskCompletionSource.SetException(new XboxException(result));
}
context.Dispose();
}
}
public Task<IList<MultiplePermissionsCheckResult>> CheckMultiplePermissionsWithMultipleTargetUsersAsync(IList<string> permissionIds, IList<string> targetXboxUserIds)
{
var tcs = new TaskCompletionSource<IList<MultiplePermissionsCheckResult>>();
Task.Run(() =>
{
var permissionIdsArray = MarshalingHelpers.StringListToHGlobalUtf8StringArray(permissionIds);
var xuidsArray = MarshalingHelpers.StringListToHGlobalUtf8StringArray(targetXboxUserIds);
int contextKey = XsapiCallbackContext<CheckMultiplePermissionsContext, IList<MultiplePermissionsCheckResult>>.CreateContext(
new CheckMultiplePermissionsContext
{
permissionIdsArray = permissionIdsArray,
permissionIdsLength = permissionIds.Count,
targetXboxUserIdsArray = xuidsArray,
targetXboxUserIdsLength = targetXboxUserIds.Count
}, tcs);
var xsapiResult = PrivacyCheckMultiplePermissionsWithMultipleTargetUsers(
this.pCXboxLiveContext, permissionIdsArray, (UInt32)permissionIds.Count, xuidsArray, (UInt32)targetXboxUserIds.Count,
CheckMultiplePermissionsWithMultipleTargetUsersComplete, (IntPtr)contextKey, XboxLive.DefaultTaskGroupId);
if (xsapiResult != XSAPI_RESULT.XSAPI_RESULT_OK)
{
tcs.SetException(new XboxException(xsapiResult));
}
});
return tcs.Task;
}
[MonoPInvokeCallback(typeof(XSAPI_PRIVACY_CHECK_PERMISSION_WITH_MULTIPLE_TARGET_USERS_COMPLETION_ROUTINE))]
private void CheckMultiplePermissionsWithMultipleTargetUsersComplete(XSAPI_RESULT_INFO result, IntPtr resultsPtr, UInt32 privacyCheckResultCount, IntPtr contextKey)
{
XsapiCallbackContext<CheckMultiplePermissionsContext, IList<MultiplePermissionsCheckResult>> context;
if (XsapiCallbackContext<CheckMultiplePermissionsContext, IList<MultiplePermissionsCheckResult>>.TryRemove(contextKey.ToInt32(), out context))
{
if (result.errorCode == XSAPI_RESULT.XSAPI_RESULT_OK)
{
var results = new List<MultiplePermissionsCheckResult>();
var structSize = MarshalingHelpers.SizeOf<XSAPI_PRIVACY_MULTIPLE_PERMISSIONS_CHECK_RESULT>();
for (UInt64 i = 0; i < privacyCheckResultCount; ++i)
{
results.Add(new MultiplePermissionsCheckResult(resultsPtr));
resultsPtr = resultsPtr.Increment(structSize);
}
context.TaskCompletionSource.SetResult(results.AsReadOnly());
}
else
{
context.TaskCompletionSource.SetException(new XboxException(result));
}
MarshalingHelpers.FreeHGlobalUtf8StringArray(context.Context.permissionIdsArray, context.Context.permissionIdsLength);
MarshalingHelpers.FreeHGlobalUtf8StringArray(context.Context.targetXboxUserIdsArray, context.Context.targetXboxUserIdsLength);
context.Dispose();
}
}
internal class CheckMultiplePermissionsContext
{
public IntPtr permissionIdsArray;
public int permissionIdsLength;
public IntPtr targetXboxUserIdsArray;
public int targetXboxUserIdsLength;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void XSAPI_PRIVACY_GET_USER_LIST_COMPLETION_ROUTINE(
XSAPI_RESULT_INFO result,
IntPtr xboxUserIds,
UInt32 xboxUserIdsCount,
IntPtr context);
[DllImport(XboxLive.FlatCDllName, CallingConvention = CallingConvention.Cdecl)]
private static extern XSAPI_RESULT PrivacyGetAvoidList(
IntPtr xboxLiveContext,
XSAPI_PRIVACY_GET_USER_LIST_COMPLETION_ROUTINE completionRoutine,
IntPtr completionRoutineContext,
Int64 taskGroupId);
[DllImport(XboxLive.FlatCDllName, CallingConvention = CallingConvention.Cdecl)]
private static extern XSAPI_RESULT PrivacyGetMuteList(
IntPtr xboxLiveContext,
XSAPI_PRIVACY_GET_USER_LIST_COMPLETION_ROUTINE completionRoutine,
IntPtr completionRoutineContext,
Int64 taskGroupId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void XSAPI_PRIVACY_CHECK_PERMISSION_WITH_TARGET_USER_COMPLETION_ROUTINE(
XSAPI_RESULT_INFO result,
XSAPI_PRIVACY_PERMISSION_CHECK_RESULT payload,
IntPtr context);
[DllImport(XboxLive.FlatCDllName, CallingConvention = CallingConvention.Cdecl)]
private static extern XSAPI_RESULT PrivacyCheckPermissionWithTargetUser(
IntPtr xboxLiveContext,
IntPtr permissionId,
IntPtr xboxUserId,
XSAPI_PRIVACY_CHECK_PERMISSION_WITH_TARGET_USER_COMPLETION_ROUTINE completionRoutine,
IntPtr completionRoutineContext,
Int64 taskGroupId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void XSAPI_PRIVACY_CHECK_PERMISSION_WITH_MULTIPLE_TARGET_USERS_COMPLETION_ROUTINE(
XSAPI_RESULT_INFO result,
IntPtr privacyCheckResults,
UInt32 privacyCheckResultsCount,
IntPtr context);
[DllImport(XboxLive.FlatCDllName, CallingConvention = CallingConvention.Cdecl)]
private static extern XSAPI_RESULT PrivacyCheckMultiplePermissionsWithMultipleTargetUsers(
IntPtr xboxLiveContext,
IntPtr permissionIds,
UInt32 permissionIdsCount,
IntPtr xboxUserIds,
UInt32 xboxUserIdsCount,
XSAPI_PRIVACY_CHECK_PERMISSION_WITH_MULTIPLE_TARGET_USERS_COMPLETION_ROUTINE completionRoutine,
IntPtr completionRoutineContext,
Int64 taskGroupId);
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/group_service.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Monitoring.V3 {
/// <summary>Holder for reflection information generated from google/monitoring/v3/group_service.proto</summary>
public static partial class GroupServiceReflection {
#region Descriptor
/// <summary>File descriptor for google/monitoring/v3/group_service.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static GroupServiceReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cihnb29nbGUvbW9uaXRvcmluZy92My9ncm91cF9zZXJ2aWNlLnByb3RvEhRn",
"b29nbGUubW9uaXRvcmluZy52MxocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5w",
"cm90bxojZ29vZ2xlL2FwaS9tb25pdG9yZWRfcmVzb3VyY2UucHJvdG8aIWdv",
"b2dsZS9tb25pdG9yaW5nL3YzL2NvbW1vbi5wcm90bxogZ29vZ2xlL21vbml0",
"b3JpbmcvdjMvZ3JvdXAucHJvdG8aG2dvb2dsZS9wcm90b2J1Zi9lbXB0eS5w",
"cm90byKtAQoRTGlzdEdyb3Vwc1JlcXVlc3QSDAoEbmFtZRgHIAEoCRIbChFj",
"aGlsZHJlbl9vZl9ncm91cBgCIAEoCUgAEhwKEmFuY2VzdG9yc19vZl9ncm91",
"cBgDIAEoCUgAEh4KFGRlc2NlbmRhbnRzX29mX2dyb3VwGAQgASgJSAASEQoJ",
"cGFnZV9zaXplGAUgASgFEhIKCnBhZ2VfdG9rZW4YBiABKAlCCAoGZmlsdGVy",
"IlkKEkxpc3RHcm91cHNSZXNwb25zZRIqCgVncm91cBgBIAMoCzIbLmdvb2ds",
"ZS5tb25pdG9yaW5nLnYzLkdyb3VwEhcKD25leHRfcGFnZV90b2tlbhgCIAEo",
"CSIfCg9HZXRHcm91cFJlcXVlc3QSDAoEbmFtZRgDIAEoCSJlChJDcmVhdGVH",
"cm91cFJlcXVlc3QSDAoEbmFtZRgEIAEoCRIqCgVncm91cBgCIAEoCzIbLmdv",
"b2dsZS5tb25pdG9yaW5nLnYzLkdyb3VwEhUKDXZhbGlkYXRlX29ubHkYAyAB",
"KAgiVwoSVXBkYXRlR3JvdXBSZXF1ZXN0EioKBWdyb3VwGAIgASgLMhsuZ29v",
"Z2xlLm1vbml0b3JpbmcudjMuR3JvdXASFQoNdmFsaWRhdGVfb25seRgDIAEo",
"CCIiChJEZWxldGVHcm91cFJlcXVlc3QSDAoEbmFtZRgDIAEoCSKUAQoXTGlz",
"dEdyb3VwTWVtYmVyc1JlcXVlc3QSDAoEbmFtZRgHIAEoCRIRCglwYWdlX3Np",
"emUYAyABKAUSEgoKcGFnZV90b2tlbhgEIAEoCRIOCgZmaWx0ZXIYBSABKAkS",
"NAoIaW50ZXJ2YWwYBiABKAsyIi5nb29nbGUubW9uaXRvcmluZy52My5UaW1l",
"SW50ZXJ2YWwidwoYTGlzdEdyb3VwTWVtYmVyc1Jlc3BvbnNlEi4KB21lbWJl",
"cnMYASADKAsyHS5nb29nbGUuYXBpLk1vbml0b3JlZFJlc291cmNlEhcKD25l",
"eHRfcGFnZV90b2tlbhgCIAEoCRISCgp0b3RhbF9zaXplGAMgASgFMrsGCgxH",
"cm91cFNlcnZpY2UShQEKCkxpc3RHcm91cHMSJy5nb29nbGUubW9uaXRvcmlu",
"Zy52My5MaXN0R3JvdXBzUmVxdWVzdBooLmdvb2dsZS5tb25pdG9yaW5nLnYz",
"Lkxpc3RHcm91cHNSZXNwb25zZSIkgtPkkwIeEhwvdjMve25hbWU9cHJvamVj",
"dHMvKn0vZ3JvdXBzEnYKCEdldEdyb3VwEiUuZ29vZ2xlLm1vbml0b3Jpbmcu",
"djMuR2V0R3JvdXBSZXF1ZXN0GhsuZ29vZ2xlLm1vbml0b3JpbmcudjMuR3Jv",
"dXAiJoLT5JMCIBIeL3YzL3tuYW1lPXByb2plY3RzLyovZ3JvdXBzLyp9EoEB",
"CgtDcmVhdGVHcm91cBIoLmdvb2dsZS5tb25pdG9yaW5nLnYzLkNyZWF0ZUdy",
"b3VwUmVxdWVzdBobLmdvb2dsZS5tb25pdG9yaW5nLnYzLkdyb3VwIiuC0+ST",
"AiUiHC92My97bmFtZT1wcm9qZWN0cy8qfS9ncm91cHM6BWdyb3VwEokBCgtV",
"cGRhdGVHcm91cBIoLmdvb2dsZS5tb25pdG9yaW5nLnYzLlVwZGF0ZUdyb3Vw",
"UmVxdWVzdBobLmdvb2dsZS5tb25pdG9yaW5nLnYzLkdyb3VwIjOC0+STAi0a",
"JC92My97Z3JvdXAubmFtZT1wcm9qZWN0cy8qL2dyb3Vwcy8qfToFZ3JvdXAS",
"dwoLRGVsZXRlR3JvdXASKC5nb29nbGUubW9uaXRvcmluZy52My5EZWxldGVH",
"cm91cFJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiJoLT5JMCICoe",
"L3YzL3tuYW1lPXByb2plY3RzLyovZ3JvdXBzLyp9EqEBChBMaXN0R3JvdXBN",
"ZW1iZXJzEi0uZ29vZ2xlLm1vbml0b3JpbmcudjMuTGlzdEdyb3VwTWVtYmVy",
"c1JlcXVlc3QaLi5nb29nbGUubW9uaXRvcmluZy52My5MaXN0R3JvdXBNZW1i",
"ZXJzUmVzcG9uc2UiLoLT5JMCKBImL3YzL3tuYW1lPXByb2plY3RzLyovZ3Jv",
"dXBzLyp9L21lbWJlcnNCLwoYY29tLmdvb2dsZS5tb25pdG9yaW5nLnYzQhFH",
"cm91cFNlcnZpY2VQcm90b1ABYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Api.MonitoredResourceReflection.Descriptor, global::Google.Monitoring.V3.CommonReflection.Descriptor, global::Google.Monitoring.V3.GroupReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Monitoring.V3.ListGroupsRequest), global::Google.Monitoring.V3.ListGroupsRequest.Parser, new[]{ "Name", "ChildrenOfGroup", "AncestorsOfGroup", "DescendantsOfGroup", "PageSize", "PageToken" }, new[]{ "Filter" }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Monitoring.V3.ListGroupsResponse), global::Google.Monitoring.V3.ListGroupsResponse.Parser, new[]{ "Group", "NextPageToken" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Monitoring.V3.GetGroupRequest), global::Google.Monitoring.V3.GetGroupRequest.Parser, new[]{ "Name" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Monitoring.V3.CreateGroupRequest), global::Google.Monitoring.V3.CreateGroupRequest.Parser, new[]{ "Name", "Group", "ValidateOnly" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Monitoring.V3.UpdateGroupRequest), global::Google.Monitoring.V3.UpdateGroupRequest.Parser, new[]{ "Group", "ValidateOnly" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Monitoring.V3.DeleteGroupRequest), global::Google.Monitoring.V3.DeleteGroupRequest.Parser, new[]{ "Name" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Monitoring.V3.ListGroupMembersRequest), global::Google.Monitoring.V3.ListGroupMembersRequest.Parser, new[]{ "Name", "PageSize", "PageToken", "Filter", "Interval" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Monitoring.V3.ListGroupMembersResponse), global::Google.Monitoring.V3.ListGroupMembersResponse.Parser, new[]{ "Members", "NextPageToken", "TotalSize" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// The `ListGroup` request.
/// </summary>
public sealed partial class ListGroupsRequest : pb::IMessage<ListGroupsRequest> {
private static readonly pb::MessageParser<ListGroupsRequest> _parser = new pb::MessageParser<ListGroupsRequest>(() => new ListGroupsRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListGroupsRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListGroupsRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListGroupsRequest(ListGroupsRequest other) : this() {
name_ = other.name_;
pageSize_ = other.pageSize_;
pageToken_ = other.pageToken_;
switch (other.FilterCase) {
case FilterOneofCase.ChildrenOfGroup:
ChildrenOfGroup = other.ChildrenOfGroup;
break;
case FilterOneofCase.AncestorsOfGroup:
AncestorsOfGroup = other.AncestorsOfGroup;
break;
case FilterOneofCase.DescendantsOfGroup:
DescendantsOfGroup = other.DescendantsOfGroup;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListGroupsRequest Clone() {
return new ListGroupsRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 7;
private string name_ = "";
/// <summary>
/// The project whose groups are to be listed. The format is
/// `"projects/{project_id_or_number}"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "children_of_group" field.</summary>
public const int ChildrenOfGroupFieldNumber = 2;
/// <summary>
/// A group name: `"projects/{project_id_or_number}/groups/{group_id}"`.
/// Returns groups whose `parentName` field contains the group
/// name. If no groups have this parent, the results are empty.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ChildrenOfGroup {
get { return filterCase_ == FilterOneofCase.ChildrenOfGroup ? (string) filter_ : ""; }
set {
filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
filterCase_ = FilterOneofCase.ChildrenOfGroup;
}
}
/// <summary>Field number for the "ancestors_of_group" field.</summary>
public const int AncestorsOfGroupFieldNumber = 3;
/// <summary>
/// A group name: `"projects/{project_id_or_number}/groups/{group_id}"`.
/// Returns groups that are ancestors of the specified group.
/// The groups are returned in order, starting with the immediate parent and
/// ending with the most distant ancestor. If the specified group has no
/// immediate parent, the results are empty.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string AncestorsOfGroup {
get { return filterCase_ == FilterOneofCase.AncestorsOfGroup ? (string) filter_ : ""; }
set {
filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
filterCase_ = FilterOneofCase.AncestorsOfGroup;
}
}
/// <summary>Field number for the "descendants_of_group" field.</summary>
public const int DescendantsOfGroupFieldNumber = 4;
/// <summary>
/// A group name: `"projects/{project_id_or_number}/groups/{group_id}"`.
/// Returns the descendants of the specified group. This is a superset of
/// the results returned by the `childrenOfGroup` filter, and includes
/// children-of-children, and so forth.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string DescendantsOfGroup {
get { return filterCase_ == FilterOneofCase.DescendantsOfGroup ? (string) filter_ : ""; }
set {
filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
filterCase_ = FilterOneofCase.DescendantsOfGroup;
}
}
/// <summary>Field number for the "page_size" field.</summary>
public const int PageSizeFieldNumber = 5;
private int pageSize_;
/// <summary>
/// A positive number that is the maximum number of results to return.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int PageSize {
get { return pageSize_; }
set {
pageSize_ = value;
}
}
/// <summary>Field number for the "page_token" field.</summary>
public const int PageTokenFieldNumber = 6;
private string pageToken_ = "";
/// <summary>
/// If this field is not empty then it must contain the `nextPageToken` value
/// returned by a previous call to this method. Using this field causes the
/// method to return additional results from the previous method call.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string PageToken {
get { return pageToken_; }
set {
pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
private object filter_;
/// <summary>Enum of possible cases for the "filter" oneof.</summary>
public enum FilterOneofCase {
None = 0,
ChildrenOfGroup = 2,
AncestorsOfGroup = 3,
DescendantsOfGroup = 4,
}
private FilterOneofCase filterCase_ = FilterOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FilterOneofCase FilterCase {
get { return filterCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearFilter() {
filterCase_ = FilterOneofCase.None;
filter_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListGroupsRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListGroupsRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (ChildrenOfGroup != other.ChildrenOfGroup) return false;
if (AncestorsOfGroup != other.AncestorsOfGroup) return false;
if (DescendantsOfGroup != other.DescendantsOfGroup) return false;
if (PageSize != other.PageSize) return false;
if (PageToken != other.PageToken) return false;
if (FilterCase != other.FilterCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (filterCase_ == FilterOneofCase.ChildrenOfGroup) hash ^= ChildrenOfGroup.GetHashCode();
if (filterCase_ == FilterOneofCase.AncestorsOfGroup) hash ^= AncestorsOfGroup.GetHashCode();
if (filterCase_ == FilterOneofCase.DescendantsOfGroup) hash ^= DescendantsOfGroup.GetHashCode();
if (PageSize != 0) hash ^= PageSize.GetHashCode();
if (PageToken.Length != 0) hash ^= PageToken.GetHashCode();
hash ^= (int) filterCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (filterCase_ == FilterOneofCase.ChildrenOfGroup) {
output.WriteRawTag(18);
output.WriteString(ChildrenOfGroup);
}
if (filterCase_ == FilterOneofCase.AncestorsOfGroup) {
output.WriteRawTag(26);
output.WriteString(AncestorsOfGroup);
}
if (filterCase_ == FilterOneofCase.DescendantsOfGroup) {
output.WriteRawTag(34);
output.WriteString(DescendantsOfGroup);
}
if (PageSize != 0) {
output.WriteRawTag(40);
output.WriteInt32(PageSize);
}
if (PageToken.Length != 0) {
output.WriteRawTag(50);
output.WriteString(PageToken);
}
if (Name.Length != 0) {
output.WriteRawTag(58);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (filterCase_ == FilterOneofCase.ChildrenOfGroup) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ChildrenOfGroup);
}
if (filterCase_ == FilterOneofCase.AncestorsOfGroup) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(AncestorsOfGroup);
}
if (filterCase_ == FilterOneofCase.DescendantsOfGroup) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DescendantsOfGroup);
}
if (PageSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize);
}
if (PageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListGroupsRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.PageSize != 0) {
PageSize = other.PageSize;
}
if (other.PageToken.Length != 0) {
PageToken = other.PageToken;
}
switch (other.FilterCase) {
case FilterOneofCase.ChildrenOfGroup:
ChildrenOfGroup = other.ChildrenOfGroup;
break;
case FilterOneofCase.AncestorsOfGroup:
AncestorsOfGroup = other.AncestorsOfGroup;
break;
case FilterOneofCase.DescendantsOfGroup:
DescendantsOfGroup = other.DescendantsOfGroup;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 18: {
ChildrenOfGroup = input.ReadString();
break;
}
case 26: {
AncestorsOfGroup = input.ReadString();
break;
}
case 34: {
DescendantsOfGroup = input.ReadString();
break;
}
case 40: {
PageSize = input.ReadInt32();
break;
}
case 50: {
PageToken = input.ReadString();
break;
}
case 58: {
Name = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The `ListGroups` response.
/// </summary>
public sealed partial class ListGroupsResponse : pb::IMessage<ListGroupsResponse> {
private static readonly pb::MessageParser<ListGroupsResponse> _parser = new pb::MessageParser<ListGroupsResponse>(() => new ListGroupsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListGroupsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListGroupsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListGroupsResponse(ListGroupsResponse other) : this() {
group_ = other.group_.Clone();
nextPageToken_ = other.nextPageToken_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListGroupsResponse Clone() {
return new ListGroupsResponse(this);
}
/// <summary>Field number for the "group" field.</summary>
public const int GroupFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Monitoring.V3.Group> _repeated_group_codec
= pb::FieldCodec.ForMessage(10, global::Google.Monitoring.V3.Group.Parser);
private readonly pbc::RepeatedField<global::Google.Monitoring.V3.Group> group_ = new pbc::RepeatedField<global::Google.Monitoring.V3.Group>();
/// <summary>
/// The groups that match the specified filters.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Monitoring.V3.Group> Group {
get { return group_; }
}
/// <summary>Field number for the "next_page_token" field.</summary>
public const int NextPageTokenFieldNumber = 2;
private string nextPageToken_ = "";
/// <summary>
/// If there are more results than have been returned, then this field is set
/// to a non-empty value. To see the additional results,
/// use that value as `pageToken` in the next call to this method.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string NextPageToken {
get { return nextPageToken_; }
set {
nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListGroupsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListGroupsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!group_.Equals(other.group_)) return false;
if (NextPageToken != other.NextPageToken) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= group_.GetHashCode();
if (NextPageToken.Length != 0) hash ^= NextPageToken.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) {
group_.WriteTo(output, _repeated_group_codec);
if (NextPageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(NextPageToken);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += group_.CalculateSize(_repeated_group_codec);
if (NextPageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListGroupsResponse other) {
if (other == null) {
return;
}
group_.Add(other.group_);
if (other.NextPageToken.Length != 0) {
NextPageToken = other.NextPageToken;
}
}
[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: {
group_.AddEntriesFrom(input, _repeated_group_codec);
break;
}
case 18: {
NextPageToken = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The `GetGroup` request.
/// </summary>
public sealed partial class GetGroupRequest : pb::IMessage<GetGroupRequest> {
private static readonly pb::MessageParser<GetGroupRequest> _parser = new pb::MessageParser<GetGroupRequest>(() => new GetGroupRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetGroupRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetGroupRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetGroupRequest(GetGroupRequest other) : this() {
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetGroupRequest Clone() {
return new GetGroupRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 3;
private string name_ = "";
/// <summary>
/// The group to retrieve. The format is
/// `"projects/{project_id_or_number}/groups/{group_id}"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetGroupRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetGroupRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetGroupRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 26: {
Name = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The `CreateGroup` request.
/// </summary>
public sealed partial class CreateGroupRequest : pb::IMessage<CreateGroupRequest> {
private static readonly pb::MessageParser<CreateGroupRequest> _parser = new pb::MessageParser<CreateGroupRequest>(() => new CreateGroupRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CreateGroupRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateGroupRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateGroupRequest(CreateGroupRequest other) : this() {
name_ = other.name_;
Group = other.group_ != null ? other.Group.Clone() : null;
validateOnly_ = other.validateOnly_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateGroupRequest Clone() {
return new CreateGroupRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 4;
private string name_ = "";
/// <summary>
/// The project in which to create the group. The format is
/// `"projects/{project_id_or_number}"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "group" field.</summary>
public const int GroupFieldNumber = 2;
private global::Google.Monitoring.V3.Group group_;
/// <summary>
/// A group definition. It is an error to define the `name` field because
/// the system assigns the name.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Monitoring.V3.Group Group {
get { return group_; }
set {
group_ = value;
}
}
/// <summary>Field number for the "validate_only" field.</summary>
public const int ValidateOnlyFieldNumber = 3;
private bool validateOnly_;
/// <summary>
/// If true, validate this request but do not create the group.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ValidateOnly {
get { return validateOnly_; }
set {
validateOnly_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CreateGroupRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CreateGroupRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (!object.Equals(Group, other.Group)) return false;
if (ValidateOnly != other.ValidateOnly) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (group_ != null) hash ^= Group.GetHashCode();
if (ValidateOnly != false) hash ^= ValidateOnly.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (group_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Group);
}
if (ValidateOnly != false) {
output.WriteRawTag(24);
output.WriteBool(ValidateOnly);
}
if (Name.Length != 0) {
output.WriteRawTag(34);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (group_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Group);
}
if (ValidateOnly != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CreateGroupRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.group_ != null) {
if (group_ == null) {
group_ = new global::Google.Monitoring.V3.Group();
}
Group.MergeFrom(other.Group);
}
if (other.ValidateOnly != false) {
ValidateOnly = other.ValidateOnly;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 18: {
if (group_ == null) {
group_ = new global::Google.Monitoring.V3.Group();
}
input.ReadMessage(group_);
break;
}
case 24: {
ValidateOnly = input.ReadBool();
break;
}
case 34: {
Name = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The `UpdateGroup` request.
/// </summary>
public sealed partial class UpdateGroupRequest : pb::IMessage<UpdateGroupRequest> {
private static readonly pb::MessageParser<UpdateGroupRequest> _parser = new pb::MessageParser<UpdateGroupRequest>(() => new UpdateGroupRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UpdateGroupRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateGroupRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateGroupRequest(UpdateGroupRequest other) : this() {
Group = other.group_ != null ? other.Group.Clone() : null;
validateOnly_ = other.validateOnly_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateGroupRequest Clone() {
return new UpdateGroupRequest(this);
}
/// <summary>Field number for the "group" field.</summary>
public const int GroupFieldNumber = 2;
private global::Google.Monitoring.V3.Group group_;
/// <summary>
/// The new definition of the group. All fields of the existing group,
/// excepting `name`, are replaced with the corresponding fields of this group.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Monitoring.V3.Group Group {
get { return group_; }
set {
group_ = value;
}
}
/// <summary>Field number for the "validate_only" field.</summary>
public const int ValidateOnlyFieldNumber = 3;
private bool validateOnly_;
/// <summary>
/// If true, validate this request but do not update the existing group.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ValidateOnly {
get { return validateOnly_; }
set {
validateOnly_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UpdateGroupRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UpdateGroupRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Group, other.Group)) return false;
if (ValidateOnly != other.ValidateOnly) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (group_ != null) hash ^= Group.GetHashCode();
if (ValidateOnly != false) hash ^= ValidateOnly.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (group_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Group);
}
if (ValidateOnly != false) {
output.WriteRawTag(24);
output.WriteBool(ValidateOnly);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (group_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Group);
}
if (ValidateOnly != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UpdateGroupRequest other) {
if (other == null) {
return;
}
if (other.group_ != null) {
if (group_ == null) {
group_ = new global::Google.Monitoring.V3.Group();
}
Group.MergeFrom(other.Group);
}
if (other.ValidateOnly != false) {
ValidateOnly = other.ValidateOnly;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 18: {
if (group_ == null) {
group_ = new global::Google.Monitoring.V3.Group();
}
input.ReadMessage(group_);
break;
}
case 24: {
ValidateOnly = input.ReadBool();
break;
}
}
}
}
}
/// <summary>
/// The `DeleteGroup` request. You can only delete a group if it has no children.
/// </summary>
public sealed partial class DeleteGroupRequest : pb::IMessage<DeleteGroupRequest> {
private static readonly pb::MessageParser<DeleteGroupRequest> _parser = new pb::MessageParser<DeleteGroupRequest>(() => new DeleteGroupRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DeleteGroupRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteGroupRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteGroupRequest(DeleteGroupRequest other) : this() {
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteGroupRequest Clone() {
return new DeleteGroupRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 3;
private string name_ = "";
/// <summary>
/// The group to delete. The format is
/// `"projects/{project_id_or_number}/groups/{group_id}"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DeleteGroupRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DeleteGroupRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DeleteGroupRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 26: {
Name = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The `ListGroupMembers` request.
/// </summary>
public sealed partial class ListGroupMembersRequest : pb::IMessage<ListGroupMembersRequest> {
private static readonly pb::MessageParser<ListGroupMembersRequest> _parser = new pb::MessageParser<ListGroupMembersRequest>(() => new ListGroupMembersRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListGroupMembersRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListGroupMembersRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListGroupMembersRequest(ListGroupMembersRequest other) : this() {
name_ = other.name_;
pageSize_ = other.pageSize_;
pageToken_ = other.pageToken_;
filter_ = other.filter_;
Interval = other.interval_ != null ? other.Interval.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListGroupMembersRequest Clone() {
return new ListGroupMembersRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 7;
private string name_ = "";
/// <summary>
/// The group whose members are listed. The format is
/// `"projects/{project_id_or_number}/groups/{group_id}"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "page_size" field.</summary>
public const int PageSizeFieldNumber = 3;
private int pageSize_;
/// <summary>
/// A positive number that is the maximum number of results to return.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int PageSize {
get { return pageSize_; }
set {
pageSize_ = value;
}
}
/// <summary>Field number for the "page_token" field.</summary>
public const int PageTokenFieldNumber = 4;
private string pageToken_ = "";
/// <summary>
/// If this field is not empty then it must contain the `nextPageToken` value
/// returned by a previous call to this method. Using this field causes the
/// method to return additional results from the previous method call.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string PageToken {
get { return pageToken_; }
set {
pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "filter" field.</summary>
public const int FilterFieldNumber = 5;
private string filter_ = "";
/// <summary>
/// An optional [list filter](/monitoring/api/learn_more#filtering) describing
/// the members to be returned. The filter may reference the type, labels, and
/// metadata of monitored resources that comprise the group.
/// For example, to return only resources representing Compute Engine VM
/// instances, use this filter:
///
/// resource.type = "gce_instance"
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Filter {
get { return filter_; }
set {
filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "interval" field.</summary>
public const int IntervalFieldNumber = 6;
private global::Google.Monitoring.V3.TimeInterval interval_;
/// <summary>
/// An optional time interval for which results should be returned. Only
/// members that were part of the group during the specified interval are
/// included in the response. If no interval is provided then the group
/// membership over the last minute is returned.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Monitoring.V3.TimeInterval Interval {
get { return interval_; }
set {
interval_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListGroupMembersRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListGroupMembersRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (PageSize != other.PageSize) return false;
if (PageToken != other.PageToken) return false;
if (Filter != other.Filter) return false;
if (!object.Equals(Interval, other.Interval)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (PageSize != 0) hash ^= PageSize.GetHashCode();
if (PageToken.Length != 0) hash ^= PageToken.GetHashCode();
if (Filter.Length != 0) hash ^= Filter.GetHashCode();
if (interval_ != null) hash ^= Interval.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (PageSize != 0) {
output.WriteRawTag(24);
output.WriteInt32(PageSize);
}
if (PageToken.Length != 0) {
output.WriteRawTag(34);
output.WriteString(PageToken);
}
if (Filter.Length != 0) {
output.WriteRawTag(42);
output.WriteString(Filter);
}
if (interval_ != null) {
output.WriteRawTag(50);
output.WriteMessage(Interval);
}
if (Name.Length != 0) {
output.WriteRawTag(58);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (PageSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize);
}
if (PageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken);
}
if (Filter.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Filter);
}
if (interval_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Interval);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListGroupMembersRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.PageSize != 0) {
PageSize = other.PageSize;
}
if (other.PageToken.Length != 0) {
PageToken = other.PageToken;
}
if (other.Filter.Length != 0) {
Filter = other.Filter;
}
if (other.interval_ != null) {
if (interval_ == null) {
interval_ = new global::Google.Monitoring.V3.TimeInterval();
}
Interval.MergeFrom(other.Interval);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 24: {
PageSize = input.ReadInt32();
break;
}
case 34: {
PageToken = input.ReadString();
break;
}
case 42: {
Filter = input.ReadString();
break;
}
case 50: {
if (interval_ == null) {
interval_ = new global::Google.Monitoring.V3.TimeInterval();
}
input.ReadMessage(interval_);
break;
}
case 58: {
Name = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The `ListGroupMembers` response.
/// </summary>
public sealed partial class ListGroupMembersResponse : pb::IMessage<ListGroupMembersResponse> {
private static readonly pb::MessageParser<ListGroupMembersResponse> _parser = new pb::MessageParser<ListGroupMembersResponse>(() => new ListGroupMembersResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListGroupMembersResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Monitoring.V3.GroupServiceReflection.Descriptor.MessageTypes[7]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListGroupMembersResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListGroupMembersResponse(ListGroupMembersResponse other) : this() {
members_ = other.members_.Clone();
nextPageToken_ = other.nextPageToken_;
totalSize_ = other.totalSize_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListGroupMembersResponse Clone() {
return new ListGroupMembersResponse(this);
}
/// <summary>Field number for the "members" field.</summary>
public const int MembersFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Api.MonitoredResource> _repeated_members_codec
= pb::FieldCodec.ForMessage(10, global::Google.Api.MonitoredResource.Parser);
private readonly pbc::RepeatedField<global::Google.Api.MonitoredResource> members_ = new pbc::RepeatedField<global::Google.Api.MonitoredResource>();
/// <summary>
/// A set of monitored resources in the group.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.MonitoredResource> Members {
get { return members_; }
}
/// <summary>Field number for the "next_page_token" field.</summary>
public const int NextPageTokenFieldNumber = 2;
private string nextPageToken_ = "";
/// <summary>
/// If there are more results than have been returned, then this field is
/// set to a non-empty value. To see the additional results, use that value as
/// `pageToken` in the next call to this method.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string NextPageToken {
get { return nextPageToken_; }
set {
nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "total_size" field.</summary>
public const int TotalSizeFieldNumber = 3;
private int totalSize_;
/// <summary>
/// The total number of elements matching this request.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int TotalSize {
get { return totalSize_; }
set {
totalSize_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListGroupMembersResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListGroupMembersResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!members_.Equals(other.members_)) return false;
if (NextPageToken != other.NextPageToken) return false;
if (TotalSize != other.TotalSize) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= members_.GetHashCode();
if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode();
if (TotalSize != 0) hash ^= TotalSize.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) {
members_.WriteTo(output, _repeated_members_codec);
if (NextPageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(NextPageToken);
}
if (TotalSize != 0) {
output.WriteRawTag(24);
output.WriteInt32(TotalSize);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += members_.CalculateSize(_repeated_members_codec);
if (NextPageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken);
}
if (TotalSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(TotalSize);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListGroupMembersResponse other) {
if (other == null) {
return;
}
members_.Add(other.members_);
if (other.NextPageToken.Length != 0) {
NextPageToken = other.NextPageToken;
}
if (other.TotalSize != 0) {
TotalSize = other.TotalSize;
}
}
[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: {
members_.AddEntriesFrom(input, _repeated_members_codec);
break;
}
case 18: {
NextPageToken = input.ReadString();
break;
}
case 24: {
TotalSize = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Avalonia.Collections;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Controls.Utils;
using Avalonia.Input;
using Avalonia.LogicalTree;
using Avalonia.Metadata;
using Avalonia.VisualTree;
namespace Avalonia.Controls
{
/// <summary>
/// Displays a collection of items.
/// </summary>
[PseudoClasses(":empty", ":singleitem")]
public class ItemsControl : TemplatedControl, IItemsPresenterHost, ICollectionChangedListener
{
/// <summary>
/// The default value for the <see cref="ItemsPanel"/> property.
/// </summary>
private static readonly FuncTemplate<IPanel> DefaultPanel =
new FuncTemplate<IPanel>(() => new StackPanel());
/// <summary>
/// Defines the <see cref="Items"/> property.
/// </summary>
public static readonly DirectProperty<ItemsControl, IEnumerable> ItemsProperty =
AvaloniaProperty.RegisterDirect<ItemsControl, IEnumerable>(nameof(Items), o => o.Items, (o, v) => o.Items = v);
/// <summary>
/// Defines the <see cref="ItemCount"/> property.
/// </summary>
public static readonly DirectProperty<ItemsControl, int> ItemCountProperty =
AvaloniaProperty.RegisterDirect<ItemsControl, int>(nameof(ItemCount), o => o.ItemCount);
/// <summary>
/// Defines the <see cref="ItemsPanel"/> property.
/// </summary>
public static readonly StyledProperty<ITemplate<IPanel>> ItemsPanelProperty =
AvaloniaProperty.Register<ItemsControl, ITemplate<IPanel>>(nameof(ItemsPanel), DefaultPanel);
/// <summary>
/// Defines the <see cref="ItemTemplate"/> property.
/// </summary>
public static readonly StyledProperty<IDataTemplate> ItemTemplateProperty =
AvaloniaProperty.Register<ItemsControl, IDataTemplate>(nameof(ItemTemplate));
private IEnumerable _items = new AvaloniaList<object>();
private int _itemCount;
private IItemContainerGenerator _itemContainerGenerator;
/// <summary>
/// Initializes static members of the <see cref="ItemsControl"/> class.
/// </summary>
static ItemsControl()
{
ItemsProperty.Changed.AddClassHandler<ItemsControl>((x, e) => x.ItemsChanged(e));
ItemTemplateProperty.Changed.AddClassHandler<ItemsControl>((x, e) => x.ItemTemplateChanged(e));
}
/// <summary>
/// Initializes a new instance of the <see cref="ItemsControl"/> class.
/// </summary>
public ItemsControl()
{
UpdatePseudoClasses(0);
SubscribeToItems(_items);
}
/// <summary>
/// Gets the <see cref="IItemContainerGenerator"/> for the control.
/// </summary>
public IItemContainerGenerator ItemContainerGenerator
{
get
{
if (_itemContainerGenerator == null)
{
_itemContainerGenerator = CreateItemContainerGenerator();
if (_itemContainerGenerator != null)
{
_itemContainerGenerator.ItemTemplate = ItemTemplate;
_itemContainerGenerator.Materialized += (_, e) => OnContainersMaterialized(e);
_itemContainerGenerator.Dematerialized += (_, e) => OnContainersDematerialized(e);
_itemContainerGenerator.Recycled += (_, e) => OnContainersRecycled(e);
}
}
return _itemContainerGenerator;
}
}
/// <summary>
/// Gets or sets the items to display.
/// </summary>
[Content]
public IEnumerable Items
{
get { return _items; }
set { SetAndRaise(ItemsProperty, ref _items, value); }
}
/// <summary>
/// Gets the number of items in <see cref="Items"/>.
/// </summary>
public int ItemCount
{
get => _itemCount;
private set => SetAndRaise(ItemCountProperty, ref _itemCount, value);
}
/// <summary>
/// Gets or sets the panel used to display the items.
/// </summary>
public ITemplate<IPanel> ItemsPanel
{
get { return GetValue(ItemsPanelProperty); }
set { SetValue(ItemsPanelProperty, value); }
}
/// <summary>
/// Gets or sets the data template used to display the items in the control.
/// </summary>
public IDataTemplate ItemTemplate
{
get { return GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
/// <summary>
/// Gets the items presenter control.
/// </summary>
public IItemsPresenter Presenter
{
get;
protected set;
}
/// <inheritdoc/>
void IItemsPresenterHost.RegisterItemsPresenter(IItemsPresenter presenter)
{
Presenter = presenter;
ItemContainerGenerator.Clear();
}
void ICollectionChangedListener.PreChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
{
}
void ICollectionChangedListener.Changed(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
{
}
void ICollectionChangedListener.PostChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
{
ItemsCollectionChanged(sender, e);
}
/// <summary>
/// Gets the item at the specified index in a collection.
/// </summary>
/// <param name="items">The collection.</param>
/// <param name="index">The index.</param>
/// <returns>The item at the given index or null if the index is out of bounds.</returns>
protected static object ElementAt(IEnumerable items, int index)
{
if (index != -1 && index < items.Count())
{
return items.ElementAt(index) ?? null;
}
else
{
return null;
}
}
/// <summary>
/// Gets the index of an item in a collection.
/// </summary>
/// <param name="items">The collection.</param>
/// <param name="item">The item.</param>
/// <returns>The index of the item or -1 if the item was not found.</returns>
protected static int IndexOf(IEnumerable items, object item)
{
if (items != null && item != null)
{
var list = items as IList;
if (list != null)
{
return list.IndexOf(item);
}
else
{
int index = 0;
foreach (var i in items)
{
if (Equals(i, item))
{
return index;
}
++index;
}
}
}
return -1;
}
/// <summary>
/// Creates the <see cref="ItemContainerGenerator"/> for the control.
/// </summary>
/// <returns>
/// An <see cref="IItemContainerGenerator"/> or null.
/// </returns>
/// <remarks>
/// Certain controls such as <see cref="TabControl"/> don't actually create item
/// containers; however they want it to be ItemsControls so that they have an Items
/// property etc. In this case, a derived class can override this method to return null
/// in order to disable the creation of item containers.
/// </remarks>
protected virtual IItemContainerGenerator CreateItemContainerGenerator()
{
return new ItemContainerGenerator(this);
}
/// <summary>
/// Called when new containers are materialized for the <see cref="ItemsControl"/> by its
/// <see cref="ItemContainerGenerator"/>.
/// </summary>
/// <param name="e">The details of the containers.</param>
protected virtual void OnContainersMaterialized(ItemContainerEventArgs e)
{
foreach (var container in e.Containers)
{
// If the item is its own container, then it will be added to the logical tree when
// it was added to the Items collection.
if (container.ContainerControl != null && container.ContainerControl != container.Item)
{
LogicalChildren.Add(container.ContainerControl);
}
}
}
/// <summary>
/// Called when containers are dematerialized for the <see cref="ItemsControl"/> by its
/// <see cref="ItemContainerGenerator"/>.
/// </summary>
/// <param name="e">The details of the containers.</param>
protected virtual void OnContainersDematerialized(ItemContainerEventArgs e)
{
foreach (var container in e.Containers)
{
// If the item is its own container, then it will be removed from the logical tree
// when it is removed from the Items collection.
if (container?.ContainerControl != container?.Item)
{
LogicalChildren.Remove(container.ContainerControl);
}
}
}
/// <summary>
/// Called when containers are recycled for the <see cref="ItemsControl"/> by its
/// <see cref="ItemContainerGenerator"/>.
/// </summary>
/// <param name="e">The details of the containers.</param>
protected virtual void OnContainersRecycled(ItemContainerEventArgs e)
{
}
/// <summary>
/// Handles directional navigation within the <see cref="ItemsControl"/>.
/// </summary>
/// <param name="e">The key events.</param>
protected override void OnKeyDown(KeyEventArgs e)
{
if (!e.Handled)
{
var focus = FocusManager.Instance;
var direction = e.Key.ToNavigationDirection();
var container = Presenter?.Panel as INavigableContainer;
if (container == null ||
focus.Current == null ||
direction == null ||
direction.Value.IsTab())
{
return;
}
IVisual current = focus.Current;
while (current != null)
{
if (current.VisualParent == container && current is IInputElement inputElement)
{
IInputElement next = GetNextControl(container, direction.Value, inputElement, false);
if (next != null)
{
focus.Focus(next, NavigationMethod.Directional, e.KeyModifiers);
e.Handled = true;
}
break;
}
current = current.VisualParent;
}
}
base.OnKeyDown(e);
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == ItemCountProperty)
{
UpdatePseudoClasses(change.NewValue.GetValueOrDefault<int>());
}
}
/// <summary>
/// Called when the <see cref="Items"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void ItemsChanged(AvaloniaPropertyChangedEventArgs e)
{
var oldValue = e.OldValue as IEnumerable;
var newValue = e.NewValue as IEnumerable;
if (oldValue is INotifyCollectionChanged incc)
{
CollectionChangedEventManager.Instance.RemoveListener(incc, this);
}
UpdateItemCount();
RemoveControlItemsFromLogicalChildren(oldValue);
AddControlItemsToLogicalChildren(newValue);
if (Presenter != null)
{
Presenter.Items = newValue;
}
SubscribeToItems(newValue);
}
/// <summary>
/// Called when the <see cref="INotifyCollectionChanged.CollectionChanged"/> event is
/// raised on <see cref="Items"/>.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
protected virtual void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
UpdateItemCount();
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
AddControlItemsToLogicalChildren(e.NewItems);
break;
case NotifyCollectionChangedAction.Remove:
RemoveControlItemsFromLogicalChildren(e.OldItems);
break;
}
Presenter?.ItemsChanged(e);
}
/// <summary>
/// Given a collection of items, adds those that are controls to the logical children.
/// </summary>
/// <param name="items">The items.</param>
private void AddControlItemsToLogicalChildren(IEnumerable items)
{
var toAdd = new List<ILogical>();
if (items != null)
{
foreach (var i in items)
{
var control = i as IControl;
if (control != null && !LogicalChildren.Contains(control))
{
toAdd.Add(control);
}
}
}
LogicalChildren.AddRange(toAdd);
}
/// <summary>
/// Given a collection of items, removes those that are controls to from logical children.
/// </summary>
/// <param name="items">The items.</param>
private void RemoveControlItemsFromLogicalChildren(IEnumerable items)
{
var toRemove = new List<ILogical>();
if (items != null)
{
foreach (var i in items)
{
var control = i as IControl;
if (control != null)
{
toRemove.Add(control);
}
}
}
LogicalChildren.RemoveAll(toRemove);
}
/// <summary>
/// Subscribes to an <see cref="Items"/> collection.
/// </summary>
/// <param name="items">The items collection.</param>
private void SubscribeToItems(IEnumerable items)
{
if (items is INotifyCollectionChanged incc)
{
CollectionChangedEventManager.Instance.AddListener(incc, this);
}
}
/// <summary>
/// Called when the <see cref="ItemTemplate"/> changes.
/// </summary>
/// <param name="e">The event args.</param>
private void ItemTemplateChanged(AvaloniaPropertyChangedEventArgs e)
{
if (_itemContainerGenerator != null)
{
_itemContainerGenerator.ItemTemplate = (IDataTemplate)e.NewValue;
// TODO: Rebuild the item containers.
}
}
private void UpdateItemCount()
{
if (Items == null)
{
ItemCount = 0;
}
else if (Items is IList list)
{
ItemCount = list.Count;
}
else
{
ItemCount = Items.Count();
}
}
private void UpdatePseudoClasses(int itemCount)
{
PseudoClasses.Set(":empty", itemCount == 0);
PseudoClasses.Set(":singleitem", itemCount == 1);
}
protected static IInputElement GetNextControl(
INavigableContainer container,
NavigationDirection direction,
IInputElement from,
bool wrap)
{
IInputElement result;
var c = from;
do
{
result = container.GetControl(direction, c, wrap);
from = from ?? result;
if (result != null &&
result.Focusable &&
result.IsEffectivelyEnabled &&
result.IsEffectivelyVisible)
{
return result;
}
c = result;
} while (c != null && c != from);
return null;
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.IO;
using System.Linq;
using System.Text;
using Cassandra.Connections;
using Cassandra.ExecutionProfiles;
using Cassandra.Requests;
using Cassandra.Serialization;
using NUnit.Framework;
using PrepareFlags = Cassandra.Requests.PrepareRequest.PrepareFlags;
using QueryFlags = Cassandra.QueryProtocolOptions.QueryFlags;
namespace Cassandra.Tests
{
[TestFixture]
public class RequestHandlerTests
{
private static readonly ISerializerManager SerializerManager = new SerializerManager(ProtocolVersion.MaxSupported);
private static readonly ISerializer Serializer = new SerializerManager(ProtocolVersion.MaxSupported).GetCurrentSerializer();
private static Configuration GetConfig(QueryOptions queryOptions = null, Cassandra.Policies policies = null, PoolingOptions poolingOptions = null)
{
return new TestConfigurationBuilder
{
Policies = policies ?? new Cassandra.Policies(),
PoolingOptions = poolingOptions,
QueryOptions = queryOptions ?? DefaultQueryOptions
}.Build();
}
private static IRequestOptions GetRequestOptions(QueryOptions queryOptions = null, Cassandra.Policies policies = null)
{
return RequestHandlerTests.GetConfig(queryOptions, policies).DefaultRequestOptions;
}
private static QueryOptions DefaultQueryOptions => new QueryOptions();
private static PreparedStatement GetPrepared(
byte[] queryId = null, ISerializerManager serializerManager = null, RowSetMetadata rowSetMetadata = null)
{
return new PreparedStatement(
null,
queryId,
new ResultMetadata(new byte[16], rowSetMetadata),
"DUMMY QUERY",
null,
serializerManager ?? RequestHandlerTests.SerializerManager);
}
[Test]
public void RequestHandler_GetRequest_SimpleStatement_Default_QueryOptions_Are_Used()
{
var stmt = new SimpleStatement("DUMMY QUERY");
Assert.AreEqual(0, stmt.PageSize);
Assert.Null(stmt.ConsistencyLevel);
var request = (QueryRequest)RequestHandler.GetRequest(stmt, Serializer, GetRequestOptions());
Assert.AreEqual(DefaultQueryOptions.GetPageSize(), request.PageSize);
Assert.AreEqual(DefaultQueryOptions.GetConsistencyLevel(), request.Consistency);
}
[Test]
public void RequestHandler_GetRequest_SimpleStatement_QueryOptions_Are_Used()
{
var stmt = new SimpleStatement("DUMMY QUERY");
Assert.AreEqual(0, stmt.PageSize);
Assert.Null(stmt.ConsistencyLevel);
var queryOptions = new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum).SetPageSize(100);
var request = (QueryRequest)RequestHandler.GetRequest(stmt, Serializer, GetRequestOptions(queryOptions));
Assert.AreEqual(100, request.PageSize);
Assert.AreEqual(queryOptions.GetPageSize(), request.PageSize);
Assert.AreEqual(queryOptions.GetConsistencyLevel(), request.Consistency);
Assert.AreEqual(queryOptions.GetSerialConsistencyLevel(), request.SerialConsistency);
}
[Test]
public void RequestHandler_GetRequest_SimpleStatement_Statement_Level_Settings_Are_Used()
{
var stmt = new SimpleStatement("DUMMY QUERY");
stmt.SetConsistencyLevel(ConsistencyLevel.EachQuorum);
stmt.SetPageSize(350);
stmt.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
Assert.AreEqual(350, stmt.PageSize);
Assert.AreEqual(ConsistencyLevel.EachQuorum, stmt.ConsistencyLevel);
Assert.AreEqual(ConsistencyLevel.LocalSerial, stmt.SerialConsistencyLevel);
var request = (QueryRequest)RequestHandler.GetRequest(stmt, Serializer, GetRequestOptions());
Assert.AreEqual(350, request.PageSize);
Assert.AreEqual(ConsistencyLevel.EachQuorum, request.Consistency);
Assert.AreEqual(ConsistencyLevel.LocalSerial, request.SerialConsistency);
}
[Test]
public void RequestHandler_GetRequest_BoundStatement_Default_QueryOptions_Are_Used()
{
var ps = GetPrepared();
var stmt = ps.Bind();
Assert.AreEqual(0, stmt.PageSize);
Assert.Null(stmt.ConsistencyLevel);
var request = (ExecuteRequest)RequestHandler.GetRequest(stmt, Serializer, GetRequestOptions());
Assert.AreEqual(DefaultQueryOptions.GetPageSize(), request.PageSize);
Assert.AreEqual(DefaultQueryOptions.GetConsistencyLevel(), request.Consistency);
}
[Test]
public void RequestHandler_GetRequest_BoundStatement_QueryOptions_Are_Used()
{
var ps = GetPrepared();
var stmt = ps.Bind();
Assert.AreEqual(0, stmt.PageSize);
Assert.Null(stmt.ConsistencyLevel);
var queryOptions = new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum).SetPageSize(100);
var request = (ExecuteRequest)RequestHandler.GetRequest(stmt, Serializer, GetRequestOptions(queryOptions));
Assert.AreEqual(100, request.PageSize);
Assert.AreEqual(queryOptions.GetPageSize(), request.PageSize);
Assert.AreEqual(queryOptions.GetConsistencyLevel(), request.Consistency);
Assert.AreEqual(QueryOptions.DefaultSerialConsistencyLevel, request.SerialConsistency);
}
[Test]
[TestCase(ProtocolVersion.V5)]
[TestCase(ProtocolVersion.DseV2)]
[TestCase(ProtocolVersion.V4)]
[TestCase(ProtocolVersion.V3)]
[TestCase(ProtocolVersion.V2)]
[TestCase(ProtocolVersion.V1)]
public void Should_NotSkipMetadata_When_BoundStatementDoesNotContainColumnDefinitions(ProtocolVersion version)
{
var serializerManager = new SerializerManager(version);
var ps = GetPrepared(serializerManager: serializerManager);
var stmt = ps.Bind();
var queryOptions = new QueryOptions();
var request = (ExecuteRequest)RequestHandler.GetRequest(stmt, serializerManager.GetCurrentSerializer(), GetRequestOptions(queryOptions));
Assert.IsFalse(request.SkipMetadata);
}
[Test]
[TestCase(ProtocolVersion.V5, true)]
[TestCase(ProtocolVersion.DseV2, true)]
[TestCase(ProtocolVersion.V4, false)]
[TestCase(ProtocolVersion.V3, false)]
[TestCase(ProtocolVersion.V2, false)]
[TestCase(ProtocolVersion.V1, false)]
public void Should_SkipMetadata_When_BoundStatementContainsColumnDefinitionsAndProtocolSupportsNewResultMetadataId(
ProtocolVersion version, bool isSet)
{
var serializerManager = new SerializerManager(version);
var rsMetadata = new RowSetMetadata { Columns = new[] { new CqlColumn() } };
var ps = GetPrepared(new byte[16], serializerManager, rsMetadata);
var stmt = ps.Bind();
var queryOptions = new QueryOptions();
var request = (ExecuteRequest)RequestHandler.GetRequest(stmt, serializerManager.GetCurrentSerializer(), GetRequestOptions(queryOptions));
Assert.AreEqual(isSet, request.SkipMetadata);
}
[Test]
[TestCase(ProtocolVersion.V5)]
[TestCase(ProtocolVersion.DseV2)]
[TestCase(ProtocolVersion.V4)]
[TestCase(ProtocolVersion.V3)]
[TestCase(ProtocolVersion.V2)]
[TestCase(ProtocolVersion.V1)]
public void Should_SkipMetadata_When_NotBoundStatement(ProtocolVersion version)
{
var serializerManager = new SerializerManager(version);
var stmt = new SimpleStatement("DUMMY QUERY");
var queryOptions = new QueryOptions();
var request = (QueryRequest)RequestHandler.GetRequest(stmt, serializerManager.GetCurrentSerializer(), GetRequestOptions(queryOptions));
Assert.IsFalse(request.SkipMetadata);
}
[Test]
public void RequestHandler_GetRequest_BoundStatement_Statement_Level_Settings_Are_Used()
{
var ps = GetPrepared();
var stmt = ps.Bind();
stmt.SetConsistencyLevel(ConsistencyLevel.EachQuorum);
stmt.SetPageSize(350);
stmt.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
Assert.AreEqual(350, stmt.PageSize);
Assert.AreEqual(ConsistencyLevel.EachQuorum, stmt.ConsistencyLevel);
Assert.AreEqual(ConsistencyLevel.LocalSerial, stmt.SerialConsistencyLevel);
var request = (ExecuteRequest)RequestHandler.GetRequest(stmt, Serializer, GetRequestOptions());
Assert.AreEqual(350, request.PageSize);
Assert.AreEqual(ConsistencyLevel.EachQuorum, request.Consistency);
Assert.AreEqual(ConsistencyLevel.LocalSerial, request.SerialConsistency);
}
[Test]
public void RequestHandler_GetRequest_BatchStatement_Default_QueryOptions_Are_Used()
{
var stmt = new BatchStatement();
Assert.Null(stmt.ConsistencyLevel);
var request = (BatchRequest)RequestHandler.GetRequest(stmt, Serializer, GetRequestOptions());
Assert.AreEqual(DefaultQueryOptions.GetConsistencyLevel(), request.Consistency);
}
[Test]
public void RequestHandler_GetRequest_BatchStatement_QueryOptions_Are_Used()
{
var stmt = new BatchStatement();
Assert.Null(stmt.ConsistencyLevel);
var queryOptions = new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum);
var request = (BatchRequest)RequestHandler.GetRequest(stmt, Serializer, GetRequestOptions(queryOptions));
Assert.AreEqual(queryOptions.GetConsistencyLevel(), request.Consistency);
}
[Test]
public void RequestHandler_GetRequest_BatchStatement_Statement_Level_Settings_Are_Used()
{
var stmt = new BatchStatement();
stmt.SetConsistencyLevel(ConsistencyLevel.EachQuorum);
Assert.AreEqual(ConsistencyLevel.EachQuorum, stmt.ConsistencyLevel);
var request = (BatchRequest)RequestHandler.GetRequest(stmt, Serializer, GetRequestOptions());
Assert.AreEqual(ConsistencyLevel.EachQuorum, request.Consistency);
}
[Test]
public void RequestExecution_GetRetryDecision_Test()
{
var config = new Configuration();
var policy = Cassandra.Policies.DefaultRetryPolicy as IExtendedRetryPolicy;
var statement = new SimpleStatement("SELECT WILL FAIL");
//Using default retry policy the decision will always be to rethrow on read/write timeout
var expected = RetryDecision.RetryDecisionType.Rethrow;
var decision = GetRetryDecisionFromServerError(
new ReadTimeoutException(ConsistencyLevel.Quorum, 1, 2, true), policy, statement, config, 0);
Assert.AreEqual(expected, decision.DecisionType);
decision = GetRetryDecisionFromServerError(
new WriteTimeoutException(ConsistencyLevel.Quorum, 1, 2, "SIMPLE"), policy, statement, config, 0);
Assert.AreEqual(expected, decision.DecisionType);
decision = GetRetryDecisionFromServerError(
new UnavailableException(ConsistencyLevel.Quorum, 2, 1), policy, statement, config, 0);
Assert.AreEqual(expected, decision.DecisionType);
decision = GetRetryDecisionFromClientError(
new Exception(), policy, statement, config, 0);
Assert.AreEqual(expected, decision.DecisionType);
//Expecting to retry when a Cassandra node is Bootstrapping/overloaded
expected = RetryDecision.RetryDecisionType.Retry;
decision = GetRetryDecisionFromServerError(
new OverloadedException(null), policy, statement, config, 0);
Assert.AreEqual(expected, decision.DecisionType);
decision = GetRetryDecisionFromServerError(
new IsBootstrappingException(null), policy, statement, config, 0);
Assert.AreEqual(expected, decision.DecisionType);
decision = GetRetryDecisionFromServerError(
new TruncateException(null), policy, statement, config, 0);
Assert.AreEqual(expected, decision.DecisionType);
}
[Test]
public void GetRequest_With_Timestamp_Generator()
{
// Timestamp generator should be enabled by default
var statement = new SimpleStatement("QUERY");
var config = new Configuration();
var request = RequestHandler.GetRequest(statement, Serializer, config.DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The query request is composed by:
// <query><consistency><flags><result_page_size><paging_state><serial_consistency><timestamp>
var queryBuffer = BeConverter.GetBytes(statement.QueryString.Length)
.Concat(Encoding.UTF8.GetBytes(statement.QueryString))
.ToArray();
CollectionAssert.AreEqual(queryBuffer, bodyBuffer.Take(queryBuffer.Length));
// Skip the query and consistency (2)
var offset = queryBuffer.Length + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
Assert.True(flags.HasFlag(QueryFlags.PageSize));
Assert.False(flags.HasFlag(QueryFlags.Values));
Assert.False(flags.HasFlag(QueryFlags.WithPagingState));
Assert.False(flags.HasFlag(QueryFlags.SkipMetadata));
Assert.True(flags.HasFlag(QueryFlags.WithSerialConsistency));
// Skip result_page_size (4) + serial_consistency (2)
offset += 6;
var timestamp = BeConverter.ToInt64(bodyBuffer, offset);
var expectedTimestamp = TypeSerializer.SinceUnixEpoch(DateTimeOffset.Now.Subtract(TimeSpan.FromMilliseconds(100))).Ticks / 10;
Assert.Greater(timestamp, expectedTimestamp);
}
[Test]
public void GetRequest_With_Timestamp_Generator_Empty_Value()
{
var statement = new SimpleStatement("QUERY");
var policies = new Cassandra.Policies(
Cassandra.Policies.DefaultLoadBalancingPolicy, Cassandra.Policies.DefaultReconnectionPolicy,
Cassandra.Policies.DefaultRetryPolicy, Cassandra.Policies.DefaultSpeculativeExecutionPolicy,
new NoTimestampGenerator());
var config = RequestHandlerTests.GetConfig(new QueryOptions(), policies, PoolingOptions.Create());
var request = RequestHandler.GetRequest(
statement, RequestHandlerTests.Serializer, config.DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The query request is composed by:
// <query><consistency><flags><result_page_size><paging_state><serial_consistency><timestamp>
var queryBuffer = BeConverter.GetBytes(statement.QueryString.Length)
.Concat(Encoding.UTF8.GetBytes(statement.QueryString))
.ToArray();
CollectionAssert.AreEqual(queryBuffer, bodyBuffer.Take(queryBuffer.Length));
// Skip the query and consistency (2)
var offset = queryBuffer.Length + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.False(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
Assert.True(flags.HasFlag(QueryFlags.PageSize));
Assert.False(flags.HasFlag(QueryFlags.Values));
Assert.False(flags.HasFlag(QueryFlags.WithPagingState));
Assert.False(flags.HasFlag(QueryFlags.SkipMetadata));
Assert.True(flags.HasFlag(QueryFlags.WithSerialConsistency));
}
[Test]
public void GetRequest_With_Timestamp_Generator_Empty_Value_With_Statement_Timestamp()
{
var statement = new SimpleStatement("STATEMENT WITH TIMESTAMP");
var expectedTimestamp = new DateTimeOffset(2010, 04, 29, 1, 2, 3, 4, TimeSpan.Zero).AddTicks(20);
statement.SetTimestamp(expectedTimestamp);
var policies = new Cassandra.Policies(
Cassandra.Policies.DefaultLoadBalancingPolicy, Cassandra.Policies.DefaultReconnectionPolicy,
Cassandra.Policies.DefaultRetryPolicy, Cassandra.Policies.DefaultSpeculativeExecutionPolicy,
new NoTimestampGenerator());
var config = RequestHandlerTests.GetConfig(new QueryOptions(), policies, PoolingOptions.Create());
var request = RequestHandler.GetRequest(statement, Serializer, config.DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The query request is composed by:
// <query><consistency><flags><result_page_size><paging_state><serial_consistency><timestamp>
var queryBuffer = BeConverter.GetBytes(statement.QueryString.Length)
.Concat(Encoding.UTF8.GetBytes(statement.QueryString))
.ToArray();
CollectionAssert.AreEqual(queryBuffer, bodyBuffer.Take(queryBuffer.Length));
// Skip the query and consistency (2)
var offset = queryBuffer.Length + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
Assert.True(flags.HasFlag(QueryFlags.PageSize));
// Skip result_page_size (4) + serial_consistency (2)
offset += 6;
var timestamp = BeConverter.ToInt64(bodyBuffer, offset);
Assert.AreEqual(TypeSerializer.SinceUnixEpoch(expectedTimestamp).Ticks / 10, timestamp);
}
[Test]
public void GetRequest_Batch_With_64K_Queries()
{
var batch = new BatchStatement();
for (var i = 0; i < ushort.MaxValue; i++)
{
batch.Add(new SimpleStatement("QUERY"));
}
var config = RequestHandlerTests.GetConfig(new QueryOptions(), Cassandra.Policies.DefaultPolicies, PoolingOptions.Create());
var request = RequestHandler.GetRequest(batch, Serializer, config.DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The batch request is composed by:
// <type><n><query_1>...<query_n><consistency><flags>[<serial_consistency>][<timestamp>]
CollectionAssert.AreEqual(new byte[] { 0xff, 0xff }, bodyBuffer.Skip(1).Take(2));
}
[Test]
public void GetRequest_Batch_With_Timestamp_Generator()
{
var batch = new BatchStatement();
batch.Add(new SimpleStatement("QUERY"));
var startDate = DateTimeOffset.Now;
// To microsecond precision
startDate = startDate.Subtract(TimeSpan.FromTicks(startDate.Ticks % 10));
var config = RequestHandlerTests.GetConfig(new QueryOptions(), Cassandra.Policies.DefaultPolicies, PoolingOptions.Create());
var request = RequestHandler.GetRequest(batch, Serializer, config.DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The batch request is composed by:
// <type><n><query_1>...<query_n><consistency><flags>[<serial_consistency>][<timestamp>]
var offset = 1;
// n = 1
Assert.AreEqual(1, BeConverter.ToInt16(bodyBuffer, offset));
// Query_1 <kind><string><n_params>
offset += 2;
// kind = 0, not prepared
Assert.AreEqual(0, bodyBuffer[offset++]);
var queryLength = BeConverter.ToInt32(bodyBuffer, offset);
Assert.AreEqual(5, queryLength);
// skip query, n_params and consistency
offset += 4 + queryLength + 2 + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
// Skip serial consistency
offset += 2;
var timestamp = TypeSerializer.UnixStart.AddTicks(BeConverter.ToInt64(bodyBuffer, offset) * 10);
Assert.GreaterOrEqual(timestamp, startDate);
Assert.LessOrEqual(timestamp, DateTimeOffset.Now.Add(TimeSpan.FromMilliseconds(100)));
}
[Test]
public void GetRequest_Batch_With_Empty_Timestamp_Generator()
{
var batch = new BatchStatement();
batch.Add(new SimpleStatement("QUERY"));
var policies = new Cassandra.Policies(
Cassandra.Policies.DefaultLoadBalancingPolicy, Cassandra.Policies.DefaultReconnectionPolicy,
Cassandra.Policies.DefaultRetryPolicy, Cassandra.Policies.DefaultSpeculativeExecutionPolicy,
new NoTimestampGenerator());
var config = RequestHandlerTests.GetConfig(new QueryOptions(), policies, PoolingOptions.Create());
var request = RequestHandler.GetRequest(batch, Serializer, config.DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The batch request is composed by:
// <type><n><query_1>...<query_n><consistency><flags>[<serial_consistency>][<timestamp>]
var offset = 1 + 2 + 1;
var queryLength = BeConverter.ToInt32(bodyBuffer, offset);
Assert.AreEqual(5, queryLength);
// skip query, n_params and consistency
offset += 4 + queryLength + 2 + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.False(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
// Only serial consistency left
Assert.AreEqual(bodyBuffer.Length, offset + 2);
}
[Test]
public void GetRequest_Batch_With_Provided_Timestamp()
{
var batch = new BatchStatement();
batch.Add(new SimpleStatement("QUERY"));
var providedTimestamp = DateTimeOffset.Now;
// To microsecond precision
providedTimestamp = providedTimestamp.Subtract(TimeSpan.FromTicks(providedTimestamp.Ticks % 10));
batch.SetTimestamp(providedTimestamp);
var config = RequestHandlerTests.GetConfig(new QueryOptions(), Cassandra.Policies.DefaultPolicies, PoolingOptions.Create());
var request = RequestHandler.GetRequest(batch, Serializer, config.DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The batch request is composed by:
// <type><n><query_1>...<query_n><consistency><flags>[<serial_consistency>][<timestamp>]
var offset = 1 + 2 + 1;
var queryLength = BeConverter.ToInt32(bodyBuffer, offset);
Assert.AreEqual(5, queryLength);
// skip query, n_params and consistency
offset += 4 + queryLength + 2 + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
// Skip serial consistency
offset += 2;
var timestamp = TypeSerializer.UnixStart.AddTicks(BeConverter.ToInt64(bodyBuffer, offset) * 10);
Assert.AreEqual(providedTimestamp, timestamp);
}
[Test]
public void GetRequest_Batch_With_Provided_Keyspace()
{
const string keyspace = "test_keyspace";
var batch = new BatchStatement();
batch.Add(new SimpleStatement("QUERY")).SetKeyspace(keyspace);
var request = RequestHandler.GetRequest(batch, Serializer, new Configuration().DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The batch request is composed by:
// <type><n><query_1>...<query_n><consistency><flags>[<serial_consistency>][<timestamp>][<keyspace>]
var offset = 1 + 2 + 1;
var queryLength = BeConverter.ToInt32(bodyBuffer, offset);
Assert.AreEqual(5, queryLength);
// skip query, n_params and consistency
offset += 4 + queryLength + 2 + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.True(flags.HasFlag(QueryFlags.WithKeyspace));
// Skip serial consistency and timestamp
offset +=
(flags.HasFlag(QueryFlags.WithSerialConsistency) ? 2 : 0) +
(flags.HasFlag(QueryFlags.WithDefaultTimestamp) ? 8 : 0);
var keyspaceLength = BeConverter.ToInt16(bodyBuffer, offset);
offset += 2;
Assert.AreEqual(keyspace, Encoding.UTF8.GetString(bodyBuffer, offset, keyspaceLength));
}
[Test]
public void GetRequest_Batch_With_Provided_Keyspace_On_Older_Protocol_Versions_Should_Ignore()
{
var batch = new BatchStatement();
batch.Add(new SimpleStatement("QUERY")).SetKeyspace("test_keyspace");
var serializer = new SerializerManager(ProtocolVersion.V3).GetCurrentSerializer();
var request = RequestHandler.GetRequest(batch, serializer, new Configuration().DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request, serializer);
// The batch request is composed by:
// <type><n><query_1>...<query_n><consistency><flags>[<serial_consistency>][<timestamp>][<keyspace>]
var offset = 1 + 2 + 1;
var queryLength = BeConverter.ToInt32(bodyBuffer, offset);
Assert.AreEqual(5, queryLength);
// skip query, n_params and consistency
offset += 4 + queryLength + 2 + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.False(flags.HasFlag(QueryFlags.WithKeyspace));
}
[Test]
public void GetRequest_Batch_With_SerialConsistency_On_Older_Protocol_Versions_Should_Ignore()
{
const string query = "QUERY";
var batch = new BatchStatement();
batch.Add(new SimpleStatement(query))
.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
var serializer = new SerializerManager(ProtocolVersion.V2).GetCurrentSerializer();
var request = RequestHandler.GetRequest(batch, serializer, new Configuration().DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request, serializer);
// The batch request on protocol 2 is composed by:
// <type><n><query_1>...<query_n><consistency>
const int queryOffSet = 1 + 2 + 1;
var queryLength = BeConverter.ToInt32(bodyBuffer, queryOffSet);
Assert.AreEqual(query.Length, queryLength);
// query, n_params and consistency
Assert.AreEqual(4 + 4 + queryLength + 2 + 2, bodyBuffer.Length);
}
[Test]
public void GetRequest_Batch_Should_Use_Serial_Consistency_From_QueryOptions()
{
const string query = "QUERY";
var batch = new BatchStatement();
batch.Add(new SimpleStatement(query));
const ConsistencyLevel expectedSerialConsistencyLevel = ConsistencyLevel.LocalSerial;
var config = new Configuration();
config.QueryOptions.SetSerialConsistencyLevel(expectedSerialConsistencyLevel);
AssertBatchSerialConsistencyLevel(batch, config, query, expectedSerialConsistencyLevel);
}
[Test]
public void GetRequest_Batch_Should_Use_Serial_Consistency_From_Statement()
{
const ConsistencyLevel expectedSerialConsistencyLevel = ConsistencyLevel.LocalSerial;
const string query = "QUERY";
var batch = new BatchStatement();
batch.Add(new SimpleStatement(query))
.SetSerialConsistencyLevel(expectedSerialConsistencyLevel);
var config = new Configuration();
config.QueryOptions.SetSerialConsistencyLevel(ConsistencyLevel.Serial);
AssertBatchSerialConsistencyLevel(batch, config, query, expectedSerialConsistencyLevel);
}
[Test]
public void GetRequest_Execute_Should_Use_Serial_Consistency_From_Statement()
{
const ConsistencyLevel expectedSerialConsistencyLevel = ConsistencyLevel.Serial;
var ps = GetPrepared(queryId: new byte[16]);
var statement = ps.Bind().SetSerialConsistencyLevel(expectedSerialConsistencyLevel);
var config = new Configuration();
config.QueryOptions.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
var request = RequestHandler.GetRequest(statement, Serializer, config.DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The execute request is composed by:
// <query_id><consistency><flags><result_page_size><paging_state><serial_consistency><timestamp>
// Skip the queryid and consistency (2)
var offset = 2 + ps.Id.Length + 2;
if (Serializer.ProtocolVersion.SupportsResultMetadataId())
{
// Short bytes: 2 + 16
offset += 18;
}
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
Assert.True(flags.HasFlag(QueryFlags.PageSize));
Assert.True(flags.HasFlag(QueryFlags.WithSerialConsistency));
// Skip result_page_size (4)
offset += 4;
Assert.That((ConsistencyLevel)BeConverter.ToInt16(bodyBuffer, offset), Is.EqualTo(expectedSerialConsistencyLevel));
}
[Test]
public void GetRequest_Execute_Should_Use_Serial_Consistency_From_QueryOptions()
{
const ConsistencyLevel expectedSerialConsistencyLevel = ConsistencyLevel.LocalSerial;
var ps = GetPrepared(queryId: new byte[16]);
var statement = ps.Bind();
var config = new Configuration();
config.QueryOptions.SetSerialConsistencyLevel(expectedSerialConsistencyLevel);
var request = RequestHandler.GetRequest(statement, Serializer, config.DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The execute request is composed by:
// <query_id><consistency><flags><result_page_size><paging_state><serial_consistency><timestamp>
// Skip the queryid and consistency (2)
var offset = 2 + ps.Id.Length + 2;
if (Serializer.ProtocolVersion.SupportsResultMetadataId())
{
// Short bytes: 2 + 16
offset += 18;
}
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
Assert.True(flags.HasFlag(QueryFlags.PageSize));
Assert.True(flags.HasFlag(QueryFlags.WithSerialConsistency));
// Skip result_page_size (4)
offset += 4;
Assert.That((ConsistencyLevel)BeConverter.ToInt16(bodyBuffer, offset), Is.EqualTo(expectedSerialConsistencyLevel));
}
[Test]
public void GetRequest_Query_Should_Use_Serial_Consistency_From_Statement()
{
const ConsistencyLevel expectedSerialConsistencyLevel = ConsistencyLevel.LocalSerial;
var statement = new SimpleStatement("QUERY");
statement.SetSerialConsistencyLevel(expectedSerialConsistencyLevel);
var config = new Configuration();
config.QueryOptions.SetSerialConsistencyLevel(ConsistencyLevel.Serial);
var request = RequestHandler.GetRequest(statement, Serializer, config.DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The query request is composed by:
// <query><consistency><flags><result_page_size><paging_state><serial_consistency><timestamp>
// Skip the query and consistency (2)
var offset = 4 + statement.QueryString.Length + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
Assert.True(flags.HasFlag(QueryFlags.PageSize));
// Skip result_page_size (4)
offset += 4;
Assert.That((ConsistencyLevel)BeConverter.ToInt16(bodyBuffer, offset), Is.EqualTo(expectedSerialConsistencyLevel));
}
[Test]
public void GetRequest_Query_Should_Use_Provided_Keyspace()
{
const string keyspace = "my_keyspace";
var statement = new SimpleStatement("QUERY").SetKeyspace(keyspace);
var request = RequestHandler.GetRequest(statement, Serializer, new Configuration().DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The query request is composed by:
// <consistency><flags>[<n>[name_1]<value_1>...[name_n]<value_n>][<result_page_size>][<paging_state>]
// [<serial_consistency>][<timestamp>][<keyspace>][continuous_paging_options]
// Skip the query and consistency (2)
var offset = 4 + statement.QueryString.Length + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
offset +=
(flags.HasFlag(QueryFlags.WithDefaultTimestamp) ? 8 : 0) +
(flags.HasFlag(QueryFlags.PageSize) ? 4 : 0) +
(flags.HasFlag(QueryFlags.WithSerialConsistency) ? 2 : 0);
var keyspaceLength = BeConverter.ToInt16(bodyBuffer, offset);
offset += 2;
Assert.AreEqual(keyspace, Encoding.UTF8.GetString(bodyBuffer, offset, keyspaceLength));
}
[Test]
public void GetRequest_Query_With_Keyspace_On_Lower_Protocol_Version_Should_Ignore_Keyspace()
{
var statement = new SimpleStatement("QUERY").SetKeyspace("my_keyspace");
var serializer = new SerializerManager(ProtocolVersion.V3).GetCurrentSerializer();
var request = RequestHandler.GetRequest(statement, serializer, new Configuration().DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request, serializer);
// The query request is composed by:
// <consistency><flags>[<n>[name_1]<value_1>...[name_n]<value_n>][<result_page_size>][<paging_state>]
// [<serial_consistency>][<timestamp>][<keyspace>][continuous_paging_options]
// Skip the query and consistency (2)
var offset = 4 + statement.QueryString.Length + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.False(flags.HasFlag(QueryFlags.WithKeyspace));
}
[Test]
public void GetRequest_Query_Should_Use_Serial_Consistency_From_QueryOptions()
{
const ConsistencyLevel expectedSerialConsistencyLevel = ConsistencyLevel.LocalSerial;
var statement = new SimpleStatement("QUERY");
var config = new Configuration();
config.QueryOptions.SetSerialConsistencyLevel(expectedSerialConsistencyLevel);
var request = RequestHandler.GetRequest(statement, Serializer, config.DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The query request is composed by:
// <query><consistency><flags><result_page_size><paging_state><serial_consistency><timestamp>
// Skip the query and consistency (2)
var offset = 4 + statement.QueryString.Length + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
Assert.True(flags.HasFlag(QueryFlags.PageSize));
Assert.True(flags.HasFlag(QueryFlags.WithSerialConsistency));
// Skip result_page_size (4)
offset += 4;
Assert.That((ConsistencyLevel)BeConverter.ToInt16(bodyBuffer, offset), Is.EqualTo(expectedSerialConsistencyLevel));
}
[Test]
public void Prepare_With_Keyspace_Should_Send_Keyspace_And_Flag()
{
const string query = "QUERY1";
const string keyspace = "ks1";
var request = new PrepareRequest(RequestHandlerTests.Serializer, query, keyspace, null);
// The request is composed by: <query><flags>[<keyspace>]
var buffer = GetBodyBuffer(request);
var queryLength = BeConverter.ToInt32(buffer);
Assert.AreEqual(query.Length, queryLength);
var offset = 4 + queryLength;
var flags = (PrepareFlags)BeConverter.ToInt32(buffer, offset);
offset += 4;
Assert.True(flags.HasFlag(PrepareFlags.WithKeyspace));
var keyspaceLength = BeConverter.ToInt16(buffer, offset);
offset += 2;
Assert.AreEqual(keyspace.Length, keyspaceLength);
Assert.AreEqual(keyspace, Encoding.UTF8.GetString(buffer.Skip(offset).Take(keyspaceLength).ToArray()));
}
[Test]
public void Prepare_With_Keyspace_On_Lower_Protocol_Version_Should_Ignore_Keyspace()
{
const string query = "SELECT col1, col2 FROM table1";
var serializer = new SerializerManager(ProtocolVersion.V2).GetCurrentSerializer();
var request = new PrepareRequest(serializer, query, "my_keyspace", null);
// The request only contains the query
var buffer = GetBodyBuffer(request, serializer);
var queryLength = BeConverter.ToInt32(buffer);
Assert.AreEqual(query.Length, queryLength);
Assert.AreEqual(4 + queryLength, buffer.Length);
}
private static byte[] GetBodyBuffer(IRequest request, ISerializer serializer = null)
{
if (serializer == null)
{
serializer = Serializer;
}
var stream = new MemoryStream();
request.WriteFrame(1, stream, serializer);
var headerSize = serializer.ProtocolVersion.GetHeaderSize();
var bodyBuffer = new byte[stream.Length - headerSize];
stream.Position = headerSize;
stream.Read(bodyBuffer, 0, bodyBuffer.Length);
return bodyBuffer;
}
private static void AssertBatchSerialConsistencyLevel(BatchStatement batch, Configuration config, string query,
ConsistencyLevel expectedSerialConsistencyLevel)
{
var request = RequestHandler.GetRequest(batch, Serializer, config.DefaultRequestOptions);
var bodyBuffer = GetBodyBuffer(request);
// The batch request is composed by:
// <type><n><query_1>...<query_n><consistency><flags>[<serial_consistency>][<timestamp>]
// Skip query, n_params and consistency
var offset = 1 + 2 + 1 + 4 + query.Length + 2 + 2;
var flags = GetQueryFlags(bodyBuffer, ref offset);
Assert.True(flags.HasFlag(QueryFlags.WithSerialConsistency));
Assert.That((ConsistencyLevel)BeConverter.ToInt16(bodyBuffer, offset), Is.EqualTo(expectedSerialConsistencyLevel));
}
private static QueryFlags GetQueryFlags(byte[] bodyBuffer, ref int offset, ISerializer serializer = null)
{
if (serializer == null)
{
serializer = Serializer;
}
QueryFlags flags;
if (serializer.ProtocolVersion.Uses4BytesQueryFlags())
{
flags = (QueryFlags)BeConverter.ToInt32(bodyBuffer, offset);
offset += 4;
}
else
{
flags = (QueryFlags)bodyBuffer[offset++];
}
return flags;
}
internal static RetryDecision GetRetryDecisionFromServerError(Exception ex, IExtendedRetryPolicy policy, IStatement statement, Configuration config, int retryCount)
{
return RequestExecution.GetRetryDecisionWithReason(RequestError.CreateServerError(ex), policy, statement, config, retryCount).Decision;
}
internal static RetryDecision GetRetryDecisionFromClientError(Exception ex, IExtendedRetryPolicy policy, IStatement statement, Configuration config, int retryCount)
{
return RequestExecution.GetRetryDecisionWithReason(RequestError.CreateClientError(ex, false), policy, statement, config, retryCount).Decision;
}
/// <summary>
/// A timestamp generator that generates empty values
/// </summary>
private class NoTimestampGenerator : ITimestampGenerator
{
public long Next()
{
return long.MinValue;
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QuantConnect.Data;
using System.Collections.Concurrent;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
namespace QuantConnect.Securities
{
/// <summary>
/// Provides a means of keeping track of the different cash holdings of an algorithm
/// </summary>
public class CashBook : IDictionary<string, Cash>, ICurrencyConverter
{
/// <summary>
/// Gets the base currency used
/// </summary>
public const string AccountCurrency = "USD";
private readonly ConcurrentDictionary<string, Cash> _currencies;
/// <summary>
/// Gets the total value of the cash book in units of the base currency
/// </summary>
public decimal TotalValueInAccountCurrency
{
get { return _currencies.Sum(x => x.Value.ValueInAccountCurrency); }
}
/// <summary>
/// Initializes a new instance of the <see cref="CashBook"/> class.
/// </summary>
public CashBook()
{
_currencies = new ConcurrentDictionary<string, Cash>();
_currencies.AddOrUpdate(AccountCurrency, new Cash(AccountCurrency, 0, 1.0m));
}
/// <summary>
/// Adds a new cash of the specified symbol and quantity
/// </summary>
/// <param name="symbol">The symbol used to reference the new cash</param>
/// <param name="quantity">The amount of new cash to start</param>
/// <param name="conversionRate">The conversion rate used to determine the initial
/// portfolio value/starting capital impact caused by this currency position.</param>
public void Add(string symbol, decimal quantity, decimal conversionRate)
{
var cash = new Cash(symbol, quantity, conversionRate);
_currencies.AddOrUpdate(symbol, cash);
}
/// <summary>
/// Checks the current subscriptions and adds necessary currency pair feeds to provide real time conversion data
/// </summary>
/// <param name="securities">The SecurityManager for the algorithm</param>
/// <param name="subscriptions">The SubscriptionManager for the algorithm</param>
/// <param name="marketMap">The market map that decides which market the new security should be in</param>
/// <param name="changes">Will be used to consume <see cref="SecurityChanges.AddedSecurities"/></param>
/// <param name="securityService">Will be used to create required new <see cref="Security"/></param>
/// <returns>Returns a list of added currency <see cref="SubscriptionDataConfig"/></returns>
public List<SubscriptionDataConfig> EnsureCurrencyDataFeeds(SecurityManager securities,
SubscriptionManager subscriptions,
IReadOnlyDictionary<SecurityType, string> marketMap,
SecurityChanges changes,
ISecurityService securityService)
{
var addedSubscriptionDataConfigs = new List<SubscriptionDataConfig>();
foreach (var kvp in _currencies)
{
var cash = kvp.Value;
var subscriptionDataConfig = cash.EnsureCurrencyDataFeed(securities, subscriptions, marketMap, changes, securityService);
if (subscriptionDataConfig != null)
{
addedSubscriptionDataConfigs.Add(subscriptionDataConfig);
}
}
return addedSubscriptionDataConfigs;
}
/// <summary>
/// Converts a quantity of source currency units into the specified destination currency
/// </summary>
/// <param name="sourceQuantity">The quantity of source currency to be converted</param>
/// <param name="sourceCurrency">The source currency symbol</param>
/// <param name="destinationCurrency">The destination currency symbol</param>
/// <returns>The converted value</returns>
public decimal Convert(decimal sourceQuantity, string sourceCurrency, string destinationCurrency)
{
var source = this[sourceCurrency];
var destination = this[destinationCurrency];
if (source.ConversionRate == 0)
{
throw new Exception($"The conversion rate for {sourceCurrency} is not available.");
}
if (destination.ConversionRate == 0)
{
throw new Exception($"The conversion rate for {destinationCurrency} is not available.");
}
var conversionRate = source.ConversionRate / destination.ConversionRate;
return sourceQuantity * conversionRate;
}
/// <summary>
/// Converts a quantity of source currency units into the account currency
/// </summary>
/// <param name="sourceQuantity">The quantity of source currency to be converted</param>
/// <param name="sourceCurrency">The source currency symbol</param>
/// <returns>The converted value</returns>
public decimal ConvertToAccountCurrency(decimal sourceQuantity, string sourceCurrency)
{
return Convert(sourceQuantity, sourceCurrency, AccountCurrency);
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine(string.Format("{0} {1,13} {2,10} = {3}", "Symbol", "Quantity", "Conversion", "Value in " + AccountCurrency));
foreach (var value in _currencies.Select(x => x.Value))
{
sb.AppendLine(value.ToString());
}
sb.AppendLine("-------------------------------------------------");
sb.AppendLine(string.Format("CashBook Total Value: {0}{1}",
Currencies.GetCurrencySymbol(AccountCurrency),
Math.Round(TotalValueInAccountCurrency, 2))
);
return sb.ToString();
}
#region IDictionary Implementation
/// <summary>
/// Gets the count of Cash items in this CashBook.
/// </summary>
/// <value>The count.</value>
public int Count => _currencies.Skip(0).Count();
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value>
public bool IsReadOnly
{
get { return ((IDictionary<string, Cash>) _currencies).IsReadOnly; }
}
/// <summary>
/// Add the specified item to this CashBook.
/// </summary>
/// <param name="item">KeyValuePair of symbol -> Cash item</param>
public void Add(KeyValuePair<string, Cash> item)
{
_currencies.AddOrUpdate(item.Key, item.Value);
}
/// <summary>
/// Add the specified key and value.
/// </summary>
/// <param name="symbol">The symbol of the Cash value.</param>
/// <param name="value">Value.</param>
public void Add(string symbol, Cash value)
{
_currencies.AddOrUpdate(symbol, value);
}
/// <summary>
/// Clear this instance of all Cash entries.
/// </summary>
public void Clear()
{
_currencies.Clear();
}
/// <summary>
/// Remove the Cash item corresponding to the specified symbol
/// </summary>
/// <param name="symbol">The symbolto be removed</param>
public bool Remove(string symbol)
{
Cash cash = null;
var removed = _currencies.TryRemove(symbol, out cash);
if (!removed)
{
Log.Error(string.Format("CashBook.Remove(): Failed to remove the cash book record for symbol {0}", symbol));
}
return removed;
}
/// <summary>
/// Remove the specified item.
/// </summary>
/// <param name="item">Item.</param>
public bool Remove(KeyValuePair<string, Cash> item)
{
Cash cash = null;
var removed = _currencies.TryRemove(item.Key, out cash);
if (!removed)
{
Log.Error(string.Format("CashBook.Remove(): Failed to remove the cash book record for symbol {0} - {1}", item.Key, item.Value != null ? item.Value.ToString() : "(null)"));
}
return removed;
}
/// <summary>
/// Determines whether the current instance contains an entry with the specified symbol.
/// </summary>
/// <returns><c>true</c>, if key was contained, <c>false</c> otherwise.</returns>
/// <param name="symbol">Key.</param>
public bool ContainsKey(string symbol)
{
return _currencies.ContainsKey(symbol);
}
/// <summary>
/// Try to get the value.
/// </summary>
/// <remarks>To be added.</remarks>
/// <returns><c>true</c>, if get value was tryed, <c>false</c> otherwise.</returns>
/// <param name="symbol">The symbol.</param>
/// <param name="value">Value.</param>
public bool TryGetValue(string symbol, out Cash value)
{
return _currencies.TryGetValue(symbol, out value);
}
/// <summary>
/// Determines whether the current collection contains the specified value.
/// </summary>
/// <param name="item">Item.</param>
public bool Contains(KeyValuePair<string, Cash> item)
{
return _currencies.Contains(item);
}
/// <summary>
/// Copies to the specified array.
/// </summary>
/// <param name="array">Array.</param>
/// <param name="arrayIndex">Array index.</param>
public void CopyTo(KeyValuePair<string, Cash>[] array, int arrayIndex)
{
((IDictionary<string, Cash>) _currencies).CopyTo(array, arrayIndex);
}
/// <summary>
/// Gets or sets the <see cref="QuantConnect.Securities.Cash"/> with the specified symbol.
/// </summary>
/// <param name="symbol">Symbol.</param>
public Cash this[string symbol]
{
get
{
Cash cash;
if (!_currencies.TryGetValue(symbol, out cash))
{
throw new Exception("This cash symbol (" + symbol + ") was not found in your cash book.");
}
return cash;
}
set
{
_currencies[symbol] = value;
}
}
/// <summary>
/// Gets the keys.
/// </summary>
/// <value>The keys.</value>
public ICollection<string> Keys => _currencies.Select(x => x.Key).ToList();
/// <summary>
/// Gets the values.
/// </summary>
/// <value>The values.</value>
public ICollection<Cash> Values => _currencies.Select(x => x.Value).ToList();
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<KeyValuePair<string, Cash>> GetEnumerator()
{
return _currencies.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) _currencies).GetEnumerator();
}
#endregion
#region ICurrencyConverter Implementation
/// <summary>
/// Converts a cash amount to the account currency
/// </summary>
/// <param name="cashAmount">The <see cref="CashAmount"/> instance to convert</param>
/// <returns>A new <see cref="CashAmount"/> instance denominated in the account currency</returns>
public CashAmount ConvertToAccountCurrency(CashAmount cashAmount)
{
if (cashAmount.Currency == AccountCurrency)
{
return cashAmount;
}
var amount = Convert(cashAmount.Amount, cashAmount.Currency, AccountCurrency);
return new CashAmount(amount, AccountCurrency, this);
}
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
namespace GuruComponents.Netrix.HelpLine
{
/// <summary>
/// Properties for HelpLine Extender Provider.
/// </summary>
/// <remarks>
/// In code, you can set the properties that way:
/// <code>
/// // Prepare Properties
/// hp1.Active = true;
/// hp1.LineColor = Color.Blue;
/// hp1.CrossEnabled = false;
/// hp1.LineYEnabled = false;
/// hp1.LineXEnabled = false;
/// hp1.SnapElements = false;
/// hp1.SnapOnResize = false;
/// hp1.SnapEnabled = false;
/// hp1.X = (int)(210/25.4)*DPI;
/// // Create extender
/// this.helpLineA4 = new HelpLine(this.components);
/// // hook events (optional)
/// this.helpLineA4.HelpLineMoving += new HelpLineMoving(this.helpLineA4_HelpLineMoving);
/// this.helpLineA4.HelpLineMoved += new HelpLineMoved(this.helpLineA4_HelpLineMoved);
/// // Assign properties and editor
/// this.helpLineA4.SetHelpLine(this.htmlEditor, hp1);
/// // ... some more code
/// </code>
/// <para>
/// This way you have to create one <see cref="HelpLine"/> object per line (in fact, it's a pair of line). This can be assigned
/// to one or more editor controls. This means, if you need four editors, each with two lines, you need to create exactly two
/// <see cref="HelpLine"/> extenders, assigned to each of the four editors. The extender can manage the properties for such an
/// multiple assignment.
/// </para>
/// <para>
/// Finally, you can change the properties on the fly. This needs access to the assigned properties. Therefore, you cannot
/// access the (in the example above) <c>h1</c> variable. Instead, you must retrieve the assigned version:
/// <code>
/// helpLineA4.GetHelpLine(htmlEditor).LineXEnabled = true;
/// </code>
/// You may also 'refresh' your local property object from extender:
/// <code>
/// h1 = helpLineA4.GetHelpLine(htmlEditor);
/// h1.LineColor = Color.Red;
/// // ... more properties
/// </code>
/// </para>
/// </remarks>
[Serializable()]
public class HelpLineProperties
{
private bool active;
private bool crossEnabled;
private int snapZone;
private bool snapEnabled;
private bool snapOnResize;
private int snapgrid;
private bool snapelements;
private bool lineXEnabled;
private bool lineYEnabled;
private int x;
private int y;
private Color color;
private int width;
private System.Drawing.Drawing2D.DashStyle dash;
private bool lineVisible;
[NonSerialized()]
private HelpLineBehavior behavior;
/// <summary>
/// Ctor for properties.
/// </summary>
public HelpLineProperties()
{
active = true;
crossEnabled = true;
snapOnResize = true;
snapEnabled = true;
snapZone = 12;
snapgrid = 16;
snapelements = true;
lineXEnabled = true;
lineYEnabled = true;
x = 100;
y = 100;
color = Color.Blue;
lineVisible = true;
width = 1;
dash = System.Drawing.Drawing2D.DashStyle.Solid;
}
/// <summary>
/// Supports propertygrid
/// </summary>
/// <returns></returns>
public override string ToString()
{
int props = 0;
props += (active == false) ? 0 : 1;
props += (crossEnabled == true) ? 0 : 1;
props += (snapOnResize == true) ? 0 : 1;
props += (snapEnabled == true) ? 0 : 1;
props += (snapZone == 12) ? 0 : 1;
props += (snapgrid == 16) ? 0 : 1;
props += (snapelements == true) ? 0 : 1;
props += (lineXEnabled == true) ? 0 : 1;
props += (lineYEnabled == true) ? 0 : 1;
props += (x == 100) ? 0 : 1;
props += (y == 100) ? 0 : 1;
props += (color == Color.Blue) ? 0 : 1;
props += (lineVisible == true) ? 0 : 1;
props += (width == 1) ? 0 : 1;
props += (dash == System.Drawing.Drawing2D.DashStyle.Solid) ? 0 : 1;
return String.Format("{0} {1} changed", props, (props == 1) ? "property" : "properties");
}
internal void SetBehaviorReference(HelpLineBehavior behavior)
{
this.behavior = behavior;
}
/// <summary>
/// Current status of the event management.
/// </summary>
/// <remarks>
/// By default the helpline is active. If this property is set to <c>false</c> the control stops firing events and receiving mouse control.
/// The user is no longer able to move the helpline around. The helpline remains visible.
/// </remarks>
/// <seealso cref="LineVisible"/>
[Category("Behavior"), DefaultValue(true)]
public bool Active
{
get
{
return active;
}
set
{
active = value;
}
}
/// <summary>
/// Current X position in pixel.
/// </summary>
[Category("Behavior"), DefaultValue(100), Description("Current X position in pixel.")]
public int X
{
get
{
if (behavior != null)
{
x = behavior.X;
}
return x;
}
set
{
x = value;
if (behavior != null)
{
behavior.SetX(x);
behavior.Invalidate();
}
}
}
/// <summary>
/// Current Y position in pixel.
/// </summary>
[Category("Behavior"), DefaultValue(100), Description("Current Y position in pixel.")]
public int Y
{
get
{
if (behavior != null)
{
y = behavior.Y;
}
return y;
}
set
{
y = value;
if (behavior != null)
{
behavior.SetY(y);
behavior.Invalidate();
}
}
}
/// <summary>
/// Color of help lines.
/// </summary>
[Category("Layout"), DefaultValue(typeof(Color), "Blue"), Description("Color of help lines.")]
public System.Drawing.Color LineColor
{
get
{
return color;
}
set
{
color = value;
if (behavior != null)
{
behavior.LineStyle.Color = color;
behavior.Invalidate();
}
}
}
/// <summary>
/// Width of line in pixel.
/// </summary>
[Category("Layout"), DefaultValue(1), Description("Width of pen in pixel.")]
public int LineWidth
{
get
{
return width;
}
set
{
width = value;
if (behavior != null)
{
behavior.LineStyle.Width = width;
behavior.Invalidate();
}
}
}
/// <summary>
/// Dashstyle of line.
/// </summary>
[Category("Layout"), DefaultValue(typeof(System.Drawing.Drawing2D.DashStyle), "Solid"), Description("Dashstyle of pen.")]
public System.Drawing.Drawing2D.DashStyle LineDash
{
get
{
return dash;
}
set
{
dash = value;
if (behavior != null)
{
behavior.LineStyle.DashStyle = value;
behavior.Invalidate();
}
}
}
/// <summary>
/// Make the helpline temporarily invisible.
/// </summary>
[Category("Layout"), DefaultValue(true), Description("Make the helpline temporarily invisible.")]
public bool LineVisible
{
get
{
return lineVisible;
}
set
{
lineVisible = value;
if (behavior != null)
{
behavior.LineVisible = lineVisible;
behavior.Invalidate();
}
}
}
/// <summary>
/// Gets or sets the snap zone in which the helpline is magnetic. Defaults to 12 pixel.
/// </summary>
[Category("Snap"), DefaultValue(12), Description("Gets or sets the snap zone in which the helpline is magnetic. Defaults to 12 pixel.")]
public int SnapZone
{
get
{
return snapZone;
}
set
{
snapZone = value;
if (behavior != null)
{
behavior.SnapZone = snapZone;
behavior.Invalidate();
}
}
}
/// <summary>
/// Gets or sets the snap on resize feature. If on the helpline will be magnetic during element resizing.
/// </summary>
[Category("Snap"), DefaultValue(true), Description("Gets or sets the snap on resize feature. If on the helpline will be magnetic during element resizing.")]
public bool SnapOnResize
{
get
{
return snapOnResize;
}
set
{
snapOnResize = value;
if (behavior != null)
{
behavior.SnapOnResize = snapOnResize;
behavior.Invalidate();
}
}
}
/// <summary>
/// Gets or sets the snap to grid feature. If on the helpline will be magnetic against a virtual grid.
/// </summary>
[Category("Snap"), DefaultValue(true), Description("Gets or sets the snap to grid feature. If on the helpline will be magnetic against a virtual grid.")]
public bool SnapToGrid
{
get
{
return snapEnabled;
}
set
{
snapEnabled = value;
if (behavior != null)
{
behavior.SnapEnabled = snapEnabled;
behavior.Invalidate();
}
}
}
/// <summary>
/// Enables the X line. Default is On.
/// </summary>
[Category("Layout"), DefaultValue(true), Description("Enables the X line. Default is On.")]
public bool LineXEnabled
{
get
{
return lineXEnabled;
}
set
{
lineXEnabled = value;
if (behavior != null)
{
behavior.LineXEnabled = lineXEnabled;
behavior.Invalidate();
}
}
}
/// <summary>
/// Enables the Y line. Default is On.
/// </summary>
[Category("Layout"), DefaultValue(true), Description("Enables the Y line. Default is On.")]
public bool LineYEnabled
{
get
{
return lineYEnabled;
}
set
{
lineYEnabled = value;
if (behavior != null)
{
behavior.LineYEnabled = lineYEnabled;
behavior.Invalidate();
}
}
}
/// <summary>
/// Enables the cross sign.
/// </summary>
/// <remarks>
/// Default is On, if both lines are visible, otherwise it's not visible.
/// </remarks>
[Category("Layout"), DefaultValue(true), Description("Enables the cross sign. Default is On.")]
public bool CrossEnabled
{
get
{
return crossEnabled;
}
set
{
crossEnabled = value;
if (behavior != null)
{
behavior.CrossEnabled = crossEnabled;
behavior.Invalidate();
}
}
}
/// <summary>
/// Let elements snap to the helpline.
/// </summary>
[Category("Snap"), DefaultValue(true), Description("Let elements snap to the helpline.")]
public bool SnapElements
{
get
{
return snapelements;
}
set
{
snapelements = value;
if (behavior != null)
{
behavior.SnapElements = snapelements;
behavior.Invalidate();
}
}
}
/// <summary>
/// Gets or sets the distance in pixels between the grid.
/// </summary>
/// <remarks>
/// The grid is used to snap the helpline to fixed points. It has no relation to the Grid property
/// exposed by the NetRix base control. However, it's recommended to set both, the virtual helpine grid and
/// the visible grid to the same distance for best user experience.
/// </remarks>
[Category("Snap"), DefaultValue(16), Description("Gets or sets the distance in pixels between the grid.")]
public int SnapGrid
{
get
{
return snapgrid;
}
set
{
snapgrid = value;
if (behavior != null)
{
behavior.SnapGrid = snapgrid;
behavior.Invalidate();
}
}
}
}
}
| |
// 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.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableHashSetBuilderTest : ImmutablesTestBase
{
[Fact]
public void CreateBuilder()
{
var builder = ImmutableHashSet.CreateBuilder<string>();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableHashSet<int>.Empty.ToBuilder();
Assert.True(builder.Add(3));
Assert.True(builder.Add(5));
Assert.False(builder.Add(5));
Assert.Equal(2, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var set = builder.ToImmutable();
Assert.Equal(builder.Count, set.Count);
Assert.True(builder.Add(8));
Assert.Equal(3, builder.Count);
Assert.Equal(2, set.Count);
Assert.True(builder.Contains(8));
Assert.False(set.Contains(8));
}
[Fact]
public void BuilderFromSet()
{
var set = ImmutableHashSet<int>.Empty.Add(1);
var builder = set.ToBuilder();
Assert.True(builder.Contains(1));
Assert.True(builder.Add(3));
Assert.True(builder.Add(5));
Assert.False(builder.Add(5));
Assert.Equal(3, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var set2 = builder.ToImmutable();
Assert.Equal(builder.Count, set2.Count);
Assert.True(set2.Contains(1));
Assert.True(builder.Add(8));
Assert.Equal(4, builder.Count);
Assert.Equal(3, set2.Count);
Assert.True(builder.Contains(8));
Assert.False(set.Contains(8));
Assert.False(set2.Contains(8));
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableHashSet<int>.Empty.Union(Enumerable.Range(1, 10)).ToBuilder();
CollectionAssertAreEquivalent(Enumerable.Range(1, 10).ToArray(), builder.ToArray());
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11);
// Verify that a new enumerator will succeed.
CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray());
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray());
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableHashSet<int>.Empty.Add(1);
var builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // no changes at all.
builder.Add(2);
var newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void EnumeratorTest()
{
var builder = ImmutableHashSet.Create(1).ToBuilder();
ManuallyEnumerateTest(new[] { 1 }, ((IEnumerable<int>)builder).GetEnumerator());
}
[Fact]
public void Clear()
{
var set = ImmutableHashSet.Create(1);
var builder = set.ToBuilder();
builder.Clear();
Assert.Equal(0, builder.Count);
}
[Fact]
public void KeyComparer()
{
var builder = ImmutableHashSet.Create("a", "B").ToBuilder();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
Assert.True(builder.Contains("a"));
Assert.False(builder.Contains("A"));
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
Assert.Equal(2, builder.Count);
Assert.True(builder.Contains("a"));
Assert.True(builder.Contains("A"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void KeyComparerCollisions()
{
var builder = ImmutableHashSet.Create("a", "A").ToBuilder();
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Equal(1, builder.Count);
Assert.True(builder.Contains("a"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
Assert.Equal(1, set.Count);
Assert.True(set.Contains("a"));
}
[Fact]
public void KeyComparerEmptyCollection()
{
var builder = ImmutableHashSet.Create<string>().ToBuilder();
Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer);
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void UnionWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.UnionWith(null));
builder.UnionWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1, 2, 3, 4 }, builder);
}
[Fact]
public void ExceptWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.ExceptWith(null));
builder.ExceptWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1 }, builder);
}
[Fact]
public void SymmetricExceptWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.SymmetricExceptWith(null));
builder.SymmetricExceptWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1, 4 }, builder);
}
[Fact]
public void IntersectWith()
{
var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IntersectWith(null));
builder.IntersectWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 2, 3 }, builder);
}
[Fact]
public void IsProperSubsetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsProperSubsetOf(null));
Assert.False(builder.IsProperSubsetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsProperSubsetOf(Enumerable.Range(1, 5)));
}
[Fact]
public void IsProperSupersetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsProperSupersetOf(null));
Assert.False(builder.IsProperSupersetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsProperSupersetOf(Enumerable.Range(1, 2)));
}
[Fact]
public void IsSubsetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsSubsetOf(null));
Assert.False(builder.IsSubsetOf(Enumerable.Range(1, 2)));
Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 5)));
}
[Fact]
public void IsSupersetOf()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsSupersetOf(null));
Assert.False(builder.IsSupersetOf(Enumerable.Range(1, 4)));
Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 2)));
}
[Fact]
public void Overlaps()
{
var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.Overlaps(null));
Assert.True(builder.Overlaps(Enumerable.Range(3, 2)));
Assert.False(builder.Overlaps(Enumerable.Range(4, 3)));
}
[Fact]
public void Remove()
{
var builder = ImmutableHashSet.Create("a").ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.Remove(null));
Assert.False(builder.Remove("b"));
Assert.True(builder.Remove("a"));
}
[Fact]
public void SetEquals()
{
var builder = ImmutableHashSet.Create("a").ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.SetEquals(null));
Assert.False(builder.SetEquals(new[] { "b" }));
Assert.True(builder.SetEquals(new[] { "a" }));
Assert.True(builder.SetEquals(builder));
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> builder = ImmutableHashSet.Create("a").ToBuilder();
builder.Add("b");
Assert.True(builder.Contains("b"));
var array = new string[3];
builder.CopyTo(array, 1);
Assert.Null(array[0]);
CollectionAssertAreEquivalent(new[] { null, "a", "b" }, array);
Assert.False(builder.IsReadOnly);
CollectionAssertAreEquivalent(new[] { "a", "b" }, builder.ToArray()); // tests enumerator
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableHashSet.CreateBuilder<int>());
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Security.Cryptography
{
public abstract partial class Aes : System.Security.Cryptography.SymmetricAlgorithm
{
protected Aes() { }
public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { return default(System.Security.Cryptography.KeySizes[]); } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { return default(System.Security.Cryptography.KeySizes[]); } }
public static System.Security.Cryptography.Aes Create() { return default(System.Security.Cryptography.Aes); }
}
public abstract partial class DeriveBytes : System.IDisposable
{
protected DeriveBytes() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract byte[] GetBytes(int cb);
public abstract void Reset();
}
public abstract partial class ECDsa : System.Security.Cryptography.AsymmetricAlgorithm
{
protected ECDsa() { }
protected abstract byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm);
protected abstract byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm);
public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); }
public virtual byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); }
public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); }
public abstract byte[] SignHash(byte[] hash);
public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(bool); }
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(bool); }
public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(bool); }
public abstract bool VerifyHash(byte[] hash, byte[] signature);
}
public partial class HMACMD5 : System.Security.Cryptography.HMAC
{
public HMACMD5() { }
public HMACMD5(byte[] key) { }
public override int HashSize { get { return default(int); } }
public override byte[] Key { get { return default(byte[]); } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { return default(byte[]); }
public override void Initialize() { }
}
public partial class HMACSHA1 : System.Security.Cryptography.HMAC
{
public HMACSHA1() { }
public HMACSHA1(byte[] key) { }
public override int HashSize { get { return default(int); } }
public override byte[] Key { get { return default(byte[]); } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { return default(byte[]); }
public override void Initialize() { }
}
public partial class HMACSHA256 : System.Security.Cryptography.HMAC
{
public HMACSHA256() { }
public HMACSHA256(byte[] key) { }
public override int HashSize { get { return default(int); } }
public override byte[] Key { get { return default(byte[]); } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { return default(byte[]); }
public override void Initialize() { }
}
public partial class HMACSHA384 : System.Security.Cryptography.HMAC
{
public HMACSHA384() { }
public HMACSHA384(byte[] key) { }
public override int HashSize { get { return default(int); } }
public override byte[] Key { get { return default(byte[]); } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { return default(byte[]); }
public override void Initialize() { }
}
public partial class HMACSHA512 : System.Security.Cryptography.HMAC
{
public HMACSHA512() { }
public HMACSHA512(byte[] key) { }
public override int HashSize { get { return default(int); } }
public override byte[] Key { get { return default(byte[]); } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { return default(byte[]); }
public override void Initialize() { }
}
public sealed partial class IncrementalHash : System.IDisposable
{
internal IncrementalHash() { }
public System.Security.Cryptography.HashAlgorithmName AlgorithmName { get { return default(System.Security.Cryptography.HashAlgorithmName); } }
public void AppendData(byte[] data) { }
public void AppendData(byte[] data, int offset, int count) { }
public static System.Security.Cryptography.IncrementalHash CreateHash(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(System.Security.Cryptography.IncrementalHash); }
public static System.Security.Cryptography.IncrementalHash CreateHMAC(System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] key) { return default(System.Security.Cryptography.IncrementalHash); }
public void Dispose() { }
public byte[] GetHashAndReset() { return default(byte[]); }
}
public abstract partial class MD5 : System.Security.Cryptography.HashAlgorithm
{
protected MD5() { }
public static System.Security.Cryptography.MD5 Create() { return default(System.Security.Cryptography.MD5); }
}
public abstract partial class RandomNumberGenerator : System.IDisposable
{
protected RandomNumberGenerator() { }
public static System.Security.Cryptography.RandomNumberGenerator Create() { return default(System.Security.Cryptography.RandomNumberGenerator); }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract void GetBytes(byte[] data);
}
public partial class Rfc2898DeriveBytes : System.Security.Cryptography.DeriveBytes
{
public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) { }
public Rfc2898DeriveBytes(string password, byte[] salt) { }
public Rfc2898DeriveBytes(string password, byte[] salt, int iterations) { }
public Rfc2898DeriveBytes(string password, int saltSize) { }
public Rfc2898DeriveBytes(string password, int saltSize, int iterations) { }
public int IterationCount { get { return default(int); } set { } }
public byte[] Salt { get { return default(byte[]); } set { } }
protected override void Dispose(bool disposing) { }
public override byte[] GetBytes(int cb) { return default(byte[]); }
public override void Reset() { }
}
public abstract partial class RSA : System.Security.Cryptography.AsymmetricAlgorithm
{
protected RSA() { }
public abstract byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding);
public abstract byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding);
public abstract System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters);
protected abstract byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm);
protected abstract byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm);
public abstract void ImportParameters(System.Security.Cryptography.RSAParameters parameters);
public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(byte[]); }
public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(byte[]); }
public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(byte[]); }
public abstract byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding);
public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(bool); }
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(bool); }
public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(bool); }
public abstract bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding);
}
public sealed partial class RSAEncryptionPadding : System.IEquatable<System.Security.Cryptography.RSAEncryptionPadding>
{
internal RSAEncryptionPadding() { }
public System.Security.Cryptography.RSAEncryptionPaddingMode Mode { get { return default(System.Security.Cryptography.RSAEncryptionPaddingMode); } }
public System.Security.Cryptography.HashAlgorithmName OaepHashAlgorithm { get { return default(System.Security.Cryptography.HashAlgorithmName); } }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA1 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA256 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA384 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA512 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } }
public static System.Security.Cryptography.RSAEncryptionPadding Pkcs1 { get { return default(System.Security.Cryptography.RSAEncryptionPadding); } }
public static System.Security.Cryptography.RSAEncryptionPadding CreateOaep(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(System.Security.Cryptography.RSAEncryptionPadding); }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.RSAEncryptionPadding other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { return default(bool); }
public override string ToString() { return default(string); }
}
public enum RSAEncryptionPaddingMode
{
Oaep = 1,
Pkcs1 = 0,
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct RSAParameters
{
public byte[] D;
public byte[] DP;
public byte[] DQ;
public byte[] Exponent;
public byte[] InverseQ;
public byte[] Modulus;
public byte[] P;
public byte[] Q;
}
public sealed partial class RSASignaturePadding : System.IEquatable<System.Security.Cryptography.RSASignaturePadding>
{
internal RSASignaturePadding() { }
public System.Security.Cryptography.RSASignaturePaddingMode Mode { get { return default(System.Security.Cryptography.RSASignaturePaddingMode); } }
public static System.Security.Cryptography.RSASignaturePadding Pkcs1 { get { return default(System.Security.Cryptography.RSASignaturePadding); } }
public static System.Security.Cryptography.RSASignaturePadding Pss { get { return default(System.Security.Cryptography.RSASignaturePadding); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.RSASignaturePadding other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { return default(bool); }
public override string ToString() { return default(string); }
}
public enum RSASignaturePaddingMode
{
Pkcs1 = 0,
Pss = 1,
}
public abstract partial class SHA1 : System.Security.Cryptography.HashAlgorithm
{
protected SHA1() { }
public static System.Security.Cryptography.SHA1 Create() { return default(System.Security.Cryptography.SHA1); }
}
public abstract partial class SHA256 : System.Security.Cryptography.HashAlgorithm
{
protected SHA256() { }
public static System.Security.Cryptography.SHA256 Create() { return default(System.Security.Cryptography.SHA256); }
}
public abstract partial class SHA384 : System.Security.Cryptography.HashAlgorithm
{
protected SHA384() { }
public static System.Security.Cryptography.SHA384 Create() { return default(System.Security.Cryptography.SHA384); }
}
public abstract partial class SHA512 : System.Security.Cryptography.HashAlgorithm
{
protected SHA512() { }
public static System.Security.Cryptography.SHA512 Create() { return default(System.Security.Cryptography.SHA512); }
}
public abstract partial class TripleDES : System.Security.Cryptography.SymmetricAlgorithm
{
protected TripleDES() { }
public override byte[] Key { get { return default(byte[]); } set { } }
public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { return default(System.Security.Cryptography.KeySizes[]); } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { return default(System.Security.Cryptography.KeySizes[]); } }
public static System.Security.Cryptography.TripleDES Create() { return default(System.Security.Cryptography.TripleDES); }
public static bool IsWeakKey(byte[] rgbKey) { return default(bool); }
}
}
| |
// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT!
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class PersistenceMessages {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_PersistentMessage__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::PersistentMessage, global::PersistentMessage.Builder> internal__static_PersistentMessage__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_PersistentPayload__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::PersistentPayload, global::PersistentPayload.Builder> internal__static_PersistentPayload__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_AtLeastOnceDeliverySnapshot__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::AtLeastOnceDeliverySnapshot, global::AtLeastOnceDeliverySnapshot.Builder> internal__static_AtLeastOnceDeliverySnapshot__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_AtLeastOnceDeliverySnapshot_UnconfirmedDelivery__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery, global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery.Builder> internal__static_AtLeastOnceDeliverySnapshot_UnconfirmedDelivery__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static PersistenceMessages() {
byte[] descriptorData = global::System.Convert.FromBase64String(
"ChlQZXJzaXN0ZW5jZU1lc3NhZ2VzLnByb3RvIoQBChFQZXJzaXN0ZW50TWVz" +
"c2FnZRIjCgdwYXlsb2FkGAEgASgLMhIuUGVyc2lzdGVudFBheWxvYWQSEgoK" +
"c2VxdWVuY2VOchgCIAEoAxIVCg1wZXJzaXN0ZW5jZUlkGAMgASgJEg8KB2Rl" +
"bGV0ZWQYBCABKAgSDgoGc2VuZGVyGAsgASgJIlMKEVBlcnNpc3RlbnRQYXls" +
"b2FkEhQKDHNlcmlhbGl6ZXJJZBgBIAIoBRIPCgdwYXlsb2FkGAIgAigMEhcK" +
"D3BheWxvYWRNYW5pZmVzdBgDIAEoDCLuAQobQXRMZWFzdE9uY2VEZWxpdmVy" +
"eVNuYXBzaG90EhkKEWN1cnJlbnREZWxpdmVyeUlkGAEgAigDEk8KFXVuY29u" +
"ZmlybWVkRGVsaXZlcmllcxgCIAMoCzIwLkF0TGVhc3RPbmNlRGVsaXZlcnlT" +
"bmFwc2hvdC5VbmNvbmZpcm1lZERlbGl2ZXJ5GmMKE1VuY29uZmlybWVkRGVs" +
"aXZlcnkSEgoKZGVsaXZlcnlJZBgBIAIoAxITCgtkZXN0aW5hdGlvbhgCIAIo" +
"CRIjCgdwYXlsb2FkGAMgAigLMhIuUGVyc2lzdGVudFBheWxvYWRCIgoeYWtr" +
"YS5wZXJzaXN0ZW5jZS5zZXJpYWxpemF0aW9uSAE=");
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_PersistentMessage__Descriptor = Descriptor.MessageTypes[0];
internal__static_PersistentMessage__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::PersistentMessage, global::PersistentMessage.Builder>(internal__static_PersistentMessage__Descriptor,
new string[] { "Payload", "SequenceNr", "PersistenceId", "Deleted", "Sender", });
internal__static_PersistentPayload__Descriptor = Descriptor.MessageTypes[1];
internal__static_PersistentPayload__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::PersistentPayload, global::PersistentPayload.Builder>(internal__static_PersistentPayload__Descriptor,
new string[] { "SerializerId", "Payload", "PayloadManifest", });
internal__static_AtLeastOnceDeliverySnapshot__Descriptor = Descriptor.MessageTypes[2];
internal__static_AtLeastOnceDeliverySnapshot__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::AtLeastOnceDeliverySnapshot, global::AtLeastOnceDeliverySnapshot.Builder>(internal__static_AtLeastOnceDeliverySnapshot__Descriptor,
new string[] { "CurrentDeliveryId", "UnconfirmedDeliveries", });
internal__static_AtLeastOnceDeliverySnapshot_UnconfirmedDelivery__Descriptor = internal__static_AtLeastOnceDeliverySnapshot__Descriptor.NestedTypes[0];
internal__static_AtLeastOnceDeliverySnapshot_UnconfirmedDelivery__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery, global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery.Builder>(internal__static_AtLeastOnceDeliverySnapshot_UnconfirmedDelivery__Descriptor,
new string[] { "DeliveryId", "Destination", "Payload", });
return null;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PersistentMessage : pb::GeneratedMessage<PersistentMessage, PersistentMessage.Builder> {
private PersistentMessage() { }
private static readonly PersistentMessage defaultInstance = new PersistentMessage().MakeReadOnly();
private static readonly string[] _persistentMessageFieldNames = new string[] { "deleted", "payload", "persistenceId", "sender", "sequenceNr" };
private static readonly uint[] _persistentMessageFieldTags = new uint[] { 32, 10, 26, 90, 16 };
public static PersistentMessage DefaultInstance {
get { return defaultInstance; }
}
public override PersistentMessage DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override PersistentMessage ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::PersistenceMessages.internal__static_PersistentMessage__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<PersistentMessage, PersistentMessage.Builder> InternalFieldAccessors {
get { return global::PersistenceMessages.internal__static_PersistentMessage__FieldAccessorTable; }
}
public const int PayloadFieldNumber = 1;
private bool hasPayload;
private global::PersistentPayload payload_;
public bool HasPayload {
get { return hasPayload; }
}
public global::PersistentPayload Payload {
get { return payload_ ?? global::PersistentPayload.DefaultInstance; }
}
public const int SequenceNrFieldNumber = 2;
private bool hasSequenceNr;
private long sequenceNr_;
public bool HasSequenceNr {
get { return hasSequenceNr; }
}
public long SequenceNr {
get { return sequenceNr_; }
}
public const int PersistenceIdFieldNumber = 3;
private bool hasPersistenceId;
private string persistenceId_ = "";
public bool HasPersistenceId {
get { return hasPersistenceId; }
}
public string PersistenceId {
get { return persistenceId_; }
}
public const int DeletedFieldNumber = 4;
private bool hasDeleted;
private bool deleted_;
public bool HasDeleted {
get { return hasDeleted; }
}
public bool Deleted {
get { return deleted_; }
}
public const int SenderFieldNumber = 11;
private bool hasSender;
private string sender_ = "";
public bool HasSender {
get { return hasSender; }
}
public string Sender {
get { return sender_; }
}
public override bool IsInitialized {
get {
if (HasPayload) {
if (!Payload.IsInitialized) return false;
}
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
int size = SerializedSize;
string[] field_names = _persistentMessageFieldNames;
if (hasPayload) {
output.WriteMessage(1, field_names[1], Payload);
}
if (hasSequenceNr) {
output.WriteInt64(2, field_names[4], SequenceNr);
}
if (hasPersistenceId) {
output.WriteString(3, field_names[2], PersistenceId);
}
if (hasDeleted) {
output.WriteBool(4, field_names[0], Deleted);
}
if (hasSender) {
output.WriteString(11, field_names[3], Sender);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasPayload) {
size += pb::CodedOutputStream.ComputeMessageSize(1, Payload);
}
if (hasSequenceNr) {
size += pb::CodedOutputStream.ComputeInt64Size(2, SequenceNr);
}
if (hasPersistenceId) {
size += pb::CodedOutputStream.ComputeStringSize(3, PersistenceId);
}
if (hasDeleted) {
size += pb::CodedOutputStream.ComputeBoolSize(4, Deleted);
}
if (hasSender) {
size += pb::CodedOutputStream.ComputeStringSize(11, Sender);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static PersistentMessage ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PersistentMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PersistentMessage ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PersistentMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PersistentMessage ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PersistentMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static PersistentMessage ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static PersistentMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static PersistentMessage ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PersistentMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private PersistentMessage MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(PersistentMessage prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<PersistentMessage, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(PersistentMessage cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private PersistentMessage result;
private PersistentMessage PrepareBuilder() {
if (resultIsReadOnly) {
PersistentMessage original = result;
result = new PersistentMessage();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override PersistentMessage MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::PersistentMessage.Descriptor; }
}
public override PersistentMessage DefaultInstanceForType {
get { return global::PersistentMessage.DefaultInstance; }
}
public override PersistentMessage BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is PersistentMessage) {
return MergeFrom((PersistentMessage) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(PersistentMessage other) {
if (other == global::PersistentMessage.DefaultInstance) return this;
PrepareBuilder();
if (other.HasPayload) {
MergePayload(other.Payload);
}
if (other.HasSequenceNr) {
SequenceNr = other.SequenceNr;
}
if (other.HasPersistenceId) {
PersistenceId = other.PersistenceId;
}
if (other.HasDeleted) {
Deleted = other.Deleted;
}
if (other.HasSender) {
Sender = other.Sender;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_persistentMessageFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _persistentMessageFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
global::PersistentPayload.Builder subBuilder = global::PersistentPayload.CreateBuilder();
if (result.hasPayload) {
subBuilder.MergeFrom(Payload);
}
input.ReadMessage(subBuilder, extensionRegistry);
Payload = subBuilder.BuildPartial();
break;
}
case 16: {
result.hasSequenceNr = input.ReadInt64(ref result.sequenceNr_);
break;
}
case 26: {
result.hasPersistenceId = input.ReadString(ref result.persistenceId_);
break;
}
case 32: {
result.hasDeleted = input.ReadBool(ref result.deleted_);
break;
}
case 90: {
result.hasSender = input.ReadString(ref result.sender_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasPayload {
get { return result.hasPayload; }
}
public global::PersistentPayload Payload {
get { return result.Payload; }
set { SetPayload(value); }
}
public Builder SetPayload(global::PersistentPayload value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasPayload = true;
result.payload_ = value;
return this;
}
public Builder SetPayload(global::PersistentPayload.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.hasPayload = true;
result.payload_ = builderForValue.Build();
return this;
}
public Builder MergePayload(global::PersistentPayload value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
if (result.hasPayload &&
result.payload_ != global::PersistentPayload.DefaultInstance) {
result.payload_ = global::PersistentPayload.CreateBuilder(result.payload_).MergeFrom(value).BuildPartial();
} else {
result.payload_ = value;
}
result.hasPayload = true;
return this;
}
public Builder ClearPayload() {
PrepareBuilder();
result.hasPayload = false;
result.payload_ = null;
return this;
}
public bool HasSequenceNr {
get { return result.hasSequenceNr; }
}
public long SequenceNr {
get { return result.SequenceNr; }
set { SetSequenceNr(value); }
}
public Builder SetSequenceNr(long value) {
PrepareBuilder();
result.hasSequenceNr = true;
result.sequenceNr_ = value;
return this;
}
public Builder ClearSequenceNr() {
PrepareBuilder();
result.hasSequenceNr = false;
result.sequenceNr_ = 0L;
return this;
}
public bool HasPersistenceId {
get { return result.hasPersistenceId; }
}
public string PersistenceId {
get { return result.PersistenceId; }
set { SetPersistenceId(value); }
}
public Builder SetPersistenceId(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasPersistenceId = true;
result.persistenceId_ = value;
return this;
}
public Builder ClearPersistenceId() {
PrepareBuilder();
result.hasPersistenceId = false;
result.persistenceId_ = "";
return this;
}
public bool HasDeleted {
get { return result.hasDeleted; }
}
public bool Deleted {
get { return result.Deleted; }
set { SetDeleted(value); }
}
public Builder SetDeleted(bool value) {
PrepareBuilder();
result.hasDeleted = true;
result.deleted_ = value;
return this;
}
public Builder ClearDeleted() {
PrepareBuilder();
result.hasDeleted = false;
result.deleted_ = false;
return this;
}
public bool HasSender {
get { return result.hasSender; }
}
public string Sender {
get { return result.Sender; }
set { SetSender(value); }
}
public Builder SetSender(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasSender = true;
result.sender_ = value;
return this;
}
public Builder ClearSender() {
PrepareBuilder();
result.hasSender = false;
result.sender_ = "";
return this;
}
}
static PersistentMessage() {
object.ReferenceEquals(global::PersistenceMessages.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PersistentPayload : pb::GeneratedMessage<PersistentPayload, PersistentPayload.Builder> {
private PersistentPayload() { }
private static readonly PersistentPayload defaultInstance = new PersistentPayload().MakeReadOnly();
private static readonly string[] _persistentPayloadFieldNames = new string[] { "payload", "payloadManifest", "serializerId" };
private static readonly uint[] _persistentPayloadFieldTags = new uint[] { 18, 26, 8 };
public static PersistentPayload DefaultInstance {
get { return defaultInstance; }
}
public override PersistentPayload DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override PersistentPayload ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::PersistenceMessages.internal__static_PersistentPayload__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<PersistentPayload, PersistentPayload.Builder> InternalFieldAccessors {
get { return global::PersistenceMessages.internal__static_PersistentPayload__FieldAccessorTable; }
}
public const int SerializerIdFieldNumber = 1;
private bool hasSerializerId;
private int serializerId_;
public bool HasSerializerId {
get { return hasSerializerId; }
}
public int SerializerId {
get { return serializerId_; }
}
public const int PayloadFieldNumber = 2;
private bool hasPayload;
private pb::ByteString payload_ = pb::ByteString.Empty;
public bool HasPayload {
get { return hasPayload; }
}
public pb::ByteString Payload {
get { return payload_; }
}
public const int PayloadManifestFieldNumber = 3;
private bool hasPayloadManifest;
private pb::ByteString payloadManifest_ = pb::ByteString.Empty;
public bool HasPayloadManifest {
get { return hasPayloadManifest; }
}
public pb::ByteString PayloadManifest {
get { return payloadManifest_; }
}
public override bool IsInitialized {
get {
if (!hasSerializerId) return false;
if (!hasPayload) return false;
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
int size = SerializedSize;
string[] field_names = _persistentPayloadFieldNames;
if (hasSerializerId) {
output.WriteInt32(1, field_names[2], SerializerId);
}
if (hasPayload) {
output.WriteBytes(2, field_names[0], Payload);
}
if (hasPayloadManifest) {
output.WriteBytes(3, field_names[1], PayloadManifest);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasSerializerId) {
size += pb::CodedOutputStream.ComputeInt32Size(1, SerializerId);
}
if (hasPayload) {
size += pb::CodedOutputStream.ComputeBytesSize(2, Payload);
}
if (hasPayloadManifest) {
size += pb::CodedOutputStream.ComputeBytesSize(3, PayloadManifest);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static PersistentPayload ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PersistentPayload ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PersistentPayload ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PersistentPayload ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PersistentPayload ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PersistentPayload ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static PersistentPayload ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static PersistentPayload ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static PersistentPayload ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PersistentPayload ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private PersistentPayload MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(PersistentPayload prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<PersistentPayload, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(PersistentPayload cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private PersistentPayload result;
private PersistentPayload PrepareBuilder() {
if (resultIsReadOnly) {
PersistentPayload original = result;
result = new PersistentPayload();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override PersistentPayload MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::PersistentPayload.Descriptor; }
}
public override PersistentPayload DefaultInstanceForType {
get { return global::PersistentPayload.DefaultInstance; }
}
public override PersistentPayload BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is PersistentPayload) {
return MergeFrom((PersistentPayload) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(PersistentPayload other) {
if (other == global::PersistentPayload.DefaultInstance) return this;
PrepareBuilder();
if (other.HasSerializerId) {
SerializerId = other.SerializerId;
}
if (other.HasPayload) {
Payload = other.Payload;
}
if (other.HasPayloadManifest) {
PayloadManifest = other.PayloadManifest;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_persistentPayloadFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _persistentPayloadFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasSerializerId = input.ReadInt32(ref result.serializerId_);
break;
}
case 18: {
result.hasPayload = input.ReadBytes(ref result.payload_);
break;
}
case 26: {
result.hasPayloadManifest = input.ReadBytes(ref result.payloadManifest_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasSerializerId {
get { return result.hasSerializerId; }
}
public int SerializerId {
get { return result.SerializerId; }
set { SetSerializerId(value); }
}
public Builder SetSerializerId(int value) {
PrepareBuilder();
result.hasSerializerId = true;
result.serializerId_ = value;
return this;
}
public Builder ClearSerializerId() {
PrepareBuilder();
result.hasSerializerId = false;
result.serializerId_ = 0;
return this;
}
public bool HasPayload {
get { return result.hasPayload; }
}
public pb::ByteString Payload {
get { return result.Payload; }
set { SetPayload(value); }
}
public Builder SetPayload(pb::ByteString value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasPayload = true;
result.payload_ = value;
return this;
}
public Builder ClearPayload() {
PrepareBuilder();
result.hasPayload = false;
result.payload_ = pb::ByteString.Empty;
return this;
}
public bool HasPayloadManifest {
get { return result.hasPayloadManifest; }
}
public pb::ByteString PayloadManifest {
get { return result.PayloadManifest; }
set { SetPayloadManifest(value); }
}
public Builder SetPayloadManifest(pb::ByteString value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasPayloadManifest = true;
result.payloadManifest_ = value;
return this;
}
public Builder ClearPayloadManifest() {
PrepareBuilder();
result.hasPayloadManifest = false;
result.payloadManifest_ = pb::ByteString.Empty;
return this;
}
}
static PersistentPayload() {
object.ReferenceEquals(global::PersistenceMessages.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class AtLeastOnceDeliverySnapshot : pb::GeneratedMessage<AtLeastOnceDeliverySnapshot, AtLeastOnceDeliverySnapshot.Builder> {
private AtLeastOnceDeliverySnapshot() { }
private static readonly AtLeastOnceDeliverySnapshot defaultInstance = new AtLeastOnceDeliverySnapshot().MakeReadOnly();
private static readonly string[] _atLeastOnceDeliverySnapshotFieldNames = new string[] { "currentDeliveryId", "unconfirmedDeliveries" };
private static readonly uint[] _atLeastOnceDeliverySnapshotFieldTags = new uint[] { 8, 18 };
public static AtLeastOnceDeliverySnapshot DefaultInstance {
get { return defaultInstance; }
}
public override AtLeastOnceDeliverySnapshot DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override AtLeastOnceDeliverySnapshot ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::PersistenceMessages.internal__static_AtLeastOnceDeliverySnapshot__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<AtLeastOnceDeliverySnapshot, AtLeastOnceDeliverySnapshot.Builder> InternalFieldAccessors {
get { return global::PersistenceMessages.internal__static_AtLeastOnceDeliverySnapshot__FieldAccessorTable; }
}
#region Nested types
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class UnconfirmedDelivery : pb::GeneratedMessage<UnconfirmedDelivery, UnconfirmedDelivery.Builder> {
private UnconfirmedDelivery() { }
private static readonly UnconfirmedDelivery defaultInstance = new UnconfirmedDelivery().MakeReadOnly();
private static readonly string[] _unconfirmedDeliveryFieldNames = new string[] { "deliveryId", "destination", "payload" };
private static readonly uint[] _unconfirmedDeliveryFieldTags = new uint[] { 8, 18, 26 };
public static UnconfirmedDelivery DefaultInstance {
get { return defaultInstance; }
}
public override UnconfirmedDelivery DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override UnconfirmedDelivery ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::PersistenceMessages.internal__static_AtLeastOnceDeliverySnapshot_UnconfirmedDelivery__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<UnconfirmedDelivery, UnconfirmedDelivery.Builder> InternalFieldAccessors {
get { return global::PersistenceMessages.internal__static_AtLeastOnceDeliverySnapshot_UnconfirmedDelivery__FieldAccessorTable; }
}
public const int DeliveryIdFieldNumber = 1;
private bool hasDeliveryId;
private long deliveryId_;
public bool HasDeliveryId {
get { return hasDeliveryId; }
}
public long DeliveryId {
get { return deliveryId_; }
}
public const int DestinationFieldNumber = 2;
private bool hasDestination;
private string destination_ = "";
public bool HasDestination {
get { return hasDestination; }
}
public string Destination {
get { return destination_; }
}
public const int PayloadFieldNumber = 3;
private bool hasPayload;
private global::PersistentPayload payload_;
public bool HasPayload {
get { return hasPayload; }
}
public global::PersistentPayload Payload {
get { return payload_ ?? global::PersistentPayload.DefaultInstance; }
}
public override bool IsInitialized {
get {
if (!hasDeliveryId) return false;
if (!hasDestination) return false;
if (!hasPayload) return false;
if (!Payload.IsInitialized) return false;
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
int size = SerializedSize;
string[] field_names = _unconfirmedDeliveryFieldNames;
if (hasDeliveryId) {
output.WriteInt64(1, field_names[0], DeliveryId);
}
if (hasDestination) {
output.WriteString(2, field_names[1], Destination);
}
if (hasPayload) {
output.WriteMessage(3, field_names[2], Payload);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasDeliveryId) {
size += pb::CodedOutputStream.ComputeInt64Size(1, DeliveryId);
}
if (hasDestination) {
size += pb::CodedOutputStream.ComputeStringSize(2, Destination);
}
if (hasPayload) {
size += pb::CodedOutputStream.ComputeMessageSize(3, Payload);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static UnconfirmedDelivery ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static UnconfirmedDelivery ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static UnconfirmedDelivery ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static UnconfirmedDelivery ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static UnconfirmedDelivery ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static UnconfirmedDelivery ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static UnconfirmedDelivery ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static UnconfirmedDelivery ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static UnconfirmedDelivery ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static UnconfirmedDelivery ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private UnconfirmedDelivery MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(UnconfirmedDelivery prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<UnconfirmedDelivery, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(UnconfirmedDelivery cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private UnconfirmedDelivery result;
private UnconfirmedDelivery PrepareBuilder() {
if (resultIsReadOnly) {
UnconfirmedDelivery original = result;
result = new UnconfirmedDelivery();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override UnconfirmedDelivery MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery.Descriptor; }
}
public override UnconfirmedDelivery DefaultInstanceForType {
get { return global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery.DefaultInstance; }
}
public override UnconfirmedDelivery BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is UnconfirmedDelivery) {
return MergeFrom((UnconfirmedDelivery) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(UnconfirmedDelivery other) {
if (other == global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery.DefaultInstance) return this;
PrepareBuilder();
if (other.HasDeliveryId) {
DeliveryId = other.DeliveryId;
}
if (other.HasDestination) {
Destination = other.Destination;
}
if (other.HasPayload) {
MergePayload(other.Payload);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_unconfirmedDeliveryFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _unconfirmedDeliveryFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasDeliveryId = input.ReadInt64(ref result.deliveryId_);
break;
}
case 18: {
result.hasDestination = input.ReadString(ref result.destination_);
break;
}
case 26: {
global::PersistentPayload.Builder subBuilder = global::PersistentPayload.CreateBuilder();
if (result.hasPayload) {
subBuilder.MergeFrom(Payload);
}
input.ReadMessage(subBuilder, extensionRegistry);
Payload = subBuilder.BuildPartial();
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasDeliveryId {
get { return result.hasDeliveryId; }
}
public long DeliveryId {
get { return result.DeliveryId; }
set { SetDeliveryId(value); }
}
public Builder SetDeliveryId(long value) {
PrepareBuilder();
result.hasDeliveryId = true;
result.deliveryId_ = value;
return this;
}
public Builder ClearDeliveryId() {
PrepareBuilder();
result.hasDeliveryId = false;
result.deliveryId_ = 0L;
return this;
}
public bool HasDestination {
get { return result.hasDestination; }
}
public string Destination {
get { return result.Destination; }
set { SetDestination(value); }
}
public Builder SetDestination(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasDestination = true;
result.destination_ = value;
return this;
}
public Builder ClearDestination() {
PrepareBuilder();
result.hasDestination = false;
result.destination_ = "";
return this;
}
public bool HasPayload {
get { return result.hasPayload; }
}
public global::PersistentPayload Payload {
get { return result.Payload; }
set { SetPayload(value); }
}
public Builder SetPayload(global::PersistentPayload value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasPayload = true;
result.payload_ = value;
return this;
}
public Builder SetPayload(global::PersistentPayload.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.hasPayload = true;
result.payload_ = builderForValue.Build();
return this;
}
public Builder MergePayload(global::PersistentPayload value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
if (result.hasPayload &&
result.payload_ != global::PersistentPayload.DefaultInstance) {
result.payload_ = global::PersistentPayload.CreateBuilder(result.payload_).MergeFrom(value).BuildPartial();
} else {
result.payload_ = value;
}
result.hasPayload = true;
return this;
}
public Builder ClearPayload() {
PrepareBuilder();
result.hasPayload = false;
result.payload_ = null;
return this;
}
}
static UnconfirmedDelivery() {
object.ReferenceEquals(global::PersistenceMessages.Descriptor, null);
}
}
}
#endregion
public const int CurrentDeliveryIdFieldNumber = 1;
private bool hasCurrentDeliveryId;
private long currentDeliveryId_;
public bool HasCurrentDeliveryId {
get { return hasCurrentDeliveryId; }
}
public long CurrentDeliveryId {
get { return currentDeliveryId_; }
}
public const int UnconfirmedDeliveriesFieldNumber = 2;
private pbc::PopsicleList<global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery> unconfirmedDeliveries_ = new pbc::PopsicleList<global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery>();
public scg::IList<global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery> UnconfirmedDeliveriesList {
get { return unconfirmedDeliveries_; }
}
public int UnconfirmedDeliveriesCount {
get { return unconfirmedDeliveries_.Count; }
}
public global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery GetUnconfirmedDeliveries(int index) {
return unconfirmedDeliveries_[index];
}
public override bool IsInitialized {
get {
if (!hasCurrentDeliveryId) return false;
foreach (global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery element in UnconfirmedDeliveriesList) {
if (!element.IsInitialized) return false;
}
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
int size = SerializedSize;
string[] field_names = _atLeastOnceDeliverySnapshotFieldNames;
if (hasCurrentDeliveryId) {
output.WriteInt64(1, field_names[0], CurrentDeliveryId);
}
if (unconfirmedDeliveries_.Count > 0) {
output.WriteMessageArray(2, field_names[1], unconfirmedDeliveries_);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasCurrentDeliveryId) {
size += pb::CodedOutputStream.ComputeInt64Size(1, CurrentDeliveryId);
}
foreach (global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery element in UnconfirmedDeliveriesList) {
size += pb::CodedOutputStream.ComputeMessageSize(2, element);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static AtLeastOnceDeliverySnapshot ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static AtLeastOnceDeliverySnapshot ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static AtLeastOnceDeliverySnapshot ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static AtLeastOnceDeliverySnapshot ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static AtLeastOnceDeliverySnapshot ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static AtLeastOnceDeliverySnapshot ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static AtLeastOnceDeliverySnapshot ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static AtLeastOnceDeliverySnapshot ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static AtLeastOnceDeliverySnapshot ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static AtLeastOnceDeliverySnapshot ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private AtLeastOnceDeliverySnapshot MakeReadOnly() {
unconfirmedDeliveries_.MakeReadOnly();
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(AtLeastOnceDeliverySnapshot prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<AtLeastOnceDeliverySnapshot, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(AtLeastOnceDeliverySnapshot cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private AtLeastOnceDeliverySnapshot result;
private AtLeastOnceDeliverySnapshot PrepareBuilder() {
if (resultIsReadOnly) {
AtLeastOnceDeliverySnapshot original = result;
result = new AtLeastOnceDeliverySnapshot();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override AtLeastOnceDeliverySnapshot MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::AtLeastOnceDeliverySnapshot.Descriptor; }
}
public override AtLeastOnceDeliverySnapshot DefaultInstanceForType {
get { return global::AtLeastOnceDeliverySnapshot.DefaultInstance; }
}
public override AtLeastOnceDeliverySnapshot BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is AtLeastOnceDeliverySnapshot) {
return MergeFrom((AtLeastOnceDeliverySnapshot) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(AtLeastOnceDeliverySnapshot other) {
if (other == global::AtLeastOnceDeliverySnapshot.DefaultInstance) return this;
PrepareBuilder();
if (other.HasCurrentDeliveryId) {
CurrentDeliveryId = other.CurrentDeliveryId;
}
if (other.unconfirmedDeliveries_.Count != 0) {
result.unconfirmedDeliveries_.Add(other.unconfirmedDeliveries_);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_atLeastOnceDeliverySnapshotFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _atLeastOnceDeliverySnapshotFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasCurrentDeliveryId = input.ReadInt64(ref result.currentDeliveryId_);
break;
}
case 18: {
input.ReadMessageArray(tag, field_name, result.unconfirmedDeliveries_, global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery.DefaultInstance, extensionRegistry);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasCurrentDeliveryId {
get { return result.hasCurrentDeliveryId; }
}
public long CurrentDeliveryId {
get { return result.CurrentDeliveryId; }
set { SetCurrentDeliveryId(value); }
}
public Builder SetCurrentDeliveryId(long value) {
PrepareBuilder();
result.hasCurrentDeliveryId = true;
result.currentDeliveryId_ = value;
return this;
}
public Builder ClearCurrentDeliveryId() {
PrepareBuilder();
result.hasCurrentDeliveryId = false;
result.currentDeliveryId_ = 0L;
return this;
}
public pbc::IPopsicleList<global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery> UnconfirmedDeliveriesList {
get { return PrepareBuilder().unconfirmedDeliveries_; }
}
public int UnconfirmedDeliveriesCount {
get { return result.UnconfirmedDeliveriesCount; }
}
public global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery GetUnconfirmedDeliveries(int index) {
return result.GetUnconfirmedDeliveries(index);
}
public Builder SetUnconfirmedDeliveries(int index, global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.unconfirmedDeliveries_[index] = value;
return this;
}
public Builder SetUnconfirmedDeliveries(int index, global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.unconfirmedDeliveries_[index] = builderForValue.Build();
return this;
}
public Builder AddUnconfirmedDeliveries(global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.unconfirmedDeliveries_.Add(value);
return this;
}
public Builder AddUnconfirmedDeliveries(global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.unconfirmedDeliveries_.Add(builderForValue.Build());
return this;
}
public Builder AddRangeUnconfirmedDeliveries(scg::IEnumerable<global::AtLeastOnceDeliverySnapshot.Types.UnconfirmedDelivery> values) {
PrepareBuilder();
result.unconfirmedDeliveries_.Add(values);
return this;
}
public Builder ClearUnconfirmedDeliveries() {
PrepareBuilder();
result.unconfirmedDeliveries_.Clear();
return this;
}
}
static AtLeastOnceDeliverySnapshot() {
object.ReferenceEquals(global::PersistenceMessages.Descriptor, null);
}
}
#endregion
#endregion Designer generated code
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ReSharper disable UnassignedField.Global
// ReSharper disable CollectionNeverUpdated.Global
namespace Apache.Ignite.Core.Tests.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using NUnit.Framework;
/// <summary>
/// Binary builder self test.
/// </summary>
public class BinaryBuilderSelfTest
{
/** Undefined type: Empty. */
private const string TypeEmpty = "EmptyUndefined";
/** Grid. */
private Ignite _grid;
/** Marshaller. */
private Marshaller _marsh;
/// <summary>
/// Set up routine.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
TestUtils.KillProcesses();
var cfg = new IgniteConfiguration
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof (Empty)),
new BinaryTypeConfiguration(typeof (Primitives)),
new BinaryTypeConfiguration(typeof (PrimitiveArrays)),
new BinaryTypeConfiguration(typeof (StringDateGuidEnum)),
new BinaryTypeConfiguration(typeof (WithRaw)),
new BinaryTypeConfiguration(typeof (MetaOverwrite)),
new BinaryTypeConfiguration(typeof (NestedOuter)),
new BinaryTypeConfiguration(typeof (NestedInner)),
new BinaryTypeConfiguration(typeof (MigrationOuter)),
new BinaryTypeConfiguration(typeof (MigrationInner)),
new BinaryTypeConfiguration(typeof (InversionOuter)),
new BinaryTypeConfiguration(typeof (InversionInner)),
new BinaryTypeConfiguration(typeof (CompositeOuter)),
new BinaryTypeConfiguration(typeof (CompositeInner)),
new BinaryTypeConfiguration(typeof (CompositeArray)),
new BinaryTypeConfiguration(typeof (CompositeContainer)),
new BinaryTypeConfiguration(typeof (ToBinary)),
new BinaryTypeConfiguration(typeof (Remove)),
new BinaryTypeConfiguration(typeof (RemoveInner)),
new BinaryTypeConfiguration(typeof (BuilderInBuilderOuter)),
new BinaryTypeConfiguration(typeof (BuilderInBuilderInner)),
new BinaryTypeConfiguration(typeof (BuilderCollection)),
new BinaryTypeConfiguration(typeof (BuilderCollectionItem)),
new BinaryTypeConfiguration(typeof (DecimalHolder)),
new BinaryTypeConfiguration(TypeEmpty),
new BinaryTypeConfiguration(typeof(TestEnumRegistered))
},
DefaultIdMapper = new IdMapper()
},
JvmClasspath = TestUtils.CreateTestClasspath(),
JvmOptions = TestUtils.TestJavaOptions(),
SpringConfigUrl = "config\\binary.xml"
};
_grid = (Ignite) Ignition.Start(cfg);
_marsh = _grid.Marshaller;
}
/// <summary>
/// Tear down routine.
/// </summary>
[TestFixtureTearDown]
public virtual void TearDown()
{
if (_grid != null)
Ignition.Stop(_grid.Name, true);
_grid = null;
}
/// <summary>
/// Ensure that binary engine is able to work with type names, which are not configured.
/// </summary>
[Test]
public void TestNonConfigured()
{
string typeName1 = "Type1";
string typeName2 = "Type2";
string field1 = "field1";
string field2 = "field2";
// 1. Ensure that builder works fine.
IBinaryObject binObj1 = _grid.GetBinary().GetBuilder(typeName1).SetField(field1, 1).Build();
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 2. Ensure that object can be unmarshalled without deserialization.
byte[] data = ((BinaryObject) binObj1).Data;
binObj1 = _grid.Marshaller.Unmarshal<IBinaryObject>(data, BinaryMode.ForceBinary);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 3. Ensure that we can nest one anonymous object inside another
IBinaryObject binObj2 =
_grid.GetBinary().GetBuilder(typeName2).SetField(field2, binObj1).Build();
Assert.AreEqual(typeName2, binObj2.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj2.GetBinaryType().Fields.Count);
Assert.AreEqual(field2, binObj2.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, binObj2.GetBinaryType().GetFieldTypeName(field2));
binObj1 = binObj2.GetField<IBinaryObject>(field2);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 4. Ensure that we can unmarshal object with other nested object.
data = ((BinaryObject) binObj2).Data;
binObj2 = _grid.Marshaller.Unmarshal<IBinaryObject>(data, BinaryMode.ForceBinary);
Assert.AreEqual(typeName2, binObj2.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj2.GetBinaryType().Fields.Count);
Assert.AreEqual(field2, binObj2.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, binObj2.GetBinaryType().GetFieldTypeName(field2));
binObj1 = binObj2.GetField<IBinaryObject>(field2);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
}
/// <summary>
/// Test "ToBinary()" method.
/// </summary>
[Test]
public void TestToBinary()
{
DateTime date = DateTime.Now.ToUniversalTime();
Guid guid = Guid.NewGuid();
IBinary api = _grid.GetBinary();
// 1. Primitives.
Assert.AreEqual(1, api.ToBinary<byte>((byte)1));
Assert.AreEqual(1, api.ToBinary<short>((short)1));
Assert.AreEqual(1, api.ToBinary<int>(1));
Assert.AreEqual(1, api.ToBinary<long>((long)1));
Assert.AreEqual((float)1, api.ToBinary<float>((float)1));
Assert.AreEqual((double)1, api.ToBinary<double>((double)1));
Assert.AreEqual(true, api.ToBinary<bool>(true));
Assert.AreEqual('a', api.ToBinary<char>('a'));
// 2. Special types.
Assert.AreEqual("a", api.ToBinary<string>("a"));
Assert.AreEqual(date, api.ToBinary<DateTime>(date));
Assert.AreEqual(guid, api.ToBinary<Guid>(guid));
Assert.AreEqual(TestEnumRegistered.One, api.ToBinary<IBinaryObject>(TestEnumRegistered.One)
.Deserialize<TestEnumRegistered>());
// 3. Arrays.
Assert.AreEqual(new byte[] { 1 }, api.ToBinary<byte[]>(new byte[] { 1 }));
Assert.AreEqual(new short[] { 1 }, api.ToBinary<short[]>(new short[] { 1 }));
Assert.AreEqual(new[] { 1 }, api.ToBinary<int[]>(new[] { 1 }));
Assert.AreEqual(new long[] { 1 }, api.ToBinary<long[]>(new long[] { 1 }));
Assert.AreEqual(new float[] { 1 }, api.ToBinary<float[]>(new float[] { 1 }));
Assert.AreEqual(new double[] { 1 }, api.ToBinary<double[]>(new double[] { 1 }));
Assert.AreEqual(new[] { true }, api.ToBinary<bool[]>(new[] { true }));
Assert.AreEqual(new[] { 'a' }, api.ToBinary<char[]>(new[] { 'a' }));
Assert.AreEqual(new[] { "a" }, api.ToBinary<string[]>(new[] { "a" }));
Assert.AreEqual(new[] { date }, api.ToBinary<DateTime[]>(new[] { date }));
Assert.AreEqual(new[] { guid }, api.ToBinary<Guid[]>(new[] { guid }));
Assert.AreEqual(new[] { TestEnumRegistered.One},
api.ToBinary<IBinaryObject[]>(new[] { TestEnumRegistered.One})
.Select(x => x.Deserialize<TestEnumRegistered>()).ToArray());
// 4. Objects.
IBinaryObject binObj = api.ToBinary<IBinaryObject>(new ToBinary(1));
Assert.AreEqual(typeof(ToBinary).Name, binObj.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj.GetBinaryType().Fields.Count);
Assert.AreEqual("Val", binObj.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj.GetBinaryType().GetFieldTypeName("Val"));
Assert.AreEqual(1, binObj.GetField<int>("val"));
Assert.AreEqual(1, binObj.Deserialize<ToBinary>().Val);
// 5. Object array.
var binObjArr = api.ToBinary<object[]>(new object[] {new ToBinary(1)})
.OfType<IBinaryObject>().ToArray();
Assert.AreEqual(1, binObjArr.Length);
Assert.AreEqual(1, binObjArr[0].GetField<int>("Val"));
Assert.AreEqual(1, binObjArr[0].Deserialize<ToBinary>().Val);
}
/// <summary>
/// Test builder field remove logic.
/// </summary>
[Test]
public void TestRemove()
{
// Create empty object.
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Remove)).Build();
Assert.IsNull(binObj.GetField<object>("val"));
Assert.IsNull(binObj.Deserialize<Remove>().Val);
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(Remove).Name, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
// Populate it with field.
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(binObj);
Assert.IsNull(builder.GetField<object>("val"));
object val = 1;
builder.SetField("val", val);
Assert.AreEqual(val, builder.GetField<object>("val"));
binObj = builder.Build();
Assert.AreEqual(val, binObj.GetField<object>("val"));
Assert.AreEqual(val, binObj.Deserialize<Remove>().Val);
meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(Remove).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("val", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("val"));
// Perform field remove.
builder = _grid.GetBinary().GetBuilder(binObj);
Assert.AreEqual(val, builder.GetField<object>("val"));
builder.RemoveField("val");
Assert.IsNull(builder.GetField<object>("val"));
builder.SetField("val", val);
Assert.AreEqual(val, builder.GetField<object>("val"));
builder.RemoveField("val");
Assert.IsNull(builder.GetField<object>("val"));
binObj = builder.Build();
Assert.IsNull(binObj.GetField<object>("val"));
Assert.IsNull(binObj.Deserialize<Remove>().Val);
// Test correct removal of field being referenced by handle somewhere else.
RemoveInner inner = new RemoveInner(2);
binObj = _grid.GetBinary().GetBuilder(typeof(Remove))
.SetField("val", inner)
.SetField("val2", inner)
.Build();
binObj = _grid.GetBinary().GetBuilder(binObj).RemoveField("val").Build();
Remove obj = binObj.Deserialize<Remove>();
Assert.IsNull(obj.Val);
Assert.AreEqual(2, obj.Val2.Val);
}
/// <summary>
/// Test builder-in-builder scenario.
/// </summary>
[Test]
public void TestBuilderInBuilder()
{
// Test different builders assembly.
IBinaryObjectBuilder builderOuter = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderOuter));
IBinaryObjectBuilder builderInner = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderInner));
builderOuter.SetField<object>("inner", builderInner);
builderInner.SetField<object>("outer", builderOuter);
IBinaryObject outerbinObj = builderOuter.Build();
IBinaryType meta = outerbinObj.GetBinaryType();
Assert.AreEqual(typeof(BuilderInBuilderOuter).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("inner", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner"));
IBinaryObject innerbinObj = outerbinObj.GetField<IBinaryObject>("inner");
meta = innerbinObj.GetBinaryType();
Assert.AreEqual(typeof(BuilderInBuilderInner).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("outer", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("outer"));
BuilderInBuilderOuter outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer, outer.Inner.Outer);
// Test same builders assembly.
innerbinObj = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderInner)).Build();
outerbinObj = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderOuter))
.SetField("inner", innerbinObj)
.SetField("inner2", innerbinObj)
.Build();
meta = outerbinObj.GetBinaryType();
Assert.AreEqual(typeof(BuilderInBuilderOuter).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.IsTrue(meta.Fields.Contains("inner"));
Assert.IsTrue(meta.Fields.Contains("inner2"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner2"));
outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer.Inner, outer.Inner2);
builderOuter = _grid.GetBinary().GetBuilder(outerbinObj);
IBinaryObjectBuilder builderInner2 = builderOuter.GetField<IBinaryObjectBuilder>("inner2");
builderInner2.SetField("outer", builderOuter);
outerbinObj = builderOuter.Build();
outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer, outer.Inner.Outer);
Assert.AreSame(outer.Inner, outer.Inner2);
}
/// <summary>
/// Test for decimals building.
/// </summary>
[Test]
public void TestDecimals()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(DecimalHolder))
.SetField("val", decimal.One)
.SetField("valArr", new decimal?[] { decimal.MinusOne })
.Build();
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(DecimalHolder).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.IsTrue(meta.Fields.Contains("val"));
Assert.IsTrue(meta.Fields.Contains("valArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameDecimal, meta.GetFieldTypeName("val"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDecimal, meta.GetFieldTypeName("valArr"));
Assert.AreEqual(decimal.One, binObj.GetField<decimal>("val"));
Assert.AreEqual(new decimal?[] { decimal.MinusOne }, binObj.GetField<decimal?[]>("valArr"));
DecimalHolder obj = binObj.Deserialize<DecimalHolder>();
Assert.AreEqual(decimal.One, obj.Val);
Assert.AreEqual(new decimal?[] { decimal.MinusOne }, obj.ValArr);
}
/// <summary>
/// Test for an object returning collection of builders.
/// </summary>
[Test]
public void TestBuilderCollection()
{
// Test collection with single element.
IBinaryObjectBuilder builderCol = _grid.GetBinary().GetBuilder(typeof(BuilderCollection));
IBinaryObjectBuilder builderItem =
_grid.GetBinary().GetBuilder(typeof(BuilderCollectionItem)).SetField("val", 1);
builderCol.SetCollectionField("col", new ArrayList { builderItem });
IBinaryObject binCol = builderCol.Build();
IBinaryType meta = binCol.GetBinaryType();
Assert.AreEqual(typeof(BuilderCollection).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("col", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameCollection, meta.GetFieldTypeName("col"));
var binColItems = binCol.GetField<ArrayList>("col");
Assert.AreEqual(1, binColItems.Count);
var binItem = (IBinaryObject) binColItems[0];
meta = binItem.GetBinaryType();
Assert.AreEqual(typeof(BuilderCollectionItem).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("val", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, meta.GetFieldTypeName("val"));
BuilderCollection col = binCol.Deserialize<BuilderCollection>();
Assert.IsNotNull(col.Col);
Assert.AreEqual(1, col.Col.Count);
Assert.AreEqual(1, ((BuilderCollectionItem) col.Col[0]).Val);
// Add more binary objects to collection.
builderCol = _grid.GetBinary().GetBuilder(binCol);
IList builderColItems = builderCol.GetField<IList>("col");
Assert.AreEqual(1, builderColItems.Count);
BinaryObjectBuilder builderColItem = (BinaryObjectBuilder) builderColItems[0];
builderColItem.SetField("val", 2); // Change nested value.
builderColItems.Add(builderColItem); // Add the same object to check handles.
builderColItems.Add(builderItem); // Add item from another builder.
builderColItems.Add(binItem); // Add item in binary form.
binCol = builderCol.Build();
col = binCol.Deserialize<BuilderCollection>();
Assert.AreEqual(4, col.Col.Count);
var item0 = (BuilderCollectionItem) col.Col[0];
var item1 = (BuilderCollectionItem) col.Col[1];
var item2 = (BuilderCollectionItem) col.Col[2];
var item3 = (BuilderCollectionItem) col.Col[3];
Assert.AreEqual(2, item0.Val);
Assert.AreSame(item0, item1);
Assert.AreNotSame(item0, item2);
Assert.AreNotSame(item0, item3);
Assert.AreEqual(1, item2.Val);
Assert.AreEqual(1, item3.Val);
Assert.AreNotSame(item2, item3);
// Test handle update inside collection.
builderCol = _grid.GetBinary().GetBuilder(binCol);
builderColItems = builderCol.GetField<IList>("col");
((BinaryObjectBuilder) builderColItems[1]).SetField("val", 3);
binCol = builderCol.Build();
col = binCol.Deserialize<BuilderCollection>();
item0 = (BuilderCollectionItem) col.Col[0];
item1 = (BuilderCollectionItem) col.Col[1];
Assert.AreEqual(3, item0.Val);
Assert.AreSame(item0, item1);
}
/// <summary>
/// Test build of an empty object.
/// </summary>
[Test]
public void TestEmptyDefined()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Empty)).Build();
Assert.IsNotNull(binObj);
Assert.AreEqual(0, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.IsNotNull(meta);
Assert.AreEqual(typeof(Empty).Name, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
Empty obj = binObj.Deserialize<Empty>();
Assert.IsNotNull(obj);
}
/// <summary>
/// Test build of an empty undefined object.
/// </summary>
[Test]
public void TestEmptyUndefined()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(TypeEmpty).Build();
Assert.IsNotNull(binObj);
Assert.AreEqual(0, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.IsNotNull(meta);
Assert.AreEqual(TypeEmpty, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
}
/// <summary>
/// Test object rebuild with no changes.
/// </summary>
[Test]
public void TestEmptyRebuild()
{
var binObj = (BinaryObject) _grid.GetBinary().GetBuilder(typeof(Empty)).Build();
BinaryObject newbinObj = (BinaryObject) _grid.GetBinary().GetBuilder(binObj).Build();
Assert.AreEqual(binObj.Data, newbinObj.Data);
}
/// <summary>
/// Test hash code alteration.
/// </summary>
[Test]
public void TestHashCodeChange()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Empty)).SetHashCode(100).Build();
Assert.AreEqual(100, binObj.GetHashCode());
}
/// <summary>
/// Test primitive fields setting.
/// </summary>
[Test]
public void TestPrimitiveFields()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Primitives))
.SetField<byte>("fByte", 1)
.SetField("fBool", true)
.SetField<short>("fShort", 2)
.SetField("fChar", 'a')
.SetField("fInt", 3)
.SetField<long>("fLong", 4)
.SetField<float>("fFloat", 5)
.SetField<double>("fDouble", 6)
.SetHashCode(100)
.Build();
Assert.AreEqual(100, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(Primitives).Name, meta.TypeName);
Assert.AreEqual(8, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameByte, meta.GetFieldTypeName("fByte"));
Assert.AreEqual(BinaryTypeNames.TypeNameBool, meta.GetFieldTypeName("fBool"));
Assert.AreEqual(BinaryTypeNames.TypeNameShort, meta.GetFieldTypeName("fShort"));
Assert.AreEqual(BinaryTypeNames.TypeNameChar, meta.GetFieldTypeName("fChar"));
Assert.AreEqual(BinaryTypeNames.TypeNameInt, meta.GetFieldTypeName("fInt"));
Assert.AreEqual(BinaryTypeNames.TypeNameLong, meta.GetFieldTypeName("fLong"));
Assert.AreEqual(BinaryTypeNames.TypeNameFloat, meta.GetFieldTypeName("fFloat"));
Assert.AreEqual(BinaryTypeNames.TypeNameDouble, meta.GetFieldTypeName("fDouble"));
Assert.AreEqual(1, binObj.GetField<byte>("fByte"));
Assert.AreEqual(true, binObj.GetField<bool>("fBool"));
Assert.AreEqual(2, binObj.GetField<short>("fShort"));
Assert.AreEqual('a', binObj.GetField<char>("fChar"));
Assert.AreEqual(3, binObj.GetField<int>("fInt"));
Assert.AreEqual(4, binObj.GetField<long>("fLong"));
Assert.AreEqual(5, binObj.GetField<float>("fFloat"));
Assert.AreEqual(6, binObj.GetField<double>("fDouble"));
Primitives obj = binObj.Deserialize<Primitives>();
Assert.AreEqual(1, obj.FByte);
Assert.AreEqual(true, obj.FBool);
Assert.AreEqual(2, obj.FShort);
Assert.AreEqual('a', obj.FChar);
Assert.AreEqual(3, obj.FInt);
Assert.AreEqual(4, obj.FLong);
Assert.AreEqual(5, obj.FFloat);
Assert.AreEqual(6, obj.FDouble);
// Overwrite.
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField<byte>("fByte", 7)
.SetField("fBool", false)
.SetField<short>("fShort", 8)
.SetField("fChar", 'b')
.SetField("fInt", 9)
.SetField<long>("fLong", 10)
.SetField<float>("fFloat", 11)
.SetField<double>("fDouble", 12)
.SetHashCode(200)
.Build();
Assert.AreEqual(200, binObj.GetHashCode());
Assert.AreEqual(7, binObj.GetField<byte>("fByte"));
Assert.AreEqual(false, binObj.GetField<bool>("fBool"));
Assert.AreEqual(8, binObj.GetField<short>("fShort"));
Assert.AreEqual('b', binObj.GetField<char>("fChar"));
Assert.AreEqual(9, binObj.GetField<int>("fInt"));
Assert.AreEqual(10, binObj.GetField<long>("fLong"));
Assert.AreEqual(11, binObj.GetField<float>("fFloat"));
Assert.AreEqual(12, binObj.GetField<double>("fDouble"));
obj = binObj.Deserialize<Primitives>();
Assert.AreEqual(7, obj.FByte);
Assert.AreEqual(false, obj.FBool);
Assert.AreEqual(8, obj.FShort);
Assert.AreEqual('b', obj.FChar);
Assert.AreEqual(9, obj.FInt);
Assert.AreEqual(10, obj.FLong);
Assert.AreEqual(11, obj.FFloat);
Assert.AreEqual(12, obj.FDouble);
}
/// <summary>
/// Test primitive array fields setting.
/// </summary>
[Test]
public void TestPrimitiveArrayFields()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(PrimitiveArrays))
.SetField("fByte", new byte[] { 1 })
.SetField("fBool", new[] { true })
.SetField("fShort", new short[] { 2 })
.SetField("fChar", new[] { 'a' })
.SetField("fInt", new[] { 3 })
.SetField("fLong", new long[] { 4 })
.SetField("fFloat", new float[] { 5 })
.SetField("fDouble", new double[] { 6 })
.SetHashCode(100)
.Build();
Assert.AreEqual(100, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(PrimitiveArrays).Name, meta.TypeName);
Assert.AreEqual(8, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayByte, meta.GetFieldTypeName("fByte"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayBool, meta.GetFieldTypeName("fBool"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayShort, meta.GetFieldTypeName("fShort"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayChar, meta.GetFieldTypeName("fChar"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayInt, meta.GetFieldTypeName("fInt"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayLong, meta.GetFieldTypeName("fLong"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayFloat, meta.GetFieldTypeName("fFloat"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDouble, meta.GetFieldTypeName("fDouble"));
Assert.AreEqual(new byte[] { 1 }, binObj.GetField<byte[]>("fByte"));
Assert.AreEqual(new[] { true }, binObj.GetField<bool[]>("fBool"));
Assert.AreEqual(new short[] { 2 }, binObj.GetField<short[]>("fShort"));
Assert.AreEqual(new[] { 'a' }, binObj.GetField<char[]>("fChar"));
Assert.AreEqual(new[] { 3 }, binObj.GetField<int[]>("fInt"));
Assert.AreEqual(new long[] { 4 }, binObj.GetField<long[]>("fLong"));
Assert.AreEqual(new float[] { 5 }, binObj.GetField<float[]>("fFloat"));
Assert.AreEqual(new double[] { 6 }, binObj.GetField<double[]>("fDouble"));
PrimitiveArrays obj = binObj.Deserialize<PrimitiveArrays>();
Assert.AreEqual(new byte[] { 1 }, obj.FByte);
Assert.AreEqual(new[] { true }, obj.FBool);
Assert.AreEqual(new short[] { 2 }, obj.FShort);
Assert.AreEqual(new[] { 'a' }, obj.FChar);
Assert.AreEqual(new[] { 3 }, obj.FInt);
Assert.AreEqual(new long[] { 4 }, obj.FLong);
Assert.AreEqual(new float[] { 5 }, obj.FFloat);
Assert.AreEqual(new double[] { 6 }, obj.FDouble);
// Overwrite.
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("fByte", new byte[] { 7 })
.SetField("fBool", new[] { false })
.SetField("fShort", new short[] { 8 })
.SetField("fChar", new[] { 'b' })
.SetField("fInt", new[] { 9 })
.SetField("fLong", new long[] { 10 })
.SetField("fFloat", new float[] { 11 })
.SetField("fDouble", new double[] { 12 })
.SetHashCode(200)
.Build();
Assert.AreEqual(200, binObj.GetHashCode());
Assert.AreEqual(new byte[] { 7 }, binObj.GetField<byte[]>("fByte"));
Assert.AreEqual(new[] { false }, binObj.GetField<bool[]>("fBool"));
Assert.AreEqual(new short[] { 8 }, binObj.GetField<short[]>("fShort"));
Assert.AreEqual(new[] { 'b' }, binObj.GetField<char[]>("fChar"));
Assert.AreEqual(new[] { 9 }, binObj.GetField<int[]>("fInt"));
Assert.AreEqual(new long[] { 10 }, binObj.GetField<long[]>("fLong"));
Assert.AreEqual(new float[] { 11 }, binObj.GetField<float[]>("fFloat"));
Assert.AreEqual(new double[] { 12 }, binObj.GetField<double[]>("fDouble"));
obj = binObj.Deserialize<PrimitiveArrays>();
Assert.AreEqual(new byte[] { 7 }, obj.FByte);
Assert.AreEqual(new[] { false }, obj.FBool);
Assert.AreEqual(new short[] { 8 }, obj.FShort);
Assert.AreEqual(new[] { 'b' }, obj.FChar);
Assert.AreEqual(new[] { 9 }, obj.FInt);
Assert.AreEqual(new long[] { 10 }, obj.FLong);
Assert.AreEqual(new float[] { 11 }, obj.FFloat);
Assert.AreEqual(new double[] { 12 }, obj.FDouble);
}
/// <summary>
/// Test non-primitive fields and their array counterparts.
/// </summary>
[Test]
public void TestStringDateGuidEnum()
{
DateTime? nDate = DateTime.Now;
Guid? nGuid = Guid.NewGuid();
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetField("fStr", "str")
.SetField("fNDate", nDate)
.SetGuidField("fNGuid", nGuid)
.SetField("fEnum", TestEnum.One)
.SetField("fStrArr", new[] { "str" })
.SetArrayField("fDateArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetField("fEnumArr", new[] { TestEnum.One })
.SetHashCode(100)
.Build();
Assert.AreEqual(100, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(StringDateGuidEnum).Name, meta.TypeName);
Assert.AreEqual(8, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameString, meta.GetFieldTypeName("fStr"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("fNDate"));
Assert.AreEqual(BinaryTypeNames.TypeNameGuid, meta.GetFieldTypeName("fNGuid"));
Assert.AreEqual(BinaryTypeNames.TypeNameEnum, meta.GetFieldTypeName("fEnum"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayString, meta.GetFieldTypeName("fStrArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("fDateArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayGuid, meta.GetFieldTypeName("fGuidArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayEnum, meta.GetFieldTypeName("fEnumArr"));
Assert.AreEqual("str", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, binObj.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] { "str" }, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] { nDate }, binObj.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] { nGuid }, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One}, binObj.GetField<TestEnum[]>("fEnumArr"));
StringDateGuidEnum obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.One, obj.FEnum);
Assert.AreEqual(new[] { "str" }, obj.FStrArr);
Assert.AreEqual(new[] { nDate }, obj.FDateArr);
Assert.AreEqual(new[] { nGuid }, obj.FGuidArr);
Assert.AreEqual(new[] { TestEnum.One }, obj.FEnumArr);
// Check builder field caching.
var builder = _grid.GetBinary().GetBuilder(binObj);
Assert.AreEqual("str", builder.GetField<string>("fStr"));
Assert.AreEqual(nDate, builder.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nGuid, builder.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, builder.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] { "str" }, builder.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] { nDate }, builder.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] { nGuid }, builder.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One}, builder.GetField<TestEnum[]>("fEnumArr"));
// Check reassemble.
binObj = builder.Build();
Assert.AreEqual("str", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, binObj.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] { "str" }, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] { nDate }, binObj.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] { nGuid }, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One}, binObj.GetField<TestEnum[]>("fEnumArr"));
obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.One, obj.FEnum);
Assert.AreEqual(new[] { "str" }, obj.FStrArr);
Assert.AreEqual(new[] { nDate }, obj.FDateArr);
Assert.AreEqual(new[] { nGuid }, obj.FGuidArr);
Assert.AreEqual(new[] { TestEnum.One }, obj.FEnumArr);
// Overwrite.
nDate = DateTime.Now.ToUniversalTime();
nGuid = Guid.NewGuid();
binObj = builder
.SetField("fStr", "str2")
.SetTimestampField("fNDate", nDate)
.SetField("fNGuid", nGuid)
.SetField("fEnum", TestEnum.Two)
.SetField("fStrArr", new[] { "str2" })
.SetArrayField("fDateArr", new[] { nDate })
.SetField("fGuidArr", new[] { nGuid })
.SetField("fEnumArr", new[] { TestEnum.Two })
.SetHashCode(200)
.Build();
Assert.AreEqual(200, binObj.GetHashCode());
Assert.AreEqual("str2", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.Two, binObj.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] { "str2" }, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] { nDate }, binObj.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] { nGuid }, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.Two}, binObj.GetField<TestEnum[]>("fEnumArr"));
obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str2", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.Two, obj.FEnum);
Assert.AreEqual(new[] { "str2" }, obj.FStrArr);
Assert.AreEqual(new[] { nDate }, obj.FDateArr);
Assert.AreEqual(new[] { nGuid }, obj.FGuidArr);
Assert.AreEqual(new[] { TestEnum.Two }, obj.FEnumArr);
}
[Test]
public void TestEnumMeta()
{
var bin = _grid.GetBinary();
// Put to cache to populate metas
var binEnum = bin.ToBinary<IBinaryObject>(TestEnumRegistered.One);
Assert.AreEqual(_marsh.GetDescriptor(typeof (TestEnumRegistered)).TypeId, binEnum.GetBinaryType().TypeId);
Assert.AreEqual(0, binEnum.EnumValue);
var meta = binEnum.GetBinaryType();
Assert.IsTrue(meta.IsEnum);
Assert.AreEqual(typeof (TestEnumRegistered).Name, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
}
/// <summary>
/// Test arrays.
/// </summary>
[Test]
public void TestCompositeArray()
{
// 1. Test simple array.
object[] inArr = { new CompositeInner(1) };
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray)).SetHashCode(100)
.SetField("inArr", inArr).Build();
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(CompositeArray).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("inArr"));
Assert.AreEqual(100, binObj.GetHashCode());
var binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(1, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
CompositeArray arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(1, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner) arr.InArr[0]).Val);
// 2. Test addition to array.
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(200)
.SetField("inArr", new[] { binInArr[0], null }).Build();
Assert.AreEqual(200, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.IsNull(binInArr[1]);
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner) arr.InArr[0]).Val);
Assert.IsNull(arr.InArr[1]);
binInArr[1] = _grid.GetBinary().GetBuilder(typeof(CompositeInner)).SetField("val", 2).Build();
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(300)
.SetField("inArr", binInArr.OfType<object>().ToArray()).Build();
Assert.AreEqual(300, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.AreEqual(2, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(2, ((CompositeInner)arr.InArr[1]).Val);
// 3. Test top-level handle inversion.
CompositeInner inner = new CompositeInner(1);
inArr = new object[] { inner, inner };
binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray)).SetHashCode(100)
.SetField("inArr", inArr).Build();
Assert.AreEqual(100, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.AreEqual(1, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[1]).Val);
binInArr[0] = _grid.GetBinary().GetBuilder(typeof(CompositeInner)).SetField("val", 2).Build();
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(200)
.SetField("inArr", binInArr.ToArray<object>()).Build();
Assert.AreEqual(200, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(2, binInArr[0].GetField<int>("val"));
Assert.AreEqual(1, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(2, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[1]).Val);
// 4. Test nested object handle inversion.
CompositeOuter[] outArr = { new CompositeOuter(inner), new CompositeOuter(inner) };
binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray)).SetHashCode(100)
.SetField("outArr", outArr.ToArray<object>()).Build();
meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(CompositeArray).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("inArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("outArr"));
Assert.AreEqual(100, binObj.GetHashCode());
var binOutArr = binObj.GetField<IBinaryObject[]>("outArr").ToArray();
Assert.AreEqual(2, binOutArr.Length);
Assert.AreEqual(1, binOutArr[0].GetField<IBinaryObject>("inner").GetField<int>("val"));
Assert.AreEqual(1, binOutArr[1].GetField<IBinaryObject>("inner").GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.InArr);
Assert.AreEqual(2, arr.OutArr.Length);
Assert.AreEqual(1, ((CompositeOuter) arr.OutArr[0]).Inner.Val);
Assert.AreEqual(1, ((CompositeOuter) arr.OutArr[0]).Inner.Val);
binOutArr[0] = _grid.GetBinary().GetBuilder(typeof(CompositeOuter))
.SetField("inner", new CompositeInner(2)).Build();
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(200)
.SetField("outArr", binOutArr.ToArray<object>()).Build();
Assert.AreEqual(200, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("outArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(2, binOutArr[0].GetField<IBinaryObject>("inner").GetField<int>("val"));
Assert.AreEqual(1, binOutArr[1].GetField<IBinaryObject>("inner").GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.InArr);
Assert.AreEqual(2, arr.OutArr.Length);
Assert.AreEqual(2, ((CompositeOuter)arr.OutArr[0]).Inner.Val);
Assert.AreEqual(1, ((CompositeOuter)arr.OutArr[1]).Inner.Val);
}
/// <summary>
/// Test container types other than array.
/// </summary>
[Test]
public void TestCompositeContainer()
{
ArrayList col = new ArrayList();
IDictionary dict = new Hashtable();
col.Add(new CompositeInner(1));
dict[3] = new CompositeInner(3);
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(CompositeContainer)).SetHashCode(100)
.SetCollectionField("col", col)
.SetDictionaryField("dict", dict).Build();
// 1. Check meta.
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(CompositeContainer).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameCollection, meta.GetFieldTypeName("col"));
Assert.AreEqual(BinaryTypeNames.TypeNameMap, meta.GetFieldTypeName("dict"));
// 2. Check in binary form.
Assert.AreEqual(1, binObj.GetField<ICollection>("col").Count);
Assert.AreEqual(1, binObj.GetField<ICollection>("col").OfType<IBinaryObject>().First()
.GetField<int>("val"));
Assert.AreEqual(1, binObj.GetField<IDictionary>("dict").Count);
Assert.AreEqual(3, ((IBinaryObject) binObj.GetField<IDictionary>("dict")[3]).GetField<int>("val"));
// 3. Check in deserialized form.
CompositeContainer obj = binObj.Deserialize<CompositeContainer>();
Assert.AreEqual(1, obj.Col.Count);
Assert.AreEqual(1, obj.Col.OfType<CompositeInner>().First().Val);
Assert.AreEqual(1, obj.Dict.Count);
Assert.AreEqual(3, ((CompositeInner) obj.Dict[3]).Val);
}
/// <summary>
/// Ensure that raw data is not lost during build.
/// </summary>
[Test]
public void TestRawData()
{
var raw = new WithRaw
{
A = 1,
B = 2
};
var binObj = _marsh.Unmarshal<IBinaryObject>(_marsh.Marshal(raw), BinaryMode.ForceBinary);
raw = binObj.Deserialize<WithRaw>();
Assert.AreEqual(1, raw.A);
Assert.AreEqual(2, raw.B);
IBinaryObject newbinObj = _grid.GetBinary().GetBuilder(binObj).SetField("a", 3).Build();
raw = newbinObj.Deserialize<WithRaw>();
Assert.AreEqual(3, raw.A);
Assert.AreEqual(2, raw.B);
}
/// <summary>
/// Test nested objects.
/// </summary>
[Test]
public void TestNested()
{
// 1. Create from scratch.
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(NestedOuter));
NestedInner inner1 = new NestedInner {Val = 1};
builder.SetField("inner1", inner1);
IBinaryObject outerbinObj = builder.Build();
IBinaryType meta = outerbinObj.GetBinaryType();
Assert.AreEqual(typeof(NestedOuter).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner1"));
IBinaryObject innerbinObj1 = outerbinObj.GetField<IBinaryObject>("inner1");
IBinaryType innerMeta = innerbinObj1.GetBinaryType();
Assert.AreEqual(typeof(NestedInner).Name, innerMeta.TypeName);
Assert.AreEqual(1, innerMeta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameInt, innerMeta.GetFieldTypeName("Val"));
inner1 = innerbinObj1.Deserialize<NestedInner>();
Assert.AreEqual(1, inner1.Val);
NestedOuter outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(outer.Inner1.Val, 1);
Assert.IsNull(outer.Inner2);
// 2. Add another field over existing binary object.
builder = _grid.GetBinary().GetBuilder(outerbinObj);
NestedInner inner2 = new NestedInner {Val = 2};
builder.SetField("inner2", inner2);
outerbinObj = builder.Build();
outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(1, outer.Inner1.Val);
Assert.AreEqual(2, outer.Inner2.Val);
// 3. Try setting inner object in binary form.
innerbinObj1 = _grid.GetBinary().GetBuilder(innerbinObj1).SetField("val", 3).Build();
inner1 = innerbinObj1.Deserialize<NestedInner>();
Assert.AreEqual(3, inner1.Val);
outerbinObj = _grid.GetBinary().GetBuilder(outerbinObj).SetField<object>("inner1", innerbinObj1).Build();
outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(3, outer.Inner1.Val);
Assert.AreEqual(2, outer.Inner2.Val);
}
/// <summary>
/// Test handle migration.
/// </summary>
[Test]
public void TestHandleMigration()
{
// 1. Simple comparison of results.
MigrationInner inner = new MigrationInner {Val = 1};
MigrationOuter outer = new MigrationOuter
{
Inner1 = inner,
Inner2 = inner
};
byte[] outerBytes = _marsh.Marshal(outer);
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(MigrationOuter));
builder.SetHashCode(outer.GetHashCode());
builder.SetField<object>("inner1", inner);
builder.SetField<object>("inner2", inner);
BinaryObject portOuter = (BinaryObject) builder.Build();
byte[] portOuterBytes = new byte[outerBytes.Length];
Buffer.BlockCopy(portOuter.Data, 0, portOuterBytes, 0, portOuterBytes.Length);
Assert.AreEqual(outerBytes, portOuterBytes);
// 2. Change the first inner object so that the handle must migrate.
MigrationInner inner1 = new MigrationInner {Val = 2};
IBinaryObject portOuterMigrated =
_grid.GetBinary().GetBuilder(portOuter).SetField<object>("inner1", inner1).Build();
MigrationOuter outerMigrated = portOuterMigrated.Deserialize<MigrationOuter>();
Assert.AreEqual(2, outerMigrated.Inner1.Val);
Assert.AreEqual(1, outerMigrated.Inner2.Val);
// 3. Change the first value using serialized form.
IBinaryObject inner1Port =
_grid.GetBinary().GetBuilder(typeof(MigrationInner)).SetField("val", 2).Build();
portOuterMigrated =
_grid.GetBinary().GetBuilder(portOuter).SetField<object>("inner1", inner1Port).Build();
outerMigrated = portOuterMigrated.Deserialize<MigrationOuter>();
Assert.AreEqual(2, outerMigrated.Inner1.Val);
Assert.AreEqual(1, outerMigrated.Inner2.Val);
}
/// <summary>
/// Test handle inversion.
/// </summary>
[Test]
public void TestHandleInversion()
{
InversionInner inner = new InversionInner();
InversionOuter outer = new InversionOuter();
inner.Outer = outer;
outer.Inner = inner;
byte[] rawOuter = _marsh.Marshal(outer);
IBinaryObject portOuter = _marsh.Unmarshal<IBinaryObject>(rawOuter, BinaryMode.ForceBinary);
IBinaryObject portInner = portOuter.GetField<IBinaryObject>("inner");
// 1. Ensure that inner object can be deserialized after build.
IBinaryObject portInnerNew = _grid.GetBinary().GetBuilder(portInner).Build();
InversionInner innerNew = portInnerNew.Deserialize<InversionInner>();
Assert.AreSame(innerNew, innerNew.Outer.Inner);
// 2. Ensure that binary object with external dependencies could be added to builder.
IBinaryObject portOuterNew =
_grid.GetBinary().GetBuilder(typeof(InversionOuter)).SetField<object>("inner", portInner).Build();
InversionOuter outerNew = portOuterNew.Deserialize<InversionOuter>();
Assert.AreNotSame(outerNew, outerNew.Inner.Outer);
Assert.AreSame(outerNew.Inner, outerNew.Inner.Outer.Inner);
}
/// <summary>
/// Test build multiple objects.
/// </summary>
[Test]
public void TestBuildMultiple()
{
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(Primitives));
builder.SetField<byte>("fByte", 1).SetField("fBool", true);
IBinaryObject po1 = builder.Build();
IBinaryObject po2 = builder.Build();
Assert.AreEqual(1, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(1, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
builder.SetField<byte>("fByte", 2);
IBinaryObject po3 = builder.Build();
Assert.AreEqual(1, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(1, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
Assert.AreEqual(2, po3.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
builder = _grid.GetBinary().GetBuilder(po1);
builder.SetField<byte>("fByte", 10);
po1 = builder.Build();
po2 = builder.Build();
builder.SetField<byte>("fByte", 20);
po3 = builder.Build();
Assert.AreEqual(10, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(10, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
Assert.AreEqual(20, po3.GetField<byte>("fByte"));
Assert.AreEqual(true, po3.GetField<bool>("fBool"));
}
/// <summary>
/// Tests type id method.
/// </summary>
[Test]
public void TestTypeId()
{
Assert.Throws<ArgumentException>(() => _grid.GetBinary().GetTypeId(null));
Assert.AreEqual(IdMapper.TestTypeId, _grid.GetBinary().GetTypeId(IdMapper.TestTypeName));
Assert.AreEqual(BinaryUtils.GetStringHashCode("someTypeName"), _grid.GetBinary().GetTypeId("someTypeName"));
}
/// <summary>
/// Tests metadata methods.
/// </summary>
[Test]
public void TestMetadata()
{
// Populate metadata
var binary = _grid.GetBinary();
binary.ToBinary<IBinaryObject>(new DecimalHolder());
// All meta
var allMetas = binary.GetBinaryTypes();
var decimalMeta = allMetas.Single(x => x.TypeName == "DecimalHolder");
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type
decimalMeta = binary.GetBinaryType(typeof (DecimalHolder));
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type id
decimalMeta = binary.GetBinaryType(binary.GetTypeId("DecimalHolder"));
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type name
decimalMeta = binary.GetBinaryType("DecimalHolder");
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
}
[Test]
public void TestBuildEnum()
{
var binary = _grid.GetBinary();
int val = (int) TestEnumRegistered.Two;
var binEnums = new[]
{
binary.BuildEnum(typeof (TestEnumRegistered), val),
binary.BuildEnum(typeof (TestEnumRegistered).Name, val)
};
foreach (var binEnum in binEnums)
{
Assert.IsTrue(binEnum.GetBinaryType().IsEnum);
Assert.AreEqual(val, binEnum.EnumValue);
Assert.AreEqual((TestEnumRegistered)val, binEnum.Deserialize<TestEnumRegistered>());
}
}
}
/// <summary>
/// Empty binary class.
/// </summary>
public class Empty
{
// No-op.
}
/// <summary>
/// binary with primitive fields.
/// </summary>
public class Primitives
{
public byte FByte;
public bool FBool;
public short FShort;
public char FChar;
public int FInt;
public long FLong;
public float FFloat;
public double FDouble;
}
/// <summary>
/// binary with primitive array fields.
/// </summary>
public class PrimitiveArrays
{
public byte[] FByte;
public bool[] FBool;
public short[] FShort;
public char[] FChar;
public int[] FInt;
public long[] FLong;
public float[] FFloat;
public double[] FDouble;
}
/// <summary>
/// binary having strings, dates, Guids and enums.
/// </summary>
public class StringDateGuidEnum
{
public string FStr;
public DateTime? FnDate;
public Guid? FnGuid;
public TestEnum FEnum;
public string[] FStrArr;
public DateTime?[] FDateArr;
public Guid?[] FGuidArr;
public TestEnum[] FEnumArr;
}
/// <summary>
/// Enumeration.
/// </summary>
public enum TestEnum
{
One, Two
}
/// <summary>
/// Registered enumeration.
/// </summary>
public enum TestEnumRegistered
{
One, Two
}
/// <summary>
/// binary with raw data.
/// </summary>
public class WithRaw : IBinarizable
{
public int A;
public int B;
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
writer.WriteInt("a", A);
writer.GetRawWriter().WriteInt(B);
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
A = reader.ReadInt("a");
B = reader.GetRawReader().ReadInt();
}
}
/// <summary>
/// Empty class for metadata overwrite test.
/// </summary>
public class MetaOverwrite
{
// No-op.
}
/// <summary>
/// Nested outer object.
/// </summary>
public class NestedOuter
{
public NestedInner Inner1;
public NestedInner Inner2;
}
/// <summary>
/// Nested inner object.
/// </summary>
public class NestedInner
{
public int Val;
}
/// <summary>
/// Outer object for handle migration test.
/// </summary>
public class MigrationOuter
{
public MigrationInner Inner1;
public MigrationInner Inner2;
}
/// <summary>
/// Inner object for handle migration test.
/// </summary>
public class MigrationInner
{
public int Val;
}
/// <summary>
/// Outer object for handle inversion test.
/// </summary>
public class InversionOuter
{
public InversionInner Inner;
}
/// <summary>
/// Inner object for handle inversion test.
/// </summary>
public class InversionInner
{
public InversionOuter Outer;
}
/// <summary>
/// Object for composite array tests.
/// </summary>
public class CompositeArray
{
public object[] InArr;
public object[] OutArr;
}
/// <summary>
/// Object for composite collection/dictionary tests.
/// </summary>
public class CompositeContainer
{
public ICollection Col;
public IDictionary Dict;
}
/// <summary>
/// OUter object for composite structures test.
/// </summary>
public class CompositeOuter
{
public CompositeInner Inner;
public CompositeOuter()
{
// No-op.
}
public CompositeOuter(CompositeInner inner)
{
Inner = inner;
}
}
/// <summary>
/// Inner object for composite structures test.
/// </summary>
public class CompositeInner
{
public int Val;
public CompositeInner()
{
// No-op.
}
public CompositeInner(int val)
{
Val = val;
}
}
/// <summary>
/// Type to test "ToBinary()" logic.
/// </summary>
public class ToBinary
{
public int Val;
public ToBinary(int val)
{
Val = val;
}
}
/// <summary>
/// Type to test removal.
/// </summary>
public class Remove
{
public object Val;
public RemoveInner Val2;
}
/// <summary>
/// Inner type to test removal.
/// </summary>
public class RemoveInner
{
/** */
public int Val;
/// <summary>
///
/// </summary>
/// <param name="val"></param>
public RemoveInner(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
public class BuilderInBuilderOuter
{
/** */
public BuilderInBuilderInner Inner;
/** */
public BuilderInBuilderInner Inner2;
}
/// <summary>
///
/// </summary>
public class BuilderInBuilderInner
{
/** */
public BuilderInBuilderOuter Outer;
}
/// <summary>
///
/// </summary>
public class BuilderCollection
{
/** */
public readonly ArrayList Col;
/// <summary>
///
/// </summary>
/// <param name="col"></param>
public BuilderCollection(ArrayList col)
{
Col = col;
}
}
/// <summary>
///
/// </summary>
public class BuilderCollectionItem
{
/** */
public int Val;
/// <summary>
///
/// </summary>
/// <param name="val"></param>
public BuilderCollectionItem(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
public class DecimalHolder
{
/** */
public decimal Val;
/** */
public decimal?[] ValArr;
}
/// <summary>
/// Test id mapper.
/// </summary>
public class IdMapper : IBinaryIdMapper
{
/** */
public const string TestTypeName = "IdMapperTestType";
/** */
public const int TestTypeId = -65537;
/** <inheritdoc /> */
public int GetTypeId(string typeName)
{
return typeName == TestTypeName ? TestTypeId : 0;
}
/** <inheritdoc /> */
public int GetFieldId(int typeId, string fieldName)
{
return 0;
}
}
}
| |
// 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.Globalization;
using System.Security;
using System.Text;
using System.Xml;
using System.Diagnostics.CodeAnalysis;
using System.ServiceModel;
namespace System.Runtime.Diagnostics
{
internal abstract class DiagnosticTraceBase
{
//Diagnostics trace
protected const string DefaultTraceListenerName = "Default";
protected const string TraceRecordVersion = "http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord";
protected static string AppDomainFriendlyName = String.Empty;
private const ushort TracingEventLogCategory = 4;
private object _thisLock;
protected string TraceSourceName;
[Fx.Tag.SecurityNote(Critical = "This determines the event source name.")]
[SecurityCritical]
private string _eventSourceName;
public DiagnosticTraceBase(string traceSourceName)
{
_thisLock = new object();
TraceSourceName = traceSourceName;
LastFailure = DateTime.MinValue;
}
protected DateTime LastFailure { get; set; }
protected string EventSourceName
{
[Fx.Tag.SecurityNote(Critical = "Access critical eventSourceName field",
Safe = "Doesn't leak info\\resources")]
[SecuritySafeCritical]
get
{
return _eventSourceName;
}
[Fx.Tag.SecurityNote(Critical = "This determines the event source name.")]
[SecurityCritical]
set
{
_eventSourceName = value;
}
}
public bool TracingEnabled
{
get
{
return false;
}
}
protected static string ProcessName
{
[Fx.Tag.SecurityNote(Critical = "Satisfies a LinkDemand for 'PermissionSetAttribute' on type 'Process' when calling method GetCurrentProcess",
Safe = "Does not leak any resource and has been reviewed")]
[SecuritySafeCritical]
get
{
string retval = null;
return retval;
}
}
protected static int ProcessId
{
[Fx.Tag.SecurityNote(Critical = "Satisfies a LinkDemand for 'PermissionSetAttribute' on type 'Process' when calling method GetCurrentProcess",
Safe = "Does not leak any resource and has been reviewed")]
[SecuritySafeCritical]
get
{
int retval = -1;
return retval;
}
}
//only used for exceptions, perf is not important
public static string XmlEncode(string text)
{
if (string.IsNullOrEmpty(text))
{
return text;
}
int len = text.Length;
StringBuilder encodedText = new StringBuilder(len + 8); //perf optimization, expecting no more than 2 > characters
for (int i = 0; i < len; ++i)
{
char ch = text[i];
switch (ch)
{
case '<':
encodedText.Append("<");
break;
case '>':
encodedText.Append(">");
break;
case '&':
encodedText.Append("&");
break;
default:
encodedText.Append(ch);
break;
}
}
return encodedText.ToString();
}
[Fx.Tag.SecurityNote(Critical = "Sets global event handlers for the AppDomain",
Safe = "Doesn't leak resources\\Information")]
[SecuritySafeCritical]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands,
Justification = "SecuritySafeCritical method, Does not expose critical resources returned by methods with Link Demands")]
protected void AddDomainEventHandlersForCleanup()
{
}
private void ExitOrUnloadEventHandler(object sender, EventArgs e)
{
}
protected static string CreateSourceString(object source)
{
var traceSourceStringProvider = source as ITraceSourceStringProvider;
if (traceSourceStringProvider != null)
{
return traceSourceStringProvider.GetSourceString();
}
return CreateDefaultSourceString(source);
}
internal static string CreateDefaultSourceString(object source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
return String.Format(CultureInfo.CurrentCulture, "{0}/{1}", source.GetType().ToString(), source.GetHashCode());
}
protected static void AddExceptionToTraceString(XmlWriter xml, Exception exception)
{
xml.WriteElementString(DiagnosticStrings.ExceptionTypeTag, XmlEncode(exception.GetType().AssemblyQualifiedName));
xml.WriteElementString(DiagnosticStrings.MessageTag, XmlEncode(exception.Message));
xml.WriteElementString(DiagnosticStrings.StackTraceTag, XmlEncode(StackTraceString(exception)));
xml.WriteElementString(DiagnosticStrings.ExceptionStringTag, XmlEncode(exception.ToString()));
if (exception.Data != null && exception.Data.Count > 0)
{
xml.WriteStartElement(DiagnosticStrings.DataItemsTag);
foreach (object dataItem in exception.Data.Keys)
{
xml.WriteStartElement(DiagnosticStrings.DataTag);
xml.WriteElementString(DiagnosticStrings.KeyTag, XmlEncode(dataItem.ToString()));
xml.WriteElementString(DiagnosticStrings.ValueTag, XmlEncode(exception.Data[dataItem].ToString()));
xml.WriteEndElement();
}
xml.WriteEndElement();
}
if (exception.InnerException != null)
{
xml.WriteStartElement(DiagnosticStrings.InnerExceptionTag);
AddExceptionToTraceString(xml, exception.InnerException);
xml.WriteEndElement();
}
}
protected static string StackTraceString(Exception exception)
{
string retval = exception.StackTrace;
return retval;
}
// Duplicate code from System.ServiceModel.Diagnostics
[Fx.Tag.SecurityNote(Critical = "Calls unsafe methods, UnsafeCreateEventLogger and UnsafeLogEvent.",
Safe = "Event identities cannot be spoofed as they are constants determined inside the method, Demands the same permission that is asserted by the unsafe method.")]
[SecuritySafeCritical]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.SecureAsserts,
Justification = "Should not demand permission that is asserted by the EtwProvider ctor.")]
protected void LogTraceFailure(string traceString, Exception exception)
{
}
public static Guid ActivityId
{
[Fx.Tag.SecurityNote(Critical = "gets the CorrelationManager, which does a LinkDemand for UnmanagedCode",
Safe = "only uses the CM to get the ActivityId, which is not protected data, doesn't leak the CM")]
[SecuritySafeCritical]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands,
Justification = "SecuritySafeCriticial method")]
get
{
throw ExceptionHelper.PlatformNotSupported();
}
[Fx.Tag.SecurityNote(Critical = "gets the CorrelationManager, which does a LinkDemand for UnmanagedCode",
Safe = "only uses the CM to get the ActivityId, which is not protected data, doesn't leak the CM")]
[SecuritySafeCritical]
set
{
throw ExceptionHelper.PlatformNotSupported();
}
}
public abstract bool IsEnabled();
}
}
| |
#if UNITY_ANDROID
using UnityEngine;
class SensorDeviceAndroid : SensorDeviceUnity
{
// the static reference to access the gyro values
private AndroidJavaObject ao;
protected override void AwakeDevice()
{
if (SystemInfo.supportsGyroscope)
{
Input.gyro.enabled = true;
}
#if !UNITY_EDITOR
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject obj = jc.GetStatic<AndroidJavaObject>("currentActivity");
#else
AndroidJavaObject obj = null;
#endif
ao = new AndroidJavaObject("com.prefrontalcortex.gyrodroid.gyrodroidlibrary.SensorClass", obj);
// get all sensor informations (including whether they area available)
for (var i = 1; i <= Sensor.Count; i++)
{
// fill the sensor information array
Sensors[i] = new Information(
ao.Call<bool>("isSensorAvailable", i),
ao.Call<float>("getMaximumRange", i),
ao.Call<int>("getMinDelay", i),
ao.Call<string>("getName", i),
ao.Call<float>("getPower", i),
ao.Call<float>("getResolution", i),
ao.Call<string>("getVendor", i),
ao.Call<int>("getVersion", i),
Description[i]
);
}
// Debug.Log("test");
base.AwakeDevice();
}
protected Quaternion CompensateSurfaceRotation;
protected override void DeviceUpdate()
{
CompensateSurfaceRotation = _getSurfaceRotationCompensation();
}
protected override bool ActivateDeviceSensor(Type sensorID, Sensor.Delay sensorSpeed)
{
if (!base.ActivateDeviceSensor(sensorID, sensorSpeed))
{
if (ao.Call<bool>("ActivateSensor", (int) sensorID, (int) sensorSpeed))
{
Sensors[(int)sensorID].active = true;
return true;
}
}
return false;
}
protected override bool DeactivateDeviceSensor(Type sensorID)
{
if (!base.DeactivateDeviceSensor(sensorID))
{
if (ao.Call<bool>("DeactivateSensor", (int) sensorID))
{
Sensors[(int)sensorID].active = false;
return true;
}
}
return false;
}
protected override Vector3 GetDeviceSensor(Type sensorID)
{
AndroidJNI.AttachCurrentThread();
Get(sensorID).gotFirstValue = ao.Call<bool>("gotFirstValue", (int)sensorID);
var ret = Vector3.zero;
ret.x = ao.Call<float>("getValueX", (int)sensorID);
ret.y = ao.Call<float>("getValueY", (int)sensorID);
ret.z = ao.Call<float>("getValueZ", (int)sensorID);
if (sensorID == Type.Orientation && (surfaceRotation == Sensor.SurfaceRotation.Rotation90 || surfaceRotation == Sensor.SurfaceRotation.Rotation270))
{
_swapXY(ref ret);
}
if(sensorID == Type.LinearAcceleration) {
ret = Quaternion.Inverse(CompensateSurfaceRotation) * ret;
}
return ret;
}
// Device sensors on Android obey the following relation:
// accelerometer = gravity + linearAcceleration
protected override Vector3 _getDeviceOrientation()
{
// if (!((Sensors.Length > 0) && Get(Type.MagneticField).active && Get(Type.Accelerometer).active))
// {
// Debug.Log("To use getOrientation, MagneticField and Accelerometer have to be active, because getOrientation internally fuses the two.\n " +
// "Magnetic Field: " + Get(Type.MagneticField).active + ", Accelerometer: " + Get(Type.Accelerometer).active);
// }
var k = Vector3.zero;
AndroidJNI.AttachCurrentThread();
k.x = ao.Call<float>("getOrientationX") * Mathf.Rad2Deg;
k.y = ao.Call<float>("getOrientationY") * Mathf.Rad2Deg;
k.z = ao.Call<float>("getOrientationZ") * Mathf.Rad2Deg;
if (surfaceRotation == Sensor.SurfaceRotation.Rotation90 || surfaceRotation == Sensor.SurfaceRotation.Rotation270)
{
// switch y and z
_swapYZ(ref k);
}
// compensate surface rotation
CompensateDeviceOrientation(ref k);
return k;
}
protected override float GetDeviceAltitude(float pressure, float pressureAtSeaLevel = PressureValue.StandardAthmosphere)
{
const float coef = 1.0f / 5.255f;
return 44330.0f * (1.0f - Mathf.Pow(pressure / pressureAtSeaLevel, coef)); // HACK switch them?
}
protected override Sensor.SurfaceRotation GetSurfaceRotation()
{
return (Sensor.SurfaceRotation)ao.Call<int>("getWindowRotation");
}
protected override Quaternion QuaternionFromDeviceRotationVector(Vector3 v)
{
var r = new Quaternion(-v.x, -v.y, v.z, Mathf.Sqrt(1 - v.sqrMagnitude));
// switch axis
r = Quaternion.Euler(90, 0, 0) * r * CompensateSurfaceRotation;
return r;
}
protected override void CompensateDeviceOrientation(ref Vector3 k)
{
// add or subtract x
switch (surfaceRotation)
{
case Sensor.SurfaceRotation.Rotation90:
k.x += 90;
break;
case Sensor.SurfaceRotation.Rotation270:
k.x -= 90;
break;
case Sensor.SurfaceRotation.Rotation180:
k.x += 180;
break;
}
}
protected override ScreenOrientation ScreenOrientationDevice {
get {
if(
(surfaceRotation == Sensor.SurfaceRotation.Rotation0 && Screen.orientation == ScreenOrientation.LandscapeLeft) ||
(surfaceRotation == Sensor.SurfaceRotation.Rotation270 && Screen.orientation == ScreenOrientation.Portrait) ||
(surfaceRotation == Sensor.SurfaceRotation.Rotation180 && Screen.orientation == ScreenOrientation.LandscapeRight) ||
(surfaceRotation == Sensor.SurfaceRotation.Rotation90 && Screen.orientation == ScreenOrientation.PortraitUpsideDown)
)
return ScreenOrientation.LandscapeLeft;
else
return ScreenOrientation.Portrait;
}
}
private static void _swapXY(ref Vector3 k)
{
var temp = k.y;
k.y = -k.z;
k.z = temp;
}
private static void _swapYZ(ref Vector3 k)
{
var temp = k.y;
k.y = k.z;
k.z = temp;
}
private Quaternion _getSurfaceRotationCompensation()
{
switch (surfaceRotation)
{
case Sensor.SurfaceRotation.Rotation90:
return Quaternion.Euler(0, 0, -90);
case Sensor.SurfaceRotation.Rotation270:
return Quaternion.Euler(0, 0, 90);
case Sensor.SurfaceRotation.Rotation180:
return Quaternion.Euler(0, 0, 180);
default:
return Quaternion.Euler(0, 0, 0);
}
}
}
#endif
| |
using System;
using dex.net;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using ICSharpCode.SharpZipLib.Zip;
namespace dedex
{
class MainClass
{
public static void Main (string[] args)
{
ClassDisplayOptions displayOptions = ClassDisplayOptions.ClassName;
IDexWriter dexWriter = null;
var classPattern = "*";
var factory = new WritersFactory ();
DirectoryInfo dir = null;
var dexFiles = new List<FileInfo> ();
var tempFiles = new List<FileInfo> ();
var apkFiles = new List<string> ();
string currentOption = null;
foreach (var arg in args) {
// Parse the option arguments
if (currentOption != null) {
switch (currentOption) {
case "-c":
classPattern = arg;
break;
case "-d":
var displayOptionStrings = arg.Split(new char[]{','});
foreach (var displayOption in displayOptionStrings) {
switch (displayOption.ToLower ()) {
case "classes":
displayOptions |= ClassDisplayOptions.ClassAnnotations |
ClassDisplayOptions.ClassName |
ClassDisplayOptions.ClassDetails;
break;
case "methods":
displayOptions |= ClassDisplayOptions.MethodAnnotations |
ClassDisplayOptions.Methods;
break;
case "fields":
displayOptions |= ClassDisplayOptions.Fields;
break;
case "opcodes":
displayOptions |= ClassDisplayOptions.Methods | ClassDisplayOptions.OpCodes;
break;
case "all":
displayOptions |= ClassDisplayOptions.ClassAnnotations | ClassDisplayOptions.ClassName |
ClassDisplayOptions.ClassDetails | ClassDisplayOptions.Fields | ClassDisplayOptions.MethodAnnotations |
ClassDisplayOptions.Methods | ClassDisplayOptions.OpCodes;
break;
default:
Stop ("Unsupported display option " + displayOption);
break;
}
}
break;
case "-o":
var dirName = arg.Trim();
if (!Directory.Exists(dirName)) {
Stop ("Directory doesn't exist " + dirName);
}
dir = new DirectoryInfo(arg.Trim());
break;
case "-w":
var writerName = arg.Trim();
try {
var writer = GetWritersMap()[writerName];
dexWriter = factory.GetWriter(writer);
} catch {
Stop (string.Format ("Writer {0} not found", writerName));
}
break;
default:
Stop ("Unsupported argument " + currentOption);
break;
}
currentOption = null;
}
// An option flag
if (arg.StartsWith ("-")) {
currentOption = arg;
continue;
}
// Build the list of dex files to disassemble
if (Path.GetExtension(arg).ToLower().Equals(".dex")) {
var dexFile = new FileInfo (arg);
if (dexFile.Exists) {
dexFiles.Add (dexFile);
} else {
Console.WriteLine ("Couldn't file file {0}", arg);
}
} else if (Path.GetExtension(arg).ToLower().Equals(".apk")) {
// Unzip the classes.dex into a temporary location
var apkFile = new FileInfo (arg);
if (apkFile.Exists) {
var zip = new ZipFile (arg);
var entry = zip.GetEntry ("classes.dex");
if (entry != null) {
var zipStream = zip.GetInputStream (entry);
var tempFileName = Path.GetTempFileName ();
var buffer = new byte[4096];
using (var writer = File.Create(tempFileName)) {
int bytesRead;
while ((bytesRead = zipStream.Read(buffer, 0, 4096)) > 0) {
writer.Write (buffer, 0, bytesRead);
}
}
var tempFile = new FileInfo (tempFileName);
dexFiles.Add (tempFile);
tempFiles.Add (tempFile);
apkFiles.Add (arg);
} else {
Console.WriteLine ("No classes.dex in {0}", arg);
}
} else {
Console.WriteLine ("Couldn't file file {0}", arg);
}
}
}
if (dexFiles.Count == 0)
PrintHelp();
// Set default writer
if (dexWriter == null) {
dexWriter = factory.GetWriter(factory.GetWriters()[0]);
}
var output = Console.Out;
// Process all DEX files
try {
int tempCount = 0;
foreach (var dexFile in dexFiles) {
using (var dex = new Dex(dexFile.Open(FileMode.Open)) ) {
var classesToDisplay = new Regex("^" + classPattern.Replace("*", ".*") + "$");
dexWriter.dex = dex;
string filename = dexFile.Name;
if (Path.GetExtension(filename).EndsWith("tmp")) {
filename = apkFiles[tempCount++];
}
filename = Path.GetFileName(filename);
if (dir == null) {
// Write out the file name as header
Console.WriteLine();
Console.WriteLine(filename);
foreach (var c in filename)
Console.Write("=");
Console.WriteLine('\n');
}
// Write out each class
foreach (var dexClass in dex.GetClasses()) {
var fullClassName = dexClass.Name;
if (classesToDisplay.IsMatch(fullClassName)) {
if (dir != null) {
fullClassName = fullClassName.Replace('.', Path.DirectorySeparatorChar) + dexWriter.GetExtension();
var fullDirPath = Path.Combine(dir.ToString(), Path.GetDirectoryName(fullClassName));
Directory.CreateDirectory(fullDirPath);
output = new StreamWriter(Path.Combine(dir.ToString(), fullClassName));
}
using (output) {
dexWriter.WriteOutClass(dexClass, displayOptions, output);
}
}
}
}
}
} finally {
foreach (var tempFile in tempFiles) {
tempFile.Delete ();
}
}
}
private static Dictionary<string,string> GetWritersMap()
{
var writers = new Dictionary<string,string> ();
foreach (var writer in new WritersFactory ().GetWriters ()) {
writers.Add(writer.ToLower().Replace(" ", ""), writer);
}
return writers;
}
private static void PrintHelp ()
{
var languages = string.Join (", ", GetWritersMap().Keys);
Console.WriteLine("Usage:\n\tdedex [options] <file.dex|apk> [file2.dex ... fileN.dex]\n");
Console.WriteLine("\t-c <pattern>. Display only classes matching the pattern. * is a wildcard");
Console.WriteLine("\t-d <display[,display...]>. Options are All, Classes, Methods, Fields, OpCodes");
Console.WriteLine("\t-o <directory>. Write classes to individual files in the output directory");
Console.WriteLine("\t-w <language>. One of " + languages);
Environment.Exit(1);
}
private static void Stop (string message)
{
Console.Error.WriteLine (message);
Environment.Exit (1);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Serialization
{
using System.IO;
using System;
using System.Security;
using System.Collections;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.ComponentModel;
using System.Globalization;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Threading;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
using System.Xml.Extensions;
using Hashtable = System.Collections.Generic.Dictionary<object, object>;
using DictionaryEntry = System.Collections.Generic.KeyValuePair<object, object>;
using XmlSchema = System.ServiceModel.Dispatcher.XmlSchemaConstants;
using XmlDeserializationEvents = System.Object;
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader"]/*' />
///<internalonly/>
public abstract class XmlSerializationReader : XmlSerializationGeneratedCode
{
private XmlReader _r;
private XmlDocument _d;
private XmlDeserializationEvents _events;
private bool _soap12;
private bool _isReturnValue;
private bool _decodeName = true;
private string _schemaNsID;
private string _schemaNs1999ID;
private string _schemaNs2000ID;
private string _schemaNonXsdTypesNsID;
private string _instanceNsID;
private string _instanceNs2000ID;
private string _instanceNs1999ID;
private string _soapNsID;
private string _soap12NsID;
private string _schemaID;
private string _wsdlNsID;
private string _wsdlArrayTypeID;
private string _nullID;
private string _nilID;
private string _typeID;
private string _arrayTypeID;
private string _itemTypeID;
private string _arraySizeID;
private string _arrayID;
private string _urTypeID;
private string _stringID;
private string _intID;
private string _booleanID;
private string _shortID;
private string _longID;
private string _floatID;
private string _doubleID;
private string _decimalID;
private string _dateTimeID;
private string _qnameID;
private string _dateID;
private string _timeID;
private string _hexBinaryID;
private string _base64BinaryID;
private string _base64ID;
private string _unsignedByteID;
private string _byteID;
private string _unsignedShortID;
private string _unsignedIntID;
private string _unsignedLongID;
private string _oldDecimalID;
private string _oldTimeInstantID;
private string _anyURIID;
private string _durationID;
private string _ENTITYID;
private string _ENTITIESID;
private string _gDayID;
private string _gMonthID;
private string _gMonthDayID;
private string _gYearID;
private string _gYearMonthID;
private string _IDID;
private string _IDREFID;
private string _IDREFSID;
private string _integerID;
private string _languageID;
private string _nameID;
private string _NCNameID;
private string _NMTOKENID;
private string _NMTOKENSID;
private string _negativeIntegerID;
private string _nonPositiveIntegerID;
private string _nonNegativeIntegerID;
private string _normalizedStringID;
private string _NOTATIONID;
private string _positiveIntegerID;
private string _tokenID;
private string _charID;
private string _guidID;
private string _timeSpanID;
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.InitIDs"]/*' />
protected abstract void InitIDs();
// this method must be called before any generated deserialization methods are called
internal void Init(XmlReader r, string encodingStyle)
{
_r = r;
_soap12 = (encodingStyle == Soap12.Encoding);
_schemaNsID = r.NameTable.Add(XmlSchema.Namespace);
_schemaNs2000ID = r.NameTable.Add("http://www.w3.org/2000/10/XMLSchema");
_schemaNs1999ID = r.NameTable.Add("http://www.w3.org/1999/XMLSchema");
_schemaNonXsdTypesNsID = r.NameTable.Add(UrtTypes.Namespace);
_instanceNsID = r.NameTable.Add(XmlSchema.InstanceNamespace);
_instanceNs2000ID = r.NameTable.Add("http://www.w3.org/2000/10/XMLSchema-instance");
_instanceNs1999ID = r.NameTable.Add("http://www.w3.org/1999/XMLSchema-instance");
_soapNsID = r.NameTable.Add(Soap.Encoding);
_soap12NsID = r.NameTable.Add(Soap12.Encoding);
_schemaID = r.NameTable.Add("schema");
_wsdlNsID = r.NameTable.Add(Wsdl.Namespace);
_wsdlArrayTypeID = r.NameTable.Add(Wsdl.ArrayType);
_nullID = r.NameTable.Add("null");
_nilID = r.NameTable.Add("nil");
_typeID = r.NameTable.Add("type");
_arrayTypeID = r.NameTable.Add("arrayType");
_itemTypeID = r.NameTable.Add("itemType");
_arraySizeID = r.NameTable.Add("arraySize");
_arrayID = r.NameTable.Add("Array");
_urTypeID = r.NameTable.Add(Soap.UrType);
InitIDs();
}
// this method must be called before any generated deserialization methods are called
internal void Init(XmlReader r, XmlDeserializationEvents events, string encodingStyle, TempAssembly tempAssembly)
{
_events = events;
Init(tempAssembly);
Init(r, encodingStyle);
}
/// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.DecodeName"]/*' />
protected bool DecodeName
{
get
{
return _decodeName;
}
set
{
_decodeName = value;
}
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.Reader"]/*' />
protected XmlReader Reader
{
get
{
return _r;
}
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.Document"]/*' />
protected XmlDocument Document
{
get
{
if (_d == null)
{
_d = new XmlDocument(_r.NameTable);
}
return _d;
}
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReaderCount"]/*' />
protected int ReaderCount
{
get
{
return 0;
}
}
private void InitPrimitiveIDs()
{
if (_tokenID != null) return;
object ns = _r.NameTable.Add(XmlSchema.Namespace);
object ns2 = _r.NameTable.Add(UrtTypes.Namespace);
_stringID = _r.NameTable.Add("string");
_intID = _r.NameTable.Add("int");
_booleanID = _r.NameTable.Add("boolean");
_shortID = _r.NameTable.Add("short");
_longID = _r.NameTable.Add("long");
_floatID = _r.NameTable.Add("float");
_doubleID = _r.NameTable.Add("double");
_decimalID = _r.NameTable.Add("decimal");
_dateTimeID = _r.NameTable.Add("dateTime");
_qnameID = _r.NameTable.Add("QName");
_dateID = _r.NameTable.Add("date");
_timeID = _r.NameTable.Add("time");
_hexBinaryID = _r.NameTable.Add("hexBinary");
_base64BinaryID = _r.NameTable.Add("base64Binary");
_unsignedByteID = _r.NameTable.Add("unsignedByte");
_byteID = _r.NameTable.Add("byte");
_unsignedShortID = _r.NameTable.Add("unsignedShort");
_unsignedIntID = _r.NameTable.Add("unsignedInt");
_unsignedLongID = _r.NameTable.Add("unsignedLong");
_oldDecimalID = _r.NameTable.Add("decimal");
_oldTimeInstantID = _r.NameTable.Add("timeInstant");
_charID = _r.NameTable.Add("char");
_guidID = _r.NameTable.Add("guid");
_timeSpanID = _r.NameTable.Add("TimeSpan");
_base64ID = _r.NameTable.Add("base64");
_anyURIID = _r.NameTable.Add("anyURI");
_durationID = _r.NameTable.Add("duration");
_ENTITYID = _r.NameTable.Add("ENTITY");
_ENTITIESID = _r.NameTable.Add("ENTITIES");
_gDayID = _r.NameTable.Add("gDay");
_gMonthID = _r.NameTable.Add("gMonth");
_gMonthDayID = _r.NameTable.Add("gMonthDay");
_gYearID = _r.NameTable.Add("gYear");
_gYearMonthID = _r.NameTable.Add("gYearMonth");
_IDID = _r.NameTable.Add("ID");
_IDREFID = _r.NameTable.Add("IDREF");
_IDREFSID = _r.NameTable.Add("IDREFS");
_integerID = _r.NameTable.Add("integer");
_languageID = _r.NameTable.Add("language");
_nameID = _r.NameTable.Add("Name");
_NCNameID = _r.NameTable.Add("NCName");
_NMTOKENID = _r.NameTable.Add("NMTOKEN");
_NMTOKENSID = _r.NameTable.Add("NMTOKENS");
_negativeIntegerID = _r.NameTable.Add("negativeInteger");
_nonNegativeIntegerID = _r.NameTable.Add("nonNegativeInteger");
_nonPositiveIntegerID = _r.NameTable.Add("nonPositiveInteger");
_normalizedStringID = _r.NameTable.Add("normalizedString");
_NOTATIONID = _r.NameTable.Add("NOTATION");
_positiveIntegerID = _r.NameTable.Add("positiveInteger");
_tokenID = _r.NameTable.Add("token");
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.GetXsiType"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected XmlQualifiedName GetXsiType()
{
string type = _r.GetAttribute(_typeID, _instanceNsID);
if (type == null)
{
type = _r.GetAttribute(_typeID, _instanceNs2000ID);
if (type == null)
{
type = _r.GetAttribute(_typeID, _instanceNs1999ID);
if (type == null)
return null;
}
}
return ToXmlQualifiedName(type, false);
}
private bool IsPrimitiveNamespace(string ns)
{
return (object)ns == (object)_schemaNsID ||
(object)ns == (object)_schemaNonXsdTypesNsID ||
(object)ns == (object)_soapNsID ||
(object)ns == (object)_soap12NsID ||
(object)ns == (object)_schemaNs2000ID ||
(object)ns == (object)_schemaNs1999ID;
}
private string ReadStringValue()
{
if (_r.IsEmptyElement)
{
_r.Skip();
return string.Empty;
}
_r.ReadStartElement();
string retVal = _r.ReadString();
ReadEndElement();
return retVal;
}
private XmlQualifiedName ReadXmlQualifiedName(bool collapseWhitespace = false)
{
string s;
bool isEmpty = false;
if (_r.IsEmptyElement)
{
s = string.Empty;
isEmpty = true;
}
else
{
_r.ReadStartElement();
s = _r.ReadString();
}
if (collapseWhitespace)
{
s = CollapseWhitespace(s);
}
XmlQualifiedName retVal = ToXmlQualifiedName(s);
if (isEmpty)
_r.Skip();
else
ReadEndElement();
return retVal;
}
private byte[] ReadByteArray(bool isBase64)
{
ArrayList list = new ArrayList();
const int MAX_ALLOC_SIZE = 64 * 1024;
int currentSize = 1024;
byte[] buffer;
int bytes = -1;
int offset = 0;
int total = 0;
buffer = new byte[currentSize];
list.Add(buffer);
while (bytes != 0)
{
if (offset == buffer.Length)
{
currentSize = Math.Min(currentSize * 2, MAX_ALLOC_SIZE);
buffer = new byte[currentSize];
offset = 0;
list.Add(buffer);
}
if (isBase64)
{
bytes = _r.ReadElementContentAsBase64(buffer, offset, buffer.Length - offset);
}
else
{
bytes = _r.ReadElementContentAsBinHex(buffer, offset, buffer.Length - offset);
}
offset += bytes;
total += bytes;
}
byte[] result = new byte[total];
offset = 0;
foreach (byte[] block in list)
{
currentSize = Math.Min(block.Length, total);
if (currentSize > 0)
{
Buffer.BlockCopy(block, 0, result, offset, currentSize);
offset += currentSize;
total -= currentSize;
}
}
list.Clear();
return result;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReadTypedPrimitive"]/*' />
protected object ReadTypedPrimitive(XmlQualifiedName type)
{
return ReadTypedPrimitive(type, false);
}
private object ReadTypedPrimitive(XmlQualifiedName type, bool elementCanBeType)
{
InitPrimitiveIDs();
object value = null;
if (!IsPrimitiveNamespace(type.Namespace) || (object)type.Name == (object)_urTypeID)
return ReadXmlNodes(elementCanBeType);
if ((object)type.Namespace == (object)_schemaNsID || (object)type.Namespace == (object)_soapNsID || (object)type.Namespace == (object)_soap12NsID)
{
if ((object)type.Name == (object)_stringID ||
(object)type.Name == (object)_normalizedStringID)
value = ReadStringValue();
else if ((object)type.Name == (object)_anyURIID ||
(object)type.Name == (object)_durationID ||
(object)type.Name == (object)_ENTITYID ||
(object)type.Name == (object)_ENTITIESID ||
(object)type.Name == (object)_gDayID ||
(object)type.Name == (object)_gMonthID ||
(object)type.Name == (object)_gMonthDayID ||
(object)type.Name == (object)_gYearID ||
(object)type.Name == (object)_gYearMonthID ||
(object)type.Name == (object)_IDID ||
(object)type.Name == (object)_IDREFID ||
(object)type.Name == (object)_IDREFSID ||
(object)type.Name == (object)_integerID ||
(object)type.Name == (object)_languageID ||
(object)type.Name == (object)_nameID ||
(object)type.Name == (object)_NCNameID ||
(object)type.Name == (object)_NMTOKENID ||
(object)type.Name == (object)_NMTOKENSID ||
(object)type.Name == (object)_negativeIntegerID ||
(object)type.Name == (object)_nonPositiveIntegerID ||
(object)type.Name == (object)_nonNegativeIntegerID ||
(object)type.Name == (object)_NOTATIONID ||
(object)type.Name == (object)_positiveIntegerID ||
(object)type.Name == (object)_tokenID)
value = CollapseWhitespace(ReadStringValue());
else if ((object)type.Name == (object)_intID)
value = XmlConvert.ToInt32(ReadStringValue());
else if ((object)type.Name == (object)_booleanID)
value = XmlConvert.ToBoolean(ReadStringValue());
else if ((object)type.Name == (object)_shortID)
value = XmlConvert.ToInt16(ReadStringValue());
else if ((object)type.Name == (object)_longID)
value = XmlConvert.ToInt64(ReadStringValue());
else if ((object)type.Name == (object)_floatID)
value = XmlConvert.ToSingle(ReadStringValue());
else if ((object)type.Name == (object)_doubleID)
value = XmlConvert.ToDouble(ReadStringValue());
else if ((object)type.Name == (object)_decimalID)
value = XmlConvert.ToDecimal(ReadStringValue());
else if ((object)type.Name == (object)_dateTimeID)
value = ToDateTime(ReadStringValue());
else if ((object)type.Name == (object)_qnameID)
value = ReadXmlQualifiedName();
else if ((object)type.Name == (object)_dateID)
value = ToDate(ReadStringValue());
else if ((object)type.Name == (object)_timeID)
value = ToTime(ReadStringValue());
else if ((object)type.Name == (object)_unsignedByteID)
value = XmlConvert.ToByte(ReadStringValue());
else if ((object)type.Name == (object)_byteID)
value = XmlConvert.ToSByte(ReadStringValue());
else if ((object)type.Name == (object)_unsignedShortID)
value = XmlConvert.ToUInt16(ReadStringValue());
else if ((object)type.Name == (object)_unsignedIntID)
value = XmlConvert.ToUInt32(ReadStringValue());
else if ((object)type.Name == (object)_unsignedLongID)
value = XmlConvert.ToUInt64(ReadStringValue());
else if ((object)type.Name == (object)_hexBinaryID)
value = ToByteArrayHex(false);
else if ((object)type.Name == (object)_base64BinaryID)
value = ToByteArrayBase64(false);
else if ((object)type.Name == (object)_base64ID && ((object)type.Namespace == (object)_soapNsID || (object)type.Namespace == (object)_soap12NsID))
value = ToByteArrayBase64(false);
else
value = ReadXmlNodes(elementCanBeType);
}
else if ((object)type.Namespace == (object)_schemaNs2000ID || (object)type.Namespace == (object)_schemaNs1999ID)
{
if ((object)type.Name == (object)_stringID ||
(object)type.Name == (object)_normalizedStringID)
value = ReadStringValue();
else if ((object)type.Name == (object)_anyURIID ||
(object)type.Name == (object)_anyURIID ||
(object)type.Name == (object)_durationID ||
(object)type.Name == (object)_ENTITYID ||
(object)type.Name == (object)_ENTITIESID ||
(object)type.Name == (object)_gDayID ||
(object)type.Name == (object)_gMonthID ||
(object)type.Name == (object)_gMonthDayID ||
(object)type.Name == (object)_gYearID ||
(object)type.Name == (object)_gYearMonthID ||
(object)type.Name == (object)_IDID ||
(object)type.Name == (object)_IDREFID ||
(object)type.Name == (object)_IDREFSID ||
(object)type.Name == (object)_integerID ||
(object)type.Name == (object)_languageID ||
(object)type.Name == (object)_nameID ||
(object)type.Name == (object)_NCNameID ||
(object)type.Name == (object)_NMTOKENID ||
(object)type.Name == (object)_NMTOKENSID ||
(object)type.Name == (object)_negativeIntegerID ||
(object)type.Name == (object)_nonPositiveIntegerID ||
(object)type.Name == (object)_nonNegativeIntegerID ||
(object)type.Name == (object)_NOTATIONID ||
(object)type.Name == (object)_positiveIntegerID ||
(object)type.Name == (object)_tokenID)
value = CollapseWhitespace(ReadStringValue());
else if ((object)type.Name == (object)_intID)
value = XmlConvert.ToInt32(ReadStringValue());
else if ((object)type.Name == (object)_booleanID)
value = XmlConvert.ToBoolean(ReadStringValue());
else if ((object)type.Name == (object)_shortID)
value = XmlConvert.ToInt16(ReadStringValue());
else if ((object)type.Name == (object)_longID)
value = XmlConvert.ToInt64(ReadStringValue());
else if ((object)type.Name == (object)_floatID)
value = XmlConvert.ToSingle(ReadStringValue());
else if ((object)type.Name == (object)_doubleID)
value = XmlConvert.ToDouble(ReadStringValue());
else if ((object)type.Name == (object)_oldDecimalID)
value = XmlConvert.ToDecimal(ReadStringValue());
else if ((object)type.Name == (object)_oldTimeInstantID)
value = ToDateTime(ReadStringValue());
else if ((object)type.Name == (object)_qnameID)
value = ReadXmlQualifiedName();
else if ((object)type.Name == (object)_dateID)
value = ToDate(ReadStringValue());
else if ((object)type.Name == (object)_timeID)
value = ToTime(ReadStringValue());
else if ((object)type.Name == (object)_unsignedByteID)
value = XmlConvert.ToByte(ReadStringValue());
else if ((object)type.Name == (object)_byteID)
value = XmlConvert.ToSByte(ReadStringValue());
else if ((object)type.Name == (object)_unsignedShortID)
value = XmlConvert.ToUInt16(ReadStringValue());
else if ((object)type.Name == (object)_unsignedIntID)
value = XmlConvert.ToUInt32(ReadStringValue());
else if ((object)type.Name == (object)_unsignedLongID)
value = XmlConvert.ToUInt64(ReadStringValue());
else
value = ReadXmlNodes(elementCanBeType);
}
else if ((object)type.Namespace == (object)_schemaNonXsdTypesNsID)
{
if ((object)type.Name == (object)_charID)
value = ToChar(ReadStringValue());
else if ((object)type.Name == (object)_guidID)
value = new Guid(CollapseWhitespace(ReadStringValue()));
else if ((object)type.Name == (object)_timeSpanID)
value = XmlConvert.ToTimeSpan(ReadStringValue());
else
value = ReadXmlNodes(elementCanBeType);
}
else
value = ReadXmlNodes(elementCanBeType);
return value;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReadTypedNull"]/*' />
protected object ReadTypedNull(XmlQualifiedName type)
{
InitPrimitiveIDs();
object value = null;
if (!IsPrimitiveNamespace(type.Namespace) || (object)type.Name == (object)_urTypeID)
{
return null;
}
if ((object)type.Namespace == (object)_schemaNsID || (object)type.Namespace == (object)_soapNsID || (object)type.Namespace == (object)_soap12NsID)
{
if ((object)type.Name == (object)_stringID ||
(object)type.Name == (object)_anyURIID ||
(object)type.Name == (object)_durationID ||
(object)type.Name == (object)_ENTITYID ||
(object)type.Name == (object)_ENTITIESID ||
(object)type.Name == (object)_gDayID ||
(object)type.Name == (object)_gMonthID ||
(object)type.Name == (object)_gMonthDayID ||
(object)type.Name == (object)_gYearID ||
(object)type.Name == (object)_gYearMonthID ||
(object)type.Name == (object)_IDID ||
(object)type.Name == (object)_IDREFID ||
(object)type.Name == (object)_IDREFSID ||
(object)type.Name == (object)_integerID ||
(object)type.Name == (object)_languageID ||
(object)type.Name == (object)_nameID ||
(object)type.Name == (object)_NCNameID ||
(object)type.Name == (object)_NMTOKENID ||
(object)type.Name == (object)_NMTOKENSID ||
(object)type.Name == (object)_negativeIntegerID ||
(object)type.Name == (object)_nonPositiveIntegerID ||
(object)type.Name == (object)_nonNegativeIntegerID ||
(object)type.Name == (object)_normalizedStringID ||
(object)type.Name == (object)_NOTATIONID ||
(object)type.Name == (object)_positiveIntegerID ||
(object)type.Name == (object)_tokenID)
value = null;
else if ((object)type.Name == (object)_intID)
{
value = default(Nullable<int>);
}
else if ((object)type.Name == (object)_booleanID)
value = default(Nullable<bool>);
else if ((object)type.Name == (object)_shortID)
value = default(Nullable<Int16>);
else if ((object)type.Name == (object)_longID)
value = default(Nullable<long>);
else if ((object)type.Name == (object)_floatID)
value = default(Nullable<float>);
else if ((object)type.Name == (object)_doubleID)
value = default(Nullable<double>);
else if ((object)type.Name == (object)_decimalID)
value = default(Nullable<decimal>);
else if ((object)type.Name == (object)_dateTimeID)
value = default(Nullable<DateTime>);
else if ((object)type.Name == (object)_qnameID)
value = null;
else if ((object)type.Name == (object)_dateID)
value = default(Nullable<DateTime>);
else if ((object)type.Name == (object)_timeID)
value = default(Nullable<DateTime>);
else if ((object)type.Name == (object)_unsignedByteID)
value = default(Nullable<byte>);
else if ((object)type.Name == (object)_byteID)
value = default(Nullable<SByte>);
else if ((object)type.Name == (object)_unsignedShortID)
value = default(Nullable<UInt16>);
else if ((object)type.Name == (object)_unsignedIntID)
value = default(Nullable<UInt32>);
else if ((object)type.Name == (object)_unsignedLongID)
value = default(Nullable<UInt64>);
else if ((object)type.Name == (object)_hexBinaryID)
value = null;
else if ((object)type.Name == (object)_base64BinaryID)
value = null;
else if ((object)type.Name == (object)_base64ID && ((object)type.Namespace == (object)_soapNsID || (object)type.Namespace == (object)_soap12NsID))
value = null;
else
value = null;
}
else if ((object)type.Namespace == (object)_schemaNonXsdTypesNsID)
{
if ((object)type.Name == (object)_charID)
value = default(Nullable<char>);
else if ((object)type.Name == (object)_guidID)
value = default(Nullable<Guid>);
else if ((object) type.Name == (object) _timeSpanID)
value = default(Nullable<TimeSpan>);
else
value = null;
}
else
value = null;
return value;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.IsXmlnsAttribute"]/*' />
protected bool IsXmlnsAttribute(string name)
{
if (!name.StartsWith("xmlns", StringComparison.Ordinal)) return false;
if (name.Length == 5) return true;
return name[5] == ':';
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.IsArrayTypeAttribute"]/*' />
protected void ParseWsdlArrayType(XmlAttribute attr)
{
if ((object)attr.LocalName == (object)_wsdlArrayTypeID && (object)attr.NamespaceURI == (object)_wsdlNsID)
{
int colon = attr.Value.LastIndexOf(':');
if (colon < 0)
{
attr.Value = _r.LookupNamespace("") + ":" + attr.Value;
}
else
{
attr.Value = _r.LookupNamespace(attr.Value.Substring(0, colon)) + ":" +
attr.Value.Substring(colon + 1);
}
}
return;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.IsReturnValue"]/*' />
protected bool IsReturnValue
{
// value only valid for soap 1.1
get { return _isReturnValue && !_soap12; }
set { _isReturnValue = value; }
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReadNull"]/*' />
protected bool ReadNull()
{
if (!GetNullAttr()) return false;
if (_r.IsEmptyElement)
{
_r.Skip();
return true;
}
_r.ReadStartElement();
int whileIterations = 0;
int readerCount = ReaderCount;
while (_r.NodeType != XmlNodeType.EndElement)
{
UnknownNode(null);
CheckReaderCount(ref whileIterations, ref readerCount);
}
ReadEndElement();
return true;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.GetNullAttr"]/*' />
protected bool GetNullAttr()
{
string isNull = _r.GetAttribute(_nilID, _instanceNsID);
if (isNull == null)
isNull = _r.GetAttribute(_nullID, _instanceNsID);
if (isNull == null)
{
isNull = _r.GetAttribute(_nullID, _instanceNs2000ID);
if (isNull == null)
isNull = _r.GetAttribute(_nullID, _instanceNs1999ID);
}
if (isNull == null || !XmlConvert.ToBoolean(isNull)) return false;
return true;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReadNullableString"]/*' />
protected string ReadNullableString()
{
if (ReadNull()) return null;
return _r.ReadElementString();
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReadNullableQualifiedName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected XmlQualifiedName ReadNullableQualifiedName()
{
if (ReadNull()) return null;
return ReadElementQualifiedName();
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReadElementQualifiedName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected XmlQualifiedName ReadElementQualifiedName()
{
if (_r.IsEmptyElement)
{
XmlQualifiedName empty = new XmlQualifiedName(string.Empty, _r.LookupNamespace(""));
_r.Skip();
return empty;
}
XmlQualifiedName qname = ReadXmlQualifiedName(collapseWhitespace: true);
return qname;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReadXmlDocument"]/*' />
protected XmlDocument ReadXmlDocument(bool wrapped)
{
XmlNode n = ReadXmlNode(wrapped);
if (n == null)
return null;
XmlDocument doc = new XmlDocument();
doc.AppendChild(doc.ImportNode(n, true));
return doc;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CollapseWhitespace"]/*' />
protected string CollapseWhitespace(string value)
{
if (value == null)
return null;
return value.Trim();
}
protected XmlNode ReadXmlNode(bool wrapped)
{
XmlNode node = null;
if (wrapped)
{
if (ReadNull()) return null;
_r.ReadStartElement();
_r.MoveToContent();
if (_r.NodeType != XmlNodeType.EndElement)
node = Document.ReadNode(_r);
int whileIterations = 0;
int readerCount = ReaderCount;
while (_r.NodeType != XmlNodeType.EndElement)
{
UnknownNode(null);
CheckReaderCount(ref whileIterations, ref readerCount);
}
_r.ReadEndElement();
}
else
{
node = Document.ReadNode(_r);
}
return node;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToByteArrayBase64"]/*' />
protected static byte[] ToByteArrayBase64(string value)
{
return XmlCustomFormatter.ToByteArrayBase64(value);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToByteArrayBase641"]/*' />
protected byte[] ToByteArrayBase64(bool isNull)
{
if (isNull)
{
return null;
}
return ReadByteArray(true); //means use Base64
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToByteArrayHex"]/*' />
protected static byte[] ToByteArrayHex(string value)
{
return XmlCustomFormatter.ToByteArrayHex(value);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToByteArrayHex1"]/*' />
protected byte[] ToByteArrayHex(bool isNull)
{
if (isNull)
{
return null;
}
return ReadByteArray(false); //means use BinHex
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToDateTime"]/*' />
protected static DateTime ToDateTime(string value)
{
return XmlCustomFormatter.ToDateTime(value);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToDate"]/*' />
protected static DateTime ToDate(string value)
{
return XmlCustomFormatter.ToDate(value);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToTime"]/*' />
protected static DateTime ToTime(string value)
{
return XmlCustomFormatter.ToTime(value);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToChar"]/*' />
protected static char ToChar(string value)
{
return XmlCustomFormatter.ToChar(value);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToEnum"]/*' />
protected static long ToEnum(string value, IDictionary h, string typeName)
{
return XmlCustomFormatter.ToEnum(value, h, typeName, true);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToXmlName"]/*' />
protected static string ToXmlName(string value)
{
return XmlCustomFormatter.ToXmlName(value);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToXmlNCName"]/*' />
protected static string ToXmlNCName(string value)
{
return XmlCustomFormatter.ToXmlNCName(value);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToXmlNmToken"]/*' />
protected static string ToXmlNmToken(string value)
{
return XmlCustomFormatter.ToXmlNmToken(value);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToXmlNmTokens"]/*' />
protected static string ToXmlNmTokens(string value)
{
return XmlCustomFormatter.ToXmlNmTokens(value);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ToXmlQualifiedName"]/*' />
protected XmlQualifiedName ToXmlQualifiedName(string value)
{
return ToXmlQualifiedName(value, DecodeName);
}
internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName)
{
int colon = value == null ? -1 : value.LastIndexOf(':');
string prefix = colon < 0 ? null : value.Substring(0, colon);
string localName = value.Substring(colon + 1);
if (decodeName)
{
prefix = XmlConvert.DecodeName(prefix);
localName = XmlConvert.DecodeName(localName);
}
if (prefix == null || prefix.Length == 0)
{
return new XmlQualifiedName(_r.NameTable.Add(value), _r.LookupNamespace(String.Empty));
}
else
{
string ns = _r.LookupNamespace(prefix);
if (ns == null)
{
// Namespace prefix '{0}' is not defined.
throw new InvalidOperationException(SR.Format(SR.XmlUndefinedAlias, prefix));
}
return new XmlQualifiedName(_r.NameTable.Add(localName), ns);
}
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.UnknownNode"]/*' />
protected void UnknownNode(object o)
{
UnknownNode(o, null);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.UnknownNode1"]/*' />
protected void UnknownNode(object o, string qnames)
{
if (_r.NodeType == XmlNodeType.None || _r.NodeType == XmlNodeType.Whitespace)
{
_r.Read();
return;
}
if (_r.NodeType == XmlNodeType.EndElement)
return;
if (_r.NodeType == XmlNodeType.Attribute)
{
return;
}
if (_r.NodeType == XmlNodeType.Element)
{
_r.Skip();
return;
}
UnknownNode(Document.ReadNode(_r), o, qnames);
}
private void UnknownNode(XmlNode unknownNode, object o, string qnames)
{
if (unknownNode == null)
return;
}
private void GetCurrentPosition(out int lineNumber, out int linePosition)
{
if (Reader is IXmlLineInfo)
{
IXmlLineInfo lineInfo = (IXmlLineInfo)Reader;
lineNumber = lineInfo.LineNumber;
linePosition = lineInfo.LinePosition;
}
else
lineNumber = linePosition = -1;
}
private string CurrentTag()
{
switch (_r.NodeType)
{
case XmlNodeType.Element:
return "<" + _r.LocalName + " xmlns='" + _r.NamespaceURI + "'>";
case XmlNodeType.EndElement:
return ">";
case XmlNodeType.Text:
return _r.Value;
case XmlNodeType.CDATA:
return "CDATA";
case XmlNodeType.Comment:
return "<--";
case XmlNodeType.ProcessingInstruction:
return "<?";
default:
return "(unknown)";
}
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CreateUnknownTypeException"]/*' />
protected Exception CreateUnknownTypeException(XmlQualifiedName type)
{
return new InvalidOperationException(SR.Format(SR.XmlUnknownType, type.Name, type.Namespace, CurrentTag()));
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CreateReadOnlyCollectionException"]/*' />
protected Exception CreateReadOnlyCollectionException(string name)
{
return new InvalidOperationException(SR.Format(SR.XmlReadOnlyCollection, name));
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CreateAbstractTypeException"]/*' />
protected Exception CreateAbstractTypeException(string name, string ns)
{
return new InvalidOperationException(SR.Format(SR.XmlAbstractType, name, ns, CurrentTag()));
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CreateInaccessibleConstructorException"]/*' />
protected Exception CreateInaccessibleConstructorException(string typeName)
{
return new InvalidOperationException(SR.Format(SR.XmlConstructorInaccessible, typeName));
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CreateCtorHasSecurityException"]/*' />
protected Exception CreateCtorHasSecurityException(string typeName)
{
return new InvalidOperationException(SR.Format(SR.XmlConstructorHasSecurityAttributes, typeName));
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CreateUnknownNodeException"]/*' />
protected Exception CreateUnknownNodeException()
{
return new InvalidOperationException(SR.Format(SR.XmlUnknownNode, CurrentTag()));
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CreateUnknownConstantException"]/*' />
protected Exception CreateUnknownConstantException(string value, Type enumType)
{
return new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, value, enumType.Name));
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CreateInvalidCastException"]/*' />
protected Exception CreateInvalidCastException(Type type, object value)
{
return CreateInvalidCastException(type, value, null);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CreateInvalidCastException1"]/*' />
protected Exception CreateInvalidCastException(Type type, object value, string id)
{
if (value == null)
return new InvalidCastException(SR.Format(SR.XmlInvalidNullCast, type.FullName));
else if (id == null)
return new InvalidCastException(SR.Format(SR.XmlInvalidCast, value.GetType().FullName, type.FullName));
else
return new InvalidCastException(SR.Format(SR.XmlInvalidCastWithId, value.GetType().FullName, type.FullName, id));
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CreateBadDerivationException"]/*' />
protected Exception CreateBadDerivationException(string xsdDerived, string nsDerived, string xsdBase, string nsBase, string clrDerived, string clrBase)
{
return new InvalidOperationException(SR.Format(SR.XmlSerializableBadDerivation, xsdDerived, nsDerived, xsdBase, nsBase, clrDerived, clrBase));
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CreateMissingIXmlSerializableType"]/*' />
protected Exception CreateMissingIXmlSerializableType(string name, string ns, string clrType)
{
return new InvalidOperationException(SR.Format(SR.XmlSerializableMissingClrType, name, ns, typeof(XmlIncludeAttribute).Name, clrType));
//XmlSerializableMissingClrType= Type '{0}' from namespace '{1}' doesnot have corresponding IXmlSerializable type. Please consider adding {2} to '{3}'.
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.EnsureArrayIndex"]/*' />
protected Array EnsureArrayIndex(Array a, int index, Type elementType)
{
if (a == null) return Array.CreateInstance(elementType, 32);
if (index < a.Length) return a;
Array b = Array.CreateInstance(elementType, a.Length * 2);
Array.Copy(a, b, index);
return b;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ShrinkArray"]/*' />
protected Array ShrinkArray(Array a, int length, Type elementType, bool isNullable)
{
if (a == null)
{
if (isNullable) return null;
return Array.CreateInstance(elementType, 0);
}
if (a.Length == length) return a;
Array b = Array.CreateInstance(elementType, length);
Array.Copy(a, b, length);
return b;
}
// This is copied from Core's XmlReader.ReadString, as it is not exposed in the Contract.
protected virtual string ReadString()
{
if (Reader.ReadState != ReadState.Interactive)
{
return string.Empty;
}
Reader.MoveToElement();
if (Reader.NodeType == XmlNodeType.Element)
{
if (Reader.IsEmptyElement)
{
return string.Empty;
}
else if (!Reader.Read())
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
if (Reader.NodeType == XmlNodeType.EndElement)
{
return string.Empty;
}
}
string result = string.Empty;
while (IsTextualNode(Reader.NodeType))
{
result += Reader.Value;
if (!Reader.Read())
{
break;
}
}
return result;
}
// 0x6018
private static uint s_isTextualNodeBitmap = (1 << (int)XmlNodeType.Text) | (1 << (int)XmlNodeType.CDATA) | (1 << (int)XmlNodeType.Whitespace) | (1 << (int)XmlNodeType.SignificantWhitespace);
private static bool IsTextualNode(XmlNodeType nodeType)
{
return 0 != (s_isTextualNodeBitmap & (1 << (int)nodeType));
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReadString"]/*' />
protected string ReadString(string value)
{
return ReadString(value, false);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReadString1"]/*' />
protected string ReadString(string value, bool trim)
{
string str = _r.ReadString();
if (str != null && trim)
str = str.Trim();
if (value == null || value.Length == 0)
return str;
return value + str;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReadSerializable"]/*' />
protected IXmlSerializable ReadSerializable(IXmlSerializable serializable)
{
return ReadSerializable(serializable, false);
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReadSerializable"]/*' />
protected IXmlSerializable ReadSerializable(IXmlSerializable serializable, bool wrappedAny)
{
string name = null;
string ns = null;
if (wrappedAny)
{
name = _r.LocalName;
ns = _r.NamespaceURI;
_r.Read();
_r.MoveToContent();
}
serializable.ReadXml(_r);
if (wrappedAny)
{
while (_r.NodeType == XmlNodeType.Whitespace) _r.Skip();
if (_r.NodeType == XmlNodeType.None) _r.Skip();
if (_r.NodeType == XmlNodeType.EndElement && _r.LocalName == name && _r.NamespaceURI == ns)
{
Reader.Read();
}
}
return serializable;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.InitCallbacks"]/*' />
protected abstract void InitCallbacks();
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.ReadEndElement"]/*' />
protected void ReadEndElement()
{
while (_r.NodeType == XmlNodeType.Whitespace) _r.Skip();
if (_r.NodeType == XmlNodeType.None) _r.Skip();
else _r.ReadEndElement();
}
private object ReadXmlNodes(bool elementCanBeType)
{
ArrayList xmlNodeList = new ArrayList();
string elemLocalName = Reader.LocalName;
string elemNs = Reader.NamespaceURI;
string elemName = Reader.Name;
string xsiTypeName = null;
string xsiTypeNs = null;
int skippableNodeCount = 0;
int lineNumber = -1, linePosition = -1;
XmlNode unknownNode = null;
if (Reader.NodeType == XmlNodeType.Attribute)
{
XmlAttribute attr = Document.CreateAttribute(elemName, elemNs);
attr.Value = Reader.Value;
unknownNode = attr;
}
else
unknownNode = Document.CreateElement(elemName, elemNs);
GetCurrentPosition(out lineNumber, out linePosition);
XmlElement unknownElement = unknownNode as XmlElement;
while (Reader.MoveToNextAttribute())
{
if (IsXmlnsAttribute(Reader.Name) || (Reader.Name == "id" && (!_soap12 || Reader.NamespaceURI == Soap12.Encoding)))
skippableNodeCount++;
if ((object)Reader.LocalName == (object)_typeID &&
((object)Reader.NamespaceURI == (object)_instanceNsID ||
(object)Reader.NamespaceURI == (object)_instanceNs2000ID ||
(object)Reader.NamespaceURI == (object)_instanceNs1999ID
)
)
{
string value = Reader.Value;
int colon = value.LastIndexOf(':');
xsiTypeName = (colon >= 0) ? value.Substring(colon + 1) : value;
xsiTypeNs = Reader.LookupNamespace((colon >= 0) ? value.Substring(0, colon) : "");
}
XmlAttribute xmlAttribute = (XmlAttribute)Document.ReadNode(_r);
xmlNodeList.Add(xmlAttribute);
if (unknownElement != null) unknownElement.SetAttributeNode(xmlAttribute);
}
// If the node is referenced (or in case of paramStyle = bare) and if xsi:type is not
// specified then the element name is used as the type name. Reveal this to the user
// by adding an extra attribute node "xsi:type" with value as the element name.
if (elementCanBeType && xsiTypeName == null)
{
xsiTypeName = elemLocalName;
xsiTypeNs = elemNs;
XmlAttribute xsiTypeAttribute = Document.CreateAttribute(_typeID, _instanceNsID);
xsiTypeAttribute.Value = elemName;
xmlNodeList.Add(xsiTypeAttribute);
}
if (xsiTypeName == Soap.UrType &&
((object)xsiTypeNs == (object)_schemaNsID ||
(object)xsiTypeNs == (object)_schemaNs1999ID ||
(object)xsiTypeNs == (object)_schemaNs2000ID
)
)
skippableNodeCount++;
Reader.MoveToElement();
if (Reader.IsEmptyElement)
{
Reader.Skip();
}
else
{
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations = 0;
int readerCount = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
XmlNode xmlNode = Document.ReadNode(_r);
xmlNodeList.Add(xmlNode);
if (unknownElement != null) unknownElement.AppendChild(xmlNode);
Reader.MoveToContent();
CheckReaderCount(ref whileIterations, ref readerCount);
}
ReadEndElement();
}
if (xmlNodeList.Count <= skippableNodeCount)
return new object();
XmlNode[] childNodes = (XmlNode[])xmlNodeList.ToArray(typeof(XmlNode));
UnknownNode(unknownNode, null, null);
return childNodes;
}
/// <include file='doc\XmlSerializationReader.uex' path='docs/doc[@for="XmlSerializationReader.CheckReaderCount"]/*' />
protected void CheckReaderCount(ref int whileIterations, ref int readerCount)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Transactions
{
public sealed partial class CommittableTransaction : System.Transactions.Transaction, System.IAsyncResult, System.IDisposable, System.Runtime.Serialization.ISerializable
{
public CommittableTransaction() { }
public CommittableTransaction(System.TimeSpan timeout) { }
public CommittableTransaction(System.Transactions.TransactionOptions options) { }
object System.IAsyncResult.AsyncState { get { return default(object); } }
System.Threading.WaitHandle System.IAsyncResult.AsyncWaitHandle { get { return default(System.Threading.WaitHandle); } }
bool System.IAsyncResult.CompletedSynchronously { get { return default(bool); } }
bool System.IAsyncResult.IsCompleted { get { return default(bool); } }
public System.IAsyncResult BeginCommit(System.AsyncCallback callback, object user_defined_state) { return default(System.IAsyncResult); }
public void Commit() { }
public void EndCommit(System.IAsyncResult ar) { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public enum DependentCloneOption
{
BlockCommitUntilComplete = 0,
RollbackIfNotComplete = 1,
}
public sealed partial class DependentTransaction : System.Transactions.Transaction, System.Runtime.Serialization.ISerializable
{
internal DependentTransaction() { }
public void Complete() { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class Enlistment
{
internal Enlistment() { }
public void Done() { }
}
[System.FlagsAttribute]
public enum EnlistmentOptions
{
EnlistDuringPrepareRequired = 1,
None = 0,
}
public enum EnterpriseServicesInteropOption
{
Automatic = 1,
Full = 2,
None = 0,
}
public delegate System.Transactions.Transaction HostCurrentTransactionCallback();
[System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)(1))]
public partial interface IDtcTransaction
{
void Abort(System.IntPtr manager, int whatever, int whatever2);
void Commit(int whatever, int whatever2, int whatever3);
void GetTransactionInfo(System.IntPtr whatever);
}
public partial interface IEnlistmentNotification
{
void Commit(System.Transactions.Enlistment enlistment);
void InDoubt(System.Transactions.Enlistment enlistment);
void Prepare(System.Transactions.PreparingEnlistment preparingEnlistment);
void Rollback(System.Transactions.Enlistment enlistment);
}
public partial interface IPromotableSinglePhaseNotification : System.Transactions.ITransactionPromoter
{
void Initialize();
void Rollback(System.Transactions.SinglePhaseEnlistment enlistment);
void SinglePhaseCommit(System.Transactions.SinglePhaseEnlistment enlistment);
}
public partial interface ISimpleTransactionSuperior : System.Transactions.ITransactionPromoter
{
void Rollback();
}
public partial interface ISinglePhaseNotification : System.Transactions.IEnlistmentNotification
{
void SinglePhaseCommit(System.Transactions.SinglePhaseEnlistment enlistment);
}
public enum IsolationLevel
{
Chaos = 5,
ReadCommitted = 2,
ReadUncommitted = 3,
RepeatableRead = 1,
Serializable = 0,
Snapshot = 4,
Unspecified = 6,
}
public partial interface ITransactionPromoter
{
byte[] Promote();
}
public partial class PreparingEnlistment : System.Transactions.Enlistment
{
internal PreparingEnlistment() { }
public void ForceRollback() { }
public void ForceRollback(System.Exception ex) { }
public void Prepared() { }
public byte[] RecoveryInformation() { return default(byte[]); }
}
public partial class SinglePhaseEnlistment : System.Transactions.Enlistment
{
internal SinglePhaseEnlistment() { }
public void Aborted() { }
public void Aborted(System.Exception e) { }
public void Committed() { }
public void InDoubt() { }
public void InDoubt(System.Exception e) { }
}
public sealed partial class SubordinateTransaction : System.Transactions.Transaction
{
public SubordinateTransaction(System.Transactions.IsolationLevel level, System.Transactions.ISimpleTransactionSuperior superior) { }
}
public partial class Transaction : System.IDisposable, System.Runtime.Serialization.ISerializable
{
internal Transaction() { }
public static System.Transactions.Transaction Current { get { return default(System.Transactions.Transaction); } set { } }
public System.Transactions.IsolationLevel IsolationLevel { get { return default(System.Transactions.IsolationLevel); } }
public System.Transactions.TransactionInformation TransactionInformation { get { return default(System.Transactions.TransactionInformation); } }
public event System.Transactions.TransactionCompletedEventHandler TransactionCompleted { add { } remove { } }
protected System.IAsyncResult BeginCommitInternal(System.AsyncCallback callback) { return default(System.IAsyncResult); }
public System.Transactions.Transaction Clone() { return default(System.Transactions.Transaction); }
public System.Transactions.DependentTransaction DependentClone(System.Transactions.DependentCloneOption option) { return default(System.Transactions.DependentTransaction); }
public void Dispose() { }
protected void EndCommitInternal(System.IAsyncResult ar) { }
[System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand)]
public System.Transactions.Enlistment EnlistDurable(System.Guid manager, System.Transactions.IEnlistmentNotification notification, System.Transactions.EnlistmentOptions options) { return default(System.Transactions.Enlistment); }
[System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand)]
public System.Transactions.Enlistment EnlistDurable(System.Guid manager, System.Transactions.ISinglePhaseNotification notification, System.Transactions.EnlistmentOptions options) { return default(System.Transactions.Enlistment); }
public bool EnlistPromotableSinglePhase(System.Transactions.IPromotableSinglePhaseNotification notification) { return default(bool); }
public System.Transactions.Enlistment EnlistVolatile(System.Transactions.IEnlistmentNotification notification, System.Transactions.EnlistmentOptions options) { return default(System.Transactions.Enlistment); }
public System.Transactions.Enlistment EnlistVolatile(System.Transactions.ISinglePhaseNotification notification, System.Transactions.EnlistmentOptions options) { return default(System.Transactions.Enlistment); }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Transactions.Transaction x, System.Transactions.Transaction y) { return default(bool); }
public static bool operator !=(System.Transactions.Transaction x, System.Transactions.Transaction y) { return default(bool); }
public void Rollback() { }
public void Rollback(System.Exception ex) { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public partial class TransactionAbortedException : System.Transactions.TransactionException
{
public TransactionAbortedException() { }
protected TransactionAbortedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public TransactionAbortedException(string message) { }
public TransactionAbortedException(string message, System.Exception innerException) { }
}
public delegate void TransactionCompletedEventHandler(object o, System.Transactions.TransactionEventArgs e);
public partial class TransactionEventArgs : System.EventArgs
{
public TransactionEventArgs() { }
public System.Transactions.Transaction Transaction { get { return default(System.Transactions.Transaction); } }
}
public partial class TransactionException : System.SystemException
{
protected TransactionException() { }
protected TransactionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public TransactionException(string message) { }
public TransactionException(string message, System.Exception innerException) { }
}
public partial class TransactionInDoubtException : System.Transactions.TransactionException
{
protected TransactionInDoubtException() { }
protected TransactionInDoubtException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public TransactionInDoubtException(string message) { }
public TransactionInDoubtException(string message, System.Exception innerException) { }
}
public partial class TransactionInformation
{
internal TransactionInformation() { }
public System.DateTime CreationTime { get { return default(System.DateTime); } }
public System.Guid DistributedIdentifier { get { return default(System.Guid); } }
public string LocalIdentifier { get { return default(string); } }
public System.Transactions.TransactionStatus Status { get { return default(System.Transactions.TransactionStatus); } }
}
public static partial class TransactionInterop
{
public static System.Transactions.IDtcTransaction GetDtcTransaction(System.Transactions.Transaction transaction) { return default(System.Transactions.IDtcTransaction); }
public static byte[] GetExportCookie(System.Transactions.Transaction transaction, byte[] exportCookie) { return default(byte[]); }
public static System.Transactions.Transaction GetTransactionFromDtcTransaction(System.Transactions.IDtcTransaction dtc) { return default(System.Transactions.Transaction); }
public static System.Transactions.Transaction GetTransactionFromExportCookie(byte[] exportCookie) { return default(System.Transactions.Transaction); }
public static System.Transactions.Transaction GetTransactionFromTransmitterPropagationToken(byte[] token) { return default(System.Transactions.Transaction); }
public static byte[] GetTransmitterPropagationToken(System.Transactions.Transaction transaction) { return default(byte[]); }
public static byte[] GetWhereabouts() { return default(byte[]); }
}
public static partial class TransactionManager
{
public static System.TimeSpan DefaultTimeout { get { return default(System.TimeSpan); } }
public static System.Transactions.HostCurrentTransactionCallback HostCurrentCallback { get { return default(System.Transactions.HostCurrentTransactionCallback); } set { } }
public static System.TimeSpan MaximumTimeout { get { return default(System.TimeSpan); } }
public static event System.Transactions.TransactionStartedEventHandler DistributedTransactionStarted { add { } remove { } }
public static void RecoveryComplete(System.Guid manager) { }
public static System.Transactions.Enlistment Reenlist(System.Guid manager, byte[] recoveryInfo, System.Transactions.IEnlistmentNotification notification) { return default(System.Transactions.Enlistment); }
}
public partial class TransactionManagerCommunicationException : System.Transactions.TransactionException
{
protected TransactionManagerCommunicationException() { }
protected TransactionManagerCommunicationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public TransactionManagerCommunicationException(string message) { }
public TransactionManagerCommunicationException(string message, System.Exception innerException) { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct TransactionOptions
{
public System.Transactions.IsolationLevel IsolationLevel { get { return default(System.Transactions.IsolationLevel); } set { } }
public System.TimeSpan Timeout { get { return default(System.TimeSpan); } set { } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Transactions.TransactionOptions o1, System.Transactions.TransactionOptions o2) { return default(bool); }
public static bool operator !=(System.Transactions.TransactionOptions o1, System.Transactions.TransactionOptions o2) { return default(bool); }
}
public partial class TransactionPromotionException : System.Transactions.TransactionException
{
protected TransactionPromotionException() { }
protected TransactionPromotionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public TransactionPromotionException(string message) { }
public TransactionPromotionException(string message, System.Exception innerException) { }
}
public sealed partial class TransactionScope : System.IDisposable
{
public TransactionScope() { }
public TransactionScope(System.Transactions.Transaction transaction) { }
public TransactionScope(System.Transactions.Transaction transaction, System.TimeSpan timeout) { }
public TransactionScope(System.Transactions.Transaction transaction, System.TimeSpan timeout, System.Transactions.EnterpriseServicesInteropOption opt) { }
public TransactionScope(System.Transactions.TransactionScopeOption option) { }
public TransactionScope(System.Transactions.TransactionScopeOption option, System.TimeSpan timeout) { }
public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionOptions options) { }
public TransactionScope(System.Transactions.TransactionScopeOption scopeOption, System.Transactions.TransactionOptions options, System.Transactions.EnterpriseServicesInteropOption opt) { }
public void Complete() { }
public void Dispose() { }
}
public enum TransactionScopeOption
{
Required = 0,
RequiresNew = 1,
Suppress = 2,
}
public delegate void TransactionStartedEventHandler(object o, System.Transactions.TransactionEventArgs e);
public enum TransactionStatus
{
Aborted = 2,
Active = 0,
Committed = 1,
InDoubt = 3,
}
}
| |
// 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.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Transactions;
namespace System.Data.Common
{
internal static partial class ADP
{
// The class ADP defines the exceptions that are specific to the Adapters.
// The class contains functions that take the proper informational variables and then construct
// the appropriate exception with an error string obtained from the resource framework.
// The exception is then returned to the caller, so that the caller may then throw from its
// location so that the catcher of the exception will have the appropriate call stack.
// This class is used so that there will be compile time checking of error messages.
internal static Exception ExceptionWithStackTrace(Exception e)
{
try
{
throw e;
}
catch (Exception caught)
{
return caught;
}
}
//
// COM+ exceptions
//
internal static IndexOutOfRangeException IndexOutOfRange(int value)
{
IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture));
return e;
}
internal static IndexOutOfRangeException IndexOutOfRange()
{
IndexOutOfRangeException e = new IndexOutOfRangeException();
return e;
}
internal static TimeoutException TimeoutException(string error)
{
TimeoutException e = new TimeoutException(error);
return e;
}
internal static InvalidOperationException InvalidOperation(string error, Exception inner)
{
InvalidOperationException e = new InvalidOperationException(error, inner);
return e;
}
internal static OverflowException Overflow(string error)
{
return Overflow(error, null);
}
internal static OverflowException Overflow(string error, Exception inner)
{
OverflowException e = new OverflowException(error, inner);
return e;
}
internal static PlatformNotSupportedException DbTypeNotSupported(string dbType)
{
PlatformNotSupportedException e = new PlatformNotSupportedException(SR.GetString(SR.SQL_DbTypeNotSupportedOnThisPlatform, dbType));
return e;
}
internal static InvalidCastException InvalidCast()
{
InvalidCastException e = new InvalidCastException();
return e;
}
internal static IOException IO(string error)
{
IOException e = new IOException(error);
return e;
}
internal static IOException IO(string error, Exception inner)
{
IOException e = new IOException(error, inner);
return e;
}
internal static ObjectDisposedException ObjectDisposed(object instance)
{
ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name);
return e;
}
internal static Exception DataTableDoesNotExist(string collectionName)
{
return Argument(SR.GetString(SR.MDF_DataTableDoesNotExist, collectionName));
}
internal static InvalidOperationException MethodCalledTwice(string method)
{
InvalidOperationException e = new InvalidOperationException(SR.GetString(SR.ADP_CalledTwice, method));
return e;
}
// IDbCommand.CommandType
internal static ArgumentOutOfRangeException InvalidCommandType(CommandType value)
{
#if DEBUG
switch (value)
{
case CommandType.Text:
case CommandType.StoredProcedure:
case CommandType.TableDirect:
Debug.Assert(false, "valid CommandType " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(CommandType), (int)value);
}
// IDbConnection.BeginTransaction, OleDbTransaction.Begin
internal static ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value)
{
#if DEBUG
switch (value)
{
case IsolationLevel.Unspecified:
case IsolationLevel.Chaos:
case IsolationLevel.ReadUncommitted:
case IsolationLevel.ReadCommitted:
case IsolationLevel.RepeatableRead:
case IsolationLevel.Serializable:
case IsolationLevel.Snapshot:
Debug.Fail("valid IsolationLevel " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(IsolationLevel), (int)value);
}
// IDataParameter.Direction
internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value)
{
#if DEBUG
switch (value)
{
case ParameterDirection.Input:
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
Debug.Assert(false, "valid ParameterDirection " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(ParameterDirection), (int)value);
}
internal static Exception TooManyRestrictions(string collectionName)
{
return Argument(SR.GetString(SR.MDF_TooManyRestrictions, collectionName));
}
// IDbCommand.UpdateRowSource
internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value)
{
#if DEBUG
switch (value)
{
case UpdateRowSource.None:
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value);
}
//
// DbConnectionOptions, DataAccess
//
internal static ArgumentException InvalidMinMaxPoolSizeValues()
{
return ADP.Argument(SR.GetString(SR.ADP_InvalidMinMaxPoolSizeValues));
}
//
// DbConnection
//
internal static InvalidOperationException NoConnectionString()
{
return InvalidOperation(SR.GetString(SR.ADP_NoConnectionString));
}
internal static Exception MethodNotImplemented([CallerMemberName] string methodName = "")
{
return NotImplemented.ByDesignWithMessage(methodName);
}
internal static Exception QueryFailed(string collectionName, Exception e)
{
return InvalidOperation(SR.GetString(SR.MDF_QueryFailed, collectionName), e);
}
//
// : DbConnectionOptions, DataAccess, SqlClient
//
internal static Exception InvalidConnectionOptionValueLength(string key, int limit)
{
return Argument(SR.GetString(SR.ADP_InvalidConnectionOptionValueLength, key, limit));
}
internal static Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey)
{
return Argument(SR.GetString(SR.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey));
}
//
// DbConnectionPool and related
//
internal static Exception PooledOpenTimeout()
{
return ADP.InvalidOperation(SR.GetString(SR.ADP_PooledOpenTimeout));
}
internal static Exception NonPooledOpenTimeout()
{
return ADP.TimeoutException(SR.GetString(SR.ADP_NonPooledOpenTimeout));
}
//
// DbProviderException
//
internal static InvalidOperationException TransactionConnectionMismatch()
{
return Provider(SR.GetString(SR.ADP_TransactionConnectionMismatch));
}
internal static InvalidOperationException TransactionRequired(string method)
{
return Provider(SR.GetString(SR.ADP_TransactionRequired, method));
}
internal static Exception CommandTextRequired(string method)
{
return InvalidOperation(SR.GetString(SR.ADP_CommandTextRequired, method));
}
internal static Exception NoColumns()
{
return Argument(SR.GetString(SR.MDF_NoColumns));
}
internal static InvalidOperationException ConnectionRequired(string method)
{
return InvalidOperation(SR.GetString(SR.ADP_ConnectionRequired, method));
}
internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state)));
}
internal static Exception OpenReaderExists()
{
return OpenReaderExists(null);
}
internal static Exception OpenReaderExists(Exception e)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenReaderExists), e);
}
//
// DbDataReader
//
internal static Exception NonSeqByteAccess(long badIndex, long currIndex, string method)
{
return InvalidOperation(SR.GetString(SR.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method));
}
internal static Exception InvalidXml()
{
return Argument(SR.GetString(SR.MDF_InvalidXml));
}
internal static Exception NegativeParameter(string parameterName)
{
return InvalidOperation(SR.GetString(SR.ADP_NegativeParameter, parameterName));
}
internal static Exception InvalidXmlMissingColumn(string collectionName, string columnName)
{
return Argument(SR.GetString(SR.MDF_InvalidXmlMissingColumn, collectionName, columnName));
}
//
// SqlMetaData, SqlTypes, SqlClient
//
internal static Exception InvalidMetaDataValue()
{
return ADP.Argument(SR.GetString(SR.ADP_InvalidMetaDataValue));
}
internal static InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol)
{
return InvalidOperation(SR.GetString(SR.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture)));
}
static internal Exception InvalidXmlInvalidValue(string collectionName, string columnName)
{
return Argument(SR.GetString(SR.MDF_InvalidXmlInvalidValue, collectionName, columnName));
}
internal static Exception CollectionNameIsNotUnique(string collectionName)
{
return Argument(SR.GetString(SR.MDF_CollectionNameISNotUnique, collectionName));
}
//
// : IDbCommand
//
internal static Exception InvalidCommandTimeout(int value, [CallerMemberName] string property = "")
{
return Argument(SR.GetString(SR.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), property);
}
internal static Exception UninitializedParameterSize(int index, Type dataType)
{
return InvalidOperation(SR.GetString(SR.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name));
}
internal static Exception UnableToBuildCollection(string collectionName)
{
return Argument(SR.GetString(SR.MDF_UnableToBuildCollection, collectionName));
}
internal static Exception PrepareParameterType(DbCommand cmd)
{
return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterType, cmd.GetType().Name));
}
internal static Exception UndefinedCollection(string collectionName)
{
return Argument(SR.GetString(SR.MDF_UndefinedCollection, collectionName));
}
internal static Exception UnsupportedVersion(string collectionName)
{
return Argument(SR.GetString(SR.MDF_UnsupportedVersion, collectionName));
}
internal static Exception AmbigousCollectionName(string collectionName)
{
return Argument(SR.GetString(SR.MDF_AmbigousCollectionName, collectionName));
}
internal static Exception PrepareParameterSize(DbCommand cmd)
{
return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterSize, cmd.GetType().Name));
}
internal static Exception PrepareParameterScale(DbCommand cmd, string type)
{
return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterScale, cmd.GetType().Name, type));
}
internal static Exception MissingDataSourceInformationColumn()
{
return Argument(SR.GetString(SR.MDF_MissingDataSourceInformationColumn));
}
internal static Exception IncorrectNumberOfDataSourceInformationRows()
{
return Argument(SR.GetString(SR.MDF_IncorrectNumberOfDataSourceInformationRows));
}
internal static Exception MismatchedAsyncResult(string expectedMethod, string gotMethod)
{
return InvalidOperation(SR.GetString(SR.ADP_MismatchedAsyncResult, expectedMethod, gotMethod));
}
//
// : ConnectionUtil
//
internal static Exception ClosedConnectionError()
{
return InvalidOperation(SR.GetString(SR.ADP_ClosedConnectionError));
}
internal static Exception ConnectionAlreadyOpen(ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state)));
}
internal static Exception OpenConnectionPropertySet(string property, ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state)));
}
internal static Exception EmptyDatabaseName()
{
return Argument(SR.GetString(SR.ADP_EmptyDatabaseName));
}
internal enum ConnectionError
{
BeginGetConnectionReturnsNull,
GetConnectionReturnsNull,
ConnectionOptionsMissing,
CouldNotSwitchToClosedPreviouslyOpenedState,
}
internal static Exception MissingRestrictionColumn()
{
return Argument(SR.GetString(SR.MDF_MissingRestrictionColumn));
}
internal static Exception InternalConnectionError(ConnectionError internalError)
{
return InvalidOperation(SR.GetString(SR.ADP_InternalConnectionError, (int)internalError));
}
internal static Exception InvalidConnectRetryCountValue()
{
return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryCountValue));
}
internal static Exception MissingRestrictionRow()
{
return Argument(SR.GetString(SR.MDF_MissingRestrictionRow));
}
internal static Exception InvalidConnectRetryIntervalValue()
{
return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryIntervalValue));
}
//
// : DbDataReader
//
internal static InvalidOperationException AsyncOperationPending()
{
return InvalidOperation(SR.GetString(SR.ADP_PendingAsyncOperation));
}
//
// : Stream
//
internal static IOException ErrorReadingFromStream(Exception internalException)
{
return IO(SR.GetString(SR.SqlMisc_StreamErrorMessage), internalException);
}
internal static ArgumentException InvalidDataType(string typeName)
{
return Argument(SR.GetString(SR.ADP_InvalidDataType, typeName));
}
internal static ArgumentException UnknownDataType(Type dataType)
{
return Argument(SR.GetString(SR.ADP_UnknownDataType, dataType.FullName));
}
internal static ArgumentException DbTypeNotSupported(DbType type, Type enumtype)
{
return Argument(SR.GetString(SR.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name));
}
internal static ArgumentException InvalidOffsetValue(int value)
{
return Argument(SR.GetString(SR.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture)));
}
internal static ArgumentException InvalidSizeValue(int value)
{
return Argument(SR.GetString(SR.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture)));
}
internal static ArgumentException ParameterValueOutOfRange(Decimal value)
{
return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null)));
}
internal static ArgumentException ParameterValueOutOfRange(SqlDecimal value)
{
return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString()));
}
internal static ArgumentException VersionDoesNotSupportDataType(string typeName)
{
return Argument(SR.GetString(SR.ADP_VersionDoesNotSupportDataType, typeName));
}
internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner)
{
Debug.Assert(null != value, "null value on conversion failure");
Debug.Assert(null != inner, "null inner on conversion failure");
Exception e;
string message = SR.GetString(SR.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name);
if (inner is ArgumentException)
{
e = new ArgumentException(message, inner);
}
else if (inner is FormatException)
{
e = new FormatException(message, inner);
}
else if (inner is InvalidCastException)
{
e = new InvalidCastException(message, inner);
}
else if (inner is OverflowException)
{
e = new OverflowException(message, inner);
}
else
{
e = inner;
}
return e;
}
//
// : IDataParameterCollection
//
internal static Exception ParametersMappingIndex(int index, DbParameterCollection collection)
{
return CollectionIndexInt32(index, collection.GetType(), collection.Count);
}
internal static Exception ParametersSourceIndex(string parameterName, DbParameterCollection collection, Type parameterType)
{
return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType());
}
internal static Exception ParameterNull(string parameter, DbParameterCollection collection, Type parameterType)
{
return CollectionNullValue(parameter, collection.GetType(), parameterType);
}
internal static Exception UndefinedPopulationMechanism(string populationMechanism)
{
throw new NotImplementedException();
}
internal static Exception InvalidParameterType(DbParameterCollection collection, Type parameterType, object invalidValue)
{
return CollectionInvalidType(collection.GetType(), parameterType, invalidValue);
}
//
// : IDbTransaction
//
internal static Exception ParallelTransactionsNotSupported(DbConnection obj)
{
return InvalidOperation(SR.GetString(SR.ADP_ParallelTransactionsNotSupported, obj.GetType().Name));
}
internal static Exception TransactionZombied(DbTransaction obj)
{
return InvalidOperation(SR.GetString(SR.ADP_TransactionZombied, obj.GetType().Name));
}
// global constant strings
internal const string Parameter = "Parameter";
internal const string ParameterName = "ParameterName";
internal const string ParameterSetPosition = "set_Position";
internal const int DefaultCommandTimeout = 30;
internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections
// security issue, don't rely upon public static readonly values
internal static readonly string StrEmpty = ""; // String.Empty
internal const int CharSize = sizeof(char);
internal static Delegate FindBuilder(MulticastDelegate mcd)
{
if (null != mcd)
{
foreach (Delegate del in mcd.GetInvocationList())
{
if (del.Target is DbCommandBuilder)
return del;
}
}
return null;
}
internal static void TimerCurrent(out long ticks)
{
ticks = DateTime.UtcNow.ToFileTimeUtc();
}
internal static long TimerCurrent()
{
return DateTime.UtcNow.ToFileTimeUtc();
}
internal static long TimerFromSeconds(int seconds)
{
long result = checked((long)seconds * TimeSpan.TicksPerSecond);
return result;
}
internal static long TimerFromMilliseconds(long milliseconds)
{
long result = checked(milliseconds * TimeSpan.TicksPerMillisecond);
return result;
}
internal static bool TimerHasExpired(long timerExpire)
{
bool result = TimerCurrent() > timerExpire;
return result;
}
internal static long TimerRemaining(long timerExpire)
{
long timerNow = TimerCurrent();
long result = checked(timerExpire - timerNow);
return result;
}
internal static long TimerRemainingMilliseconds(long timerExpire)
{
long result = TimerToMilliseconds(TimerRemaining(timerExpire));
return result;
}
internal static long TimerRemainingSeconds(long timerExpire)
{
long result = TimerToSeconds(TimerRemaining(timerExpire));
return result;
}
internal static long TimerToMilliseconds(long timerValue)
{
long result = timerValue / TimeSpan.TicksPerMillisecond;
return result;
}
private static long TimerToSeconds(long timerValue)
{
long result = timerValue / TimeSpan.TicksPerSecond;
return result;
}
internal static string MachineName()
{
return Environment.MachineName;
}
internal static Transaction GetCurrentTransaction()
{
return Transaction.Current;
}
internal static bool IsDirection(DbParameter value, ParameterDirection condition)
{
#if DEBUG
IsDirectionValid(condition);
#endif
return (condition == (condition & value.Direction));
}
#if DEBUG
private static void IsDirectionValid(ParameterDirection value)
{
switch (value)
{ // @perfnote: Enum.IsDefined
case ParameterDirection.Input:
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
break;
default:
throw ADP.InvalidParameterDirection(value);
}
}
#endif
internal static void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType)
{
if ((value == null) || (value == DBNull.Value))
{
isNull = true;
isSqlType = false;
}
else
{
INullable nullable = (value as INullable);
if (nullable != null)
{
isNull = nullable.IsNull;
// Duplicated from DataStorage.cs
// For back-compat, SqlXml is not in this list
isSqlType = ((value is SqlBinary) ||
(value is SqlBoolean) ||
(value is SqlByte) ||
(value is SqlBytes) ||
(value is SqlChars) ||
(value is SqlDateTime) ||
(value is SqlDecimal) ||
(value is SqlDouble) ||
(value is SqlGuid) ||
(value is SqlInt16) ||
(value is SqlInt32) ||
(value is SqlInt64) ||
(value is SqlMoney) ||
(value is SqlSingle) ||
(value is SqlString));
}
else
{
isNull = false;
isSqlType = false;
}
}
}
internal static Exception AmbientTransactionIsNotSupported()
{
return new NotSupportedException(SR.AmbientTransactionsNotSupported);
}
private static Version s_systemDataVersion;
internal static Version GetAssemblyVersion()
{
// NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time
if (s_systemDataVersion == null)
{
s_systemDataVersion = new Version(ThisAssembly.InformationalVersion);
}
return s_systemDataVersion;
}
internal static readonly string[] AzureSqlServerEndpoints = {SR.GetString(SR.AZURESQL_GenericEndpoint),
SR.GetString(SR.AZURESQL_GermanEndpoint),
SR.GetString(SR.AZURESQL_UsGovEndpoint),
SR.GetString(SR.AZURESQL_ChinaEndpoint)};
// This method assumes dataSource parameter is in TCP connection string format.
internal static bool IsAzureSqlServerEndpoint(string dataSource)
{
// remove server port
int i = dataSource.LastIndexOf(',');
if (i >= 0)
{
dataSource = dataSource.Substring(0, i);
}
// check for the instance name
i = dataSource.LastIndexOf('\\');
if (i >= 0)
{
dataSource = dataSource.Substring(0, i);
}
// trim redundant whitespace
dataSource = dataSource.Trim();
// check if servername end with any azure endpoints
for (i = 0; i < AzureSqlServerEndpoints.Length; i++)
{
if (dataSource.EndsWith(AzureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
static internal ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value)
{
#if DEBUG
switch (value)
{
case DataRowVersion.Default:
case DataRowVersion.Current:
case DataRowVersion.Original:
case DataRowVersion.Proposed:
Debug.Fail($"Invalid DataRowVersion {value}");
break;
}
#endif
return InvalidEnumerationValue(typeof(DataRowVersion), (int)value);
}
internal static ArgumentException SingleValuedProperty(string propertyName, string value)
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_SingleValuedProperty, propertyName, value));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2)
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_DoubleValuedProperty, propertyName, value1, value2));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException InvalidPrefixSuffix()
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_InvalidPrefixSuffix));
TraceExceptionAsReturnValue(e);
return e;
}
// the return value is true if the string was quoted and false if it was not
// this allows the caller to determine if it is an error or not for the quotedString to not be quoted
internal static bool RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString)
{
int prefixLength = quotePrefix != null ? quotePrefix.Length : 0;
int suffixLength = quoteSuffix != null ? quoteSuffix.Length : 0;
if ((suffixLength + prefixLength) == 0)
{
unquotedString = quotedString;
return true;
}
if (quotedString == null)
{
unquotedString = quotedString;
return false;
}
int quotedStringLength = quotedString.Length;
// is the source string too short to be quoted
if (quotedStringLength < prefixLength + suffixLength)
{
unquotedString = quotedString;
return false;
}
// is the prefix present?
if (prefixLength > 0)
{
if (!quotedString.StartsWith(quotePrefix, StringComparison.Ordinal))
{
unquotedString = quotedString;
return false;
}
}
// is the suffix present?
if (suffixLength > 0)
{
if (!quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal))
{
unquotedString = quotedString;
return false;
}
unquotedString = quotedString.Substring(prefixLength, quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix + quoteSuffix, quoteSuffix);
}
else
{
unquotedString = quotedString.Substring(prefixLength, quotedStringLength - prefixLength);
}
return true;
}
internal static ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value)
{
Debug.Assert((0 > (int)value) || ((int)value > 0x3F), "valid CommandType " + value.ToString());
return InvalidEnumerationValue(typeof(CommandBehavior), (int)value);
}
internal static void ValidateCommandBehavior(CommandBehavior value)
{
if (((int)value < 0) || (0x3F < (int)value))
{
throw InvalidCommandBehavior(value);
}
}
internal static ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method)
{
return NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method);
}
internal static ArgumentException BadParameterName(string parameterName)
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_BadParameterName, parameterName));
TraceExceptionAsReturnValue(e);
return e;
}
internal static Exception DeriveParametersNotSupported(IDbCommand value)
{
return DataAdapter(SR.GetString(SR.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString()));
}
internal static Exception NoStoredProcedureExists(string sproc)
{
return InvalidOperation(SR.GetString(SR.ADP_NoStoredProcedureExists, sproc));
}
}
}
| |
namespace Societatis.HAL
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Societatis.Misc;
/// <summary>
/// Class describing a HAL relation collection.
/// </summary>
public class RelationCollection<T> : IRelationCollection<T>
{
private HashSet<string> singularRelations = new HashSet<string>();
/// <summary>
/// Field containing all relations and their items.
/// </summary>
private Dictionary<string, ICollection<T>> relations = new Dictionary<string, ICollection<T>>();
/// <summary>
/// Backing field for the DefaultValueProvider property.
/// </summary>
private Func<ICollection<T>> defaultValueProvider;
/// <summary>
/// Initializes a new instance of the <see cref="RelationCollection" /> class.
/// </summary>
public RelationCollection() // TODO: Make this something other than a list...
: this(() => new List<T>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RelationCollection" /> class,
/// using the specified valueprovider as a default value provider for the relation values.
/// </summary>
/// <param name="defaultValueProvider">Function returning a collection for relation values.</param>
public RelationCollection(Func<ICollection<T>> defaultValueProvider)
{
this.DefaultValueProvider = defaultValueProvider;
}
/// <summary>
/// Gets or sets a function providing the default collection when a new relation is requested.
/// </summary>
public Func<ICollection<T>> DefaultValueProvider
{
get => this.defaultValueProvider;
set
{
value.ThrowIfNull(nameof(value));
this.defaultValueProvider = value;
}
}
/// <summary>
/// Gets the number of relations in the collection.
/// </summary>
public virtual int Count
{
get => this.relations.Count;
}
/// <summary>
/// Gets or sets the item collection of the specified relation.
/// The value returned is never null. If a relation is requested that is not currently present in the collection,
/// it is added with the <see cref="DefaultValueProvider" /> and returned.
/// </summary>
/// <param name="rel">The relation to get items for.</param>
/// <returns>Collection of items in the specified relation.</returns>
/// <example>
/// This sample shows how to add items to a collection. Below code will not throw an exception when the relation does not exist.
/// <code>
/// var relations = new RelationCollection<object>();
/// relations["myRelation"].Add(new object()); // does not throw.
/// </code>
/// </example>
public virtual ICollection<T> this[string rel]
{
get
{
ICollection<T> result = null;
if (this.relations.ContainsKey(rel))
{
result = this.relations[rel];
}
if (result == null)
{
result = this.DefaultValueProvider();
this.Set(rel, result);
}
return result;
}
set => this.Set(rel, value);
}
/// <summary>
/// Gets the names of the relations.
/// </summary>
public virtual IEnumerable<string> RelationNames
{
get
{
foreach (var relation in this.relations.Where(r => r.Value?.Count > 0 ))
{
yield return relation.Key;
}
}
}
public IEnumerable<string> SingularRelations
{
get
{
foreach (var rel in this.singularRelations)
{
yield return rel;
}
}
}
/// <summary>
/// Adds all the specified items to the specified relation.
/// </summary>
/// <param name="rel">The relation to add the items to.</param>
/// <param name="items">The items to add to the relation.</param>
/// <exception cref="ArgumentNullException">Thrown when items is null</exception>
public virtual void Add(string rel, IEnumerable<T> items)
{
// NOTE: rel is checked for null in the Add method below.
items.ThrowIfNull(nameof(items));
foreach (T item in items.Where(i => i != null))
{
this.Add(rel, item);
}
}
/// <summary>
/// Adds the specified item to the specified relation.
/// </summary>
/// <param name="rel">The relation to add the item to.</param>
/// <param name="item">The item to add to the relation.</param>
public virtual void Add(string rel, T item)
{
this[rel].Add(item);
}
/// <summary>
/// Clears all relations and items.
/// </summary>
public virtual void Clear()
{
this.relations.Clear();
}
/// <summary>
/// Gets a value indicating whether the specified relation occurs.
/// </summary>
/// <param name="relation">The relation to contain.</param>
/// <returns>A value indicating whether the current collection contains the specified relation.</returns>
public virtual bool Contains(string rel)
{
bool result = false;
if (!string.IsNullOrWhiteSpace(rel))
{
result = this.relations.ContainsKey(rel)
&& this.relations[rel].Count > 0;
}
return result;
}
/// <summary>
/// Returns all items in the specified relation, or null if the relation is not found.
/// </summary>
/// <param name="rel">The relation to get items for.</param>
/// <returns>All items in the specified relation.</returns>
public ICollection<T> Get(string rel)
{
ICollection<T> result = null;
if (this.Contains(rel))
{
result = this.relations[rel];
}
return result;
}
/// <summary>
/// Sets the items in the specified relation, replacing existing items in the relation if they exist.
/// </summary>
/// <param name="rel">The relation to set the items for.</param>
/// <param name="items">The items to set in the relation.</param>
/// <exception cref="ArgumentNullException">Thrown when items is null.</exception>
/// <exception cref="ArgumentException">Thrown when rel is null or whitespace.</exception>
public virtual void Set(string rel, ICollection<T> items)
{
rel.ThrowIfNullOrWhiteSpace(nameof(rel));
items.ThrowIfNull(nameof(items));
this.relations[rel] = items;
}
/// <summary>
/// Sets the item in the specified relation, replacing existing items in the relation if they exist.
/// </summary>
/// <param name="rel">The relation to set the item for.</param>
/// <param name="items">The item to set in the relation.</param>
/// <exception cref="ArgumentNullException">Thrown when item is null.</exception>
/// <exception cref="ArgumentException">Thrown when rel is null or whitespace.</exception>
public virtual void Set(string rel, T item)
{
rel.ThrowIfNullOrWhiteSpace(nameof(rel));
item.ThrowIfNull(nameof(item));
this.Remove(rel);
this.Add(rel, item);
}
/// <summary>
/// Removes the specified relation, and all its items from the collection.
/// </summary>
/// <param name="relation">The relation to remove.</param>
/// <returns>A value indicathing whether the relation was removed from the collection in this call.</returns>
public virtual bool Remove(string rel)
{
bool removed = false;
if (!string.IsNullOrWhiteSpace(rel)
&& this.relations.ContainsKey(rel))
{
removed = this.relations.Remove(rel);
}
return removed;
}
public virtual void MarkSingular(string relation)
{
relation.ThrowIfNullOrWhiteSpace(nameof(relation));
if (!this.singularRelations.Contains(relation))
{
var oldCollection = this.Get(relation);
var newCollection = new SingularCollection<T>();
if (oldCollection != null)
{
if (oldCollection.Count > 1)
{
throw new InvalidOperationException(
$"Cannot mark relation {relation} as singular, because it currently contains more than one item.");
}
// Add zero or one item(s).
foreach (var item in oldCollection)
{
newCollection.Add(item);
}
}
this.Set(relation, newCollection);
this.singularRelations.Add(relation);
}
}
public IEnumerator<IRelation<T>> GetEnumerator()
{
foreach (var relationName in this.RelationNames)
{
yield return new HALRelation<T>
{
Relation = relationName,
IsSingular = this.singularRelations.Contains(relationName),
Items = this[relationName]
};
}
}
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
private class HALRelation<TRelation> : IRelation<TRelation>
{
public string Relation { get; set; }
public bool IsSingular { get; set; }
public ICollection<TRelation> Items { get; set; }
}
}
}
| |
using Microsoft.VisualBasic.CompilerServices;
using System;
using System.Configuration;
using System.Text;
namespace DigestLib.Data.Sql
{
public sealed class LibSqlSelect
{
private string _Field;
private string _Table;
private string _Where;
private string _OrderBy;
private string _GroupBy;
private string _Having;
private int _Top;
private int _Offset;
private static string _ProviderName;
public string ProviderName
{
get
{
bool flag = Operators.CompareString(LibSqlSelect._ProviderName, "", false) == 0;
if (flag)
{
LibSqlSelect._ProviderName = ConfigurationManager.ConnectionStrings[0].ProviderName;
}
return LibSqlSelect._ProviderName;
}
set
{
LibSqlSelect._ProviderName = value;
}
}
public string Field
{
get
{
return this._Field;
}
set
{
this._Field = value;
}
}
public string Table
{
get
{
return this._Table;
}
set
{
this._Table = value;
}
}
public string Where
{
get
{
return this._Where;
}
set
{
this._Where = value;
}
}
public string OrderBy
{
get
{
return this._OrderBy;
}
set
{
this._OrderBy = value;
}
}
public string GroupBy
{
get
{
return this._GroupBy;
}
set
{
this._GroupBy = value;
}
}
public string Having
{
get
{
return this._Having;
}
set
{
this._Having = value;
}
}
public int Top
{
get
{
return this._Top;
}
set
{
this._Top = value;
}
}
public int Offset
{
get
{
return this._Offset;
}
set
{
this._Offset = value;
}
}
public string SqlSelect
{
get
{
return this.ToString();
}
}
static LibSqlSelect()
{
LibSqlSelect._ProviderName = "";
LibSqlSelect._ProviderName = ConfigurationManager.ConnectionStrings[0].ProviderName;
}
public LibSqlSelect()
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
}
public LibSqlSelect(string field)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
}
public LibSqlSelect(string field, string table)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
}
public LibSqlSelect(string field, string table, int top)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Top = top;
}
public LibSqlSelect(string field, string table, int top, int offset)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Top = top;
this._Offset = offset;
}
public LibSqlSelect(string field, string table, string where)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Where = where;
}
public LibSqlSelect(string field, string table, string where, int top)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Where = where;
this._Top = top;
}
public LibSqlSelect(string field, string table, string where, int top, int offset)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Where = where;
this._Top = top;
this._Offset = offset;
}
public LibSqlSelect(string field, string table, string where, string orderBy)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Where = where;
this._OrderBy = orderBy;
}
public LibSqlSelect(string field, string table, string where, string orderBy, int top)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Where = where;
this._OrderBy = orderBy;
this._Top = top;
}
public LibSqlSelect(string field, string table, string where, string orderBy, int top, int offset)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Where = where;
this._OrderBy = orderBy;
this._Top = top;
this._Offset = offset;
}
public LibSqlSelect(string field, string table, string where, string orderBy, string groupBy)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Where = where;
this._OrderBy = orderBy;
this._GroupBy = groupBy;
}
public LibSqlSelect(string field, string table, string where, string orderBy, string groupBy, int top)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Where = where;
this._OrderBy = orderBy;
this._GroupBy = groupBy;
this._Top = top;
}
public LibSqlSelect(string field, string table, string where, string orderBy, string groupBy, int top, int offset)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Where = where;
this._OrderBy = orderBy;
this._GroupBy = groupBy;
this._Top = top;
this._Offset = offset;
}
public LibSqlSelect(string field, string table, string where, string orderBy, string groupBy, string having)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Where = where;
this._OrderBy = orderBy;
this._GroupBy = groupBy;
this._Having = having;
}
public LibSqlSelect(string field, string table, string where, string orderBy, string groupBy, string having, int top)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Where = where;
this._OrderBy = orderBy;
this._GroupBy = groupBy;
this._Having = having;
this._Top = top;
}
public LibSqlSelect(string field, string table, string where, string orderBy, string groupBy, string having, int top, int offset)
{
this._Field = "";
this._Table = "";
this._Where = "";
this._OrderBy = "";
this._GroupBy = "";
this._Having = "";
this._Top = 0;
this._Offset = 0;
this._Field = field;
this._Table = table;
this._Where = where;
this._OrderBy = orderBy;
this._GroupBy = groupBy;
this._Having = having;
this._Top = top;
this._Offset = offset;
}
public override string ToString()
{
bool flag = Operators.CompareString(this.ProviderName, "", false) == 0;
if (flag)
{
this.ProviderName = "System.Data.SqlClient";
}
return this.ToString(this.ProviderName);
}
public string ToString(string ProviderName)
{
StringBuilder stringBuilder = new StringBuilder();
string left = ProviderName.ToUpper();
bool flag = Operators.CompareString(left, "SYSTEM.DATA.SQLCLIENT", false) == 0;
if (flag)
{
bool flag2 = this._Field.Trim().Length > 0;
if (flag2)
{
stringBuilder.Append("SELECT");
flag2 = (this._Top > 0);
if (flag2)
{
stringBuilder.Append(" TOP ");
stringBuilder.Append(this._Top);
}
stringBuilder.Append(" " + this._Field);
flag2 = (this._Table.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" FROM ");
stringBuilder.Append(this._Table);
flag2 = (this._Where.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" WHERE ");
stringBuilder.Append(this._Where);
}
flag2 = (this._GroupBy.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" GROUP BY ");
stringBuilder.Append(this._GroupBy);
flag2 = (this._Having.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" HAVING ");
stringBuilder.Append(this._Having);
}
}
flag2 = (this._OrderBy.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" ORDER BY ");
stringBuilder.Append(this._OrderBy);
}
}
}
}
else
{
bool flag2 = Operators.CompareString(left, "SYSTEM.DATA.ODBC", false) == 0;
if (flag2)
{
flag = (this._Field.Trim().Length > 0);
if (flag)
{
stringBuilder.Append("SELECT");
flag2 = (this._Top > 0);
if (flag2)
{
stringBuilder.Append(" TOP ");
stringBuilder.Append(this._Top);
}
stringBuilder.Append(" " + this._Field);
flag2 = (this._Table.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" FROM ");
stringBuilder.Append(this._Table);
flag2 = (this._Where.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" WHERE ");
stringBuilder.Append(this._Where);
}
flag2 = (this._GroupBy.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" GROUP BY ");
stringBuilder.Append(this._GroupBy);
flag2 = (this._Having.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" HAVING ");
stringBuilder.Append(this._Having);
}
}
flag2 = (this._OrderBy.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" ORDER BY ");
stringBuilder.Append(this._OrderBy);
}
}
}
}
else
{
flag2 = (Operators.CompareString(left, "MYSQL.DATA.MYSQLCLIENT", false) == 0);
if (flag2)
{
flag = (this._Field.Trim().Length > 0);
if (flag)
{
stringBuilder.Append("SELECT ");
stringBuilder.Append(this._Field);
flag2 = (this._Table.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" FROM ");
stringBuilder.Append(this._Table);
flag2 = (this._Where.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" WHERE ");
stringBuilder.Append(this._Where);
}
flag2 = (this._GroupBy.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" GROUP BY ");
stringBuilder.Append(this._GroupBy);
flag2 = (this._Having.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" HAVING ");
stringBuilder.Append(this._Having);
}
}
flag2 = (this._OrderBy.Trim().Length > 0);
if (flag2)
{
stringBuilder.Append(" ORDER BY ");
stringBuilder.Append(this._OrderBy);
}
}
flag2 = (this._Top > 0);
if (flag2)
{
stringBuilder.Append(" LIMIT ");
stringBuilder.Append(this._Top);
}
flag2 = (this._Offset > 0);
if (flag2)
{
stringBuilder.Append(" OFFSET ");
stringBuilder.Append(this._Offset);
}
}
}
}
}
return stringBuilder.ToString();
}
}
}
| |
/// Credit RahulOfTheRamanEffect
/// Sourced from - https://forum.unity3d.com/members/rahuloftheramaneffect.773241/
namespace UnityEngine.UI.Extensions
{
/// <summary>
/// Arranges child objects into a non-uniform grid, with fixed column widths and flexible row heights
/// </summary>
[AddComponentMenu("Layout/Extensions/Table Layout Group")]
public class TableLayoutGroup : LayoutGroup
{
public enum Corner
{
UpperLeft = 0,
UpperRight = 1,
LowerLeft = 2,
LowerRight = 3
}
[SerializeField]
protected Corner startCorner = Corner.UpperLeft;
/// <summary>
/// The corner starting from which the cells should be arranged
/// </summary>
public Corner StartCorner
{
get { return startCorner; }
set
{
SetProperty(ref startCorner, value);
}
}
[SerializeField]
protected float[] columnWidths = new float[1] { 96f };
/// <summary>
/// The widths of all the columns in the table
/// </summary>
public float[] ColumnWidths
{
get { return columnWidths; }
set
{
SetProperty(ref columnWidths, value);
}
}
[SerializeField]
protected float minimumRowHeight = 32f;
/// <summary>
/// The minimum height for any row in the table
/// </summary>
public float MinimumRowHeight
{
get { return minimumRowHeight; }
set
{
SetProperty(ref minimumRowHeight, value);
}
}
[SerializeField]
protected bool flexibleRowHeight = true;
/// <summary>
/// Expand rows to fit the cell with the highest preferred height?
/// </summary>
public bool FlexibleRowHeight
{
get { return flexibleRowHeight; }
set
{
SetProperty(ref flexibleRowHeight, value);
}
}
[SerializeField]
protected float columnSpacing = 0f;
/// <summary>
/// The horizontal spacing between each cell in the table
/// </summary>
public float ColumnSpacing
{
get { return columnSpacing; }
set
{
SetProperty(ref columnSpacing, value);
}
}
[SerializeField]
protected float rowSpacing = 0;
/// <summary>
/// The vertical spacing between each row in the table
/// </summary>
public float RowSpacing
{
get { return rowSpacing; }
set
{
SetProperty(ref rowSpacing, value);
}
}
// Temporarily stores data generated during the execution CalculateLayoutInputVertical for use in SetLayoutVertical
private float[] preferredRowHeights;
public override void CalculateLayoutInputHorizontal()
{
base.CalculateLayoutInputHorizontal();
float horizontalSize = padding.horizontal;
// We calculate the actual cell count for cases where the number of children is lesser than the number of columns
int actualCellCount = Mathf.Min(rectChildren.Count, columnWidths.Length);
for (int i = 0; i < actualCellCount; i++)
{
horizontalSize += columnWidths[i];
horizontalSize += columnSpacing;
}
horizontalSize -= columnSpacing;
SetLayoutInputForAxis(horizontalSize, horizontalSize, 0, 0);
}
public override void CalculateLayoutInputVertical()
{
int columnCount = columnWidths.Length;
int rowCount = Mathf.CeilToInt(rectChildren.Count / (float)columnCount);
preferredRowHeights = new float[rowCount];
float totalMinHeight = padding.vertical;
float totalPreferredHeight = padding.vertical;
if (rowCount > 1)
{
float heightFromSpacing = ((rowCount - 1) * rowSpacing);
totalMinHeight += heightFromSpacing;
totalPreferredHeight += heightFromSpacing;
}
if (flexibleRowHeight)
{
// If flexibleRowHeight is enabled, find the max value for minimum and preferred heights in each row
float maxMinimumHeightInRow = 0;
float maxPreferredHeightInRow = 0;
for (int i = 0; i < rowCount; i++)
{
maxMinimumHeightInRow = minimumRowHeight;
maxPreferredHeightInRow = minimumRowHeight;
for (int j = 0; j < columnCount; j++)
{
int childIndex = (i * columnCount) + j;
// Safeguard against tables with incomplete rows
if (childIndex == rectChildren.Count)
break;
maxPreferredHeightInRow = Mathf.Max(LayoutUtility.GetPreferredHeight(rectChildren[childIndex]), maxPreferredHeightInRow);
maxMinimumHeightInRow = Mathf.Max(LayoutUtility.GetMinHeight(rectChildren[childIndex]), maxMinimumHeightInRow);
}
totalMinHeight += maxMinimumHeightInRow;
totalPreferredHeight += maxPreferredHeightInRow;
// Add calculated row height to a commonly accessible array for reuse in SetLayoutVertical()
preferredRowHeights[i] = maxPreferredHeightInRow;
}
}
else
{
// If flexibleRowHeight is disabled, then use the minimumRowHeight to calculate vertical layout information
for (int i = 0; i < rowCount; i++)
preferredRowHeights[i] = minimumRowHeight;
totalMinHeight += rowCount * minimumRowHeight;
totalPreferredHeight = totalMinHeight;
}
totalPreferredHeight = Mathf.Max(totalMinHeight, totalPreferredHeight);
SetLayoutInputForAxis(totalMinHeight, totalPreferredHeight, 1, 1);
}
public override void SetLayoutHorizontal()
{
// If no column width is defined, then assign a reasonable default
if (columnWidths.Length == 0)
columnWidths = new float[1] { 0f };
int columnCount = columnWidths.Length;
int cornerX = (int)startCorner % 2;
float startOffset = 0;
float requiredSizeWithoutPadding = 0;
// We calculate the actual cell count for cases where the number of children is lesser than the number of columns
int actualCellCount = Mathf.Min(rectChildren.Count, columnWidths.Length);
for (int i = 0; i < actualCellCount; i++)
{
requiredSizeWithoutPadding += columnWidths[i];
requiredSizeWithoutPadding += columnSpacing;
}
requiredSizeWithoutPadding -= columnSpacing;
startOffset = GetStartOffset(0, requiredSizeWithoutPadding);
if (cornerX == 1)
startOffset += requiredSizeWithoutPadding;
float positionX = startOffset;
for (int i = 0; i < rectChildren.Count; i++)
{
int currentColumnIndex = i % columnCount;
// If it's the first cell in the row, reset positionX
if (currentColumnIndex == 0)
positionX = startOffset;
if (cornerX == 1)
positionX -= columnWidths[currentColumnIndex];
SetChildAlongAxis(rectChildren[i], 0, positionX, columnWidths[currentColumnIndex]);
if (cornerX == 1)
positionX -= columnSpacing;
else
positionX += columnWidths[currentColumnIndex] + columnSpacing;
}
}
public override void SetLayoutVertical()
{
int columnCount = columnWidths.Length;
int rowCount = preferredRowHeights.Length;
int cornerY = (int)startCorner / 2;
float startOffset = 0;
float requiredSizeWithoutPadding = 0;
for (int i = 0; i < rowCount; i++)
requiredSizeWithoutPadding += preferredRowHeights[i];
if (rowCount > 1)
requiredSizeWithoutPadding += (rowCount - 1) * rowSpacing;
startOffset = GetStartOffset(1, requiredSizeWithoutPadding);
if (cornerY == 1)
startOffset += requiredSizeWithoutPadding;
float positionY = startOffset;
for (int i = 0; i < rowCount; i++)
{
if (cornerY == 1)
positionY -= preferredRowHeights[i];
for (int j = 0; j < columnCount; j++)
{
int childIndex = (i * columnCount) + j;
// Safeguard against tables with incomplete rows
if (childIndex == rectChildren.Count)
break;
SetChildAlongAxis(rectChildren[childIndex], 1, positionY, preferredRowHeights[i]);
}
if (cornerY == 1)
positionY -= rowSpacing;
else
positionY += preferredRowHeights[i] + rowSpacing;
}
// Set preferredRowHeights to null to free memory
preferredRowHeights = null;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.NetCore.Analyzers.Security.Helpers;
namespace Microsoft.NetCore.Analyzers.Security
{
using static MicrosoftNetCoreAnalyzersResources;
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DoNotUseDeprecatedSecurityProtocols : DiagnosticAnalyzer
{
internal static readonly DiagnosticDescriptor DeprecatedRule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA5364",
nameof(DoNotUseDeprecatedSecurityProtocols),
nameof(DoNotUseDeprecatedSecurityProtocolsMessage),
RuleLevel.IdeHidden_BulkConfigurable,
isPortedFxCopRule: false,
isDataflowRule: false,
isReportedAtCompilationEnd: false,
descriptionResourceStringName: nameof(DoNotUseDeprecatedSecurityProtocolsDescription));
internal static readonly DiagnosticDescriptor HardCodedRule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA5386",
nameof(HardCodedSecurityProtocolTitle),
nameof(HardCodedSecurityProtocolMessage),
RuleLevel.Disabled,
isPortedFxCopRule: false,
isDataflowRule: false,
isReportedAtCompilationEnd: false);
private readonly ImmutableHashSet<string> HardCodedSafeProtocolMetadataNames = ImmutableHashSet.Create(
StringComparer.Ordinal,
"Tls12",
"Tls13");
private const string SystemDefaultName = "SystemDefault";
private const int UnsafeBits = 48 | 192 | 768; // SecurityProtocolType Ssl3 Tls10 Tls11
private const int HardCodedBits = 3072 | 12288; // SecurityProtocolType Tls12 Tls13
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(DeprecatedRule, HardCodedRule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
// Security analyzer - analyze and report diagnostics on generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterCompilationStartAction(
(CompilationStartAnalysisContext compilationStartAnalysisContext) =>
{
var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilationStartAnalysisContext.Compilation);
if (!wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName(
WellKnownTypeNames.SystemNetSecurityProtocolType,
out var securityProtocolTypeTypeSymbol)
|| !wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName(
WellKnownTypeNames.SystemNetServicePointManager,
out var servicePointManagerTypeSymbol))
{
return;
}
compilationStartAnalysisContext.RegisterOperationAction(
(OperationAnalysisContext operationAnalysisContext) =>
{
var fieldReferenceOperation = (IFieldReferenceOperation)operationAnalysisContext.Operation;
// Make sure we're not inside an &= assignment like:
// ServicePointManager.SecurityProtocol &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11)
// cuz &= is at worst, disabling protocol versions.
if (IsReferencingSecurityProtocolType(
fieldReferenceOperation,
out var isDeprecatedProtocol,
out var isHardCodedOkayProtocol)
&& null == fieldReferenceOperation.GetAncestor<ICompoundAssignmentOperation>(
OperationKind.CompoundAssignment,
IsAndEqualsServicePointManagerAssignment))
{
if (isDeprecatedProtocol)
{
operationAnalysisContext.ReportDiagnostic(
fieldReferenceOperation.CreateDiagnostic(
DeprecatedRule,
fieldReferenceOperation.Field.Name));
}
else if (isHardCodedOkayProtocol)
{
operationAnalysisContext.ReportDiagnostic(
fieldReferenceOperation.CreateDiagnostic(
HardCodedRule,
fieldReferenceOperation.Field.Name));
}
}
}, OperationKind.FieldReference);
compilationStartAnalysisContext.RegisterOperationAction(
(OperationAnalysisContext operationAnalysisContext) =>
{
var assignmentOperation = (IAssignmentOperation)operationAnalysisContext.Operation;
// Make sure this is an assignment operation for a SecurityProtocolType, and not
// an assignment like:
// ServicePointManager.SecurityProtocol &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11)
// cuz &= is at worst, disabling protocol versions.
if (!securityProtocolTypeTypeSymbol.Equals(assignmentOperation.Target.Type)
|| (assignmentOperation is ICompoundAssignmentOperation compoundAssignmentOperation
&& IsAndEqualsServicePointManagerAssignment(compoundAssignmentOperation)))
{
return;
}
// Find the topmost operation with a bad bit set, unless we find an operation that would've been
// flagged by the FieldReference callback above.
IOperation? foundDeprecatedOperation = null;
bool foundDeprecatedReference = false;
IOperation? foundHardCodedOperation = null;
bool foundHardCodedReference = false;
foreach (IOperation childOperation in assignmentOperation.Value.DescendantsAndSelf())
{
if (childOperation is IFieldReferenceOperation fieldReferenceOperation
&& IsReferencingSecurityProtocolType(
fieldReferenceOperation,
out var isDeprecatedProtocol,
out var isHardCodedOkayProtocol))
{
if (isDeprecatedProtocol)
{
foundDeprecatedReference = true;
}
else if (isHardCodedOkayProtocol)
{
foundHardCodedReference = true;
}
if (foundDeprecatedReference && foundHardCodedReference)
{
return;
}
}
if (childOperation.ConstantValue.HasValue
&& childOperation.ConstantValue.Value is int integerValue)
{
if (foundDeprecatedOperation == null // Only want the first.
&& (integerValue & UnsafeBits) != 0)
{
foundDeprecatedOperation = childOperation;
}
if (foundHardCodedOperation == null // Only want the first.
&& (integerValue & HardCodedBits) != 0)
{
foundHardCodedOperation = childOperation;
}
}
}
if (foundDeprecatedOperation != null && !foundDeprecatedReference)
{
operationAnalysisContext.ReportDiagnostic(
foundDeprecatedOperation.CreateDiagnostic(
DeprecatedRule,
foundDeprecatedOperation.ConstantValue));
}
if (foundHardCodedOperation != null && !foundHardCodedReference)
{
operationAnalysisContext.ReportDiagnostic(
foundHardCodedOperation.CreateDiagnostic(
HardCodedRule,
foundHardCodedOperation.ConstantValue));
}
},
OperationKind.SimpleAssignment,
OperationKind.CompoundAssignment);
return;
// Local function(s).
bool IsReferencingSecurityProtocolType(
IFieldReferenceOperation fieldReferenceOperation,
out bool isDeprecatedProtocol,
out bool isHardCodedOkayProtocol)
{
RoslynDebug.Assert(securityProtocolTypeTypeSymbol != null);
if (securityProtocolTypeTypeSymbol.Equals(fieldReferenceOperation.Field.ContainingType))
{
if (HardCodedSafeProtocolMetadataNames.Contains(fieldReferenceOperation.Field.Name))
{
isHardCodedOkayProtocol = true;
isDeprecatedProtocol = false;
}
else if (fieldReferenceOperation.Field.Name == SystemDefaultName)
{
isHardCodedOkayProtocol = false;
isDeprecatedProtocol = false;
}
else
{
isDeprecatedProtocol = true;
isHardCodedOkayProtocol = false;
}
return true;
}
else
{
isHardCodedOkayProtocol = false;
isDeprecatedProtocol = false;
return false;
}
}
bool IsAndEqualsServicePointManagerAssignment(ICompoundAssignmentOperation compoundAssignmentOperation)
{
RoslynDebug.Assert(servicePointManagerTypeSymbol != null);
return compoundAssignmentOperation.OperatorKind == BinaryOperatorKind.And
&& compoundAssignmentOperation.Target is IPropertyReferenceOperation targetPropertyReference
&& targetPropertyReference.Instance == null
&& servicePointManagerTypeSymbol.Equals(targetPropertyReference.Property.ContainingType)
&& targetPropertyReference.Property.MetadataName == "SecurityProtocol";
}
});
}
}
}
| |
// Created by Paul Gonzalez Becerra
using System;
using Saserdote.DataSystems;
using Saserdote.GamingServices;
using Saserdote.Input;
namespace Saserdote.UI
{
public abstract class GUIContainer:GUIComponent
{
#region --- Field Variables ---
// Variables
public GUIComponent focusedComp;
protected FList<GUIComponent> components;
// GUI Container Event Tells
protected bool bEComponents;
// GUI Container Events
protected GEvent e_components;
#endregion // Field Variables
#region --- Constructors ---
protected GUIContainer():base()
{
components= new FList<GUIComponent>();
focusedComp= null;
bEComponents= false;
e_components= null;
}
#endregion // Constructors
#region --- Properties ---
// Gets the size of the components of the container
public int size
{
get { return components.size; }
}
// Gets and sets the items of the lists
public GUIComponent this[int index]
{
get { return components[index]; }
set { components[index]= value; callCompEvent(); }
}
#endregion // Properties
#region --- Events ---
// Event for when the list of components have changed
public event GEvent onComponentsChanged
{
add { e_components= addEvent<GEvent>(e_components, value, out bEComponents); }
remove { e_components= removeEvent<GEvent>(e_components, value, out bEComponents); }
}
#endregion // Events
#region --- Methods ---
// Call the components changed events
protected void callCompEvent()
{
if(bEComponents)
e_components(this);
}
// Clears the components
public void clear()
{
components.clear();
callCompEvent();
}
// Adds in a gui component
public bool add(GUIComponent comp)
{
// Variables
bool bFirst= (size== 0);
if(components.add(comp))
{
components[size-1].setParent(this);
if(bFirst)
focusedComp= components[0];
callCompEvent();
return true;
}
return false;
}
// Adds in an array of gui component
public bool addRange(params GUIComponent[] comps)
{
// Variables
int startIndex= size;
bool bFirst= (startIndex== 0);
if(components.addRange(comps))
{
for(int i= startIndex; i< size; i++)
components[i].setParent(this);
if(bFirst)
focusedComp= components[0];
callCompEvent();
return true;
}
return false;
}
// Finds if the given component is contained within the container
public bool contains(GUIComponent comp, int startIndex)
{
return components.contains(comp, startIndex);
}
public bool contains(GUIComponent comp) { return contains(comp, 0); }
// Gets the index of the given item
public int getIndex(GUIComponent comp, int startIndex)
{
return components.getIndex(comp, startIndex);
}
public int getIndex(GUIComponent comp) { return getIndex(comp, 0); }
// Removes the gui component from the given index
public bool remove(GUIComponent comp, int startIndex)
{
if(components.remove(comp, startIndex))
{
if(size== 0)
focusedComp= null;
callCompEvent();
return true;
}
return false;
}
public bool remove(GUIComponent comp) { return remove(comp, 0); }
// Inserts the given gui to the given index
public void insert(GUIComponent comp, int index)
{
// Variables
bool bFirst= (size== 0);
components.insert(comp, index);
if(bFirst)
focusedComp= components[0];
callCompEvent();
}
// Removes the gui component of the given index
public bool removeAt(int index)
{
if(components.removeAt(index))
{
if(size== 0)
focusedComp= null;
callCompEvent();
return true;
}
return false;
}
#endregion // Methods
#region --- Inherited Methods ---
// Renders the gui component
public override void render(ref Game game, ref GameTime time)
{
for(int i= 0; i< size; i++)
components[i].render(ref game, ref time);
}
// Updates the gui component
public override void update(ref GameTime time)
{
for(int i= 0; i< size; i++)
components[i].update(ref time);
}
// Handles the component's input
public override void handleInput(ref InputArgs args)
{
for(int i= 0; i< size; i++)
components[i].handleInput(ref args);
}
#endregion // Inherited Methods
}
}
// End of File
| |
namespace SqlStreamStore
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using SqlStreamStore.Streams;
public partial class MsSqlStreamStore
{
protected override async Task<ReadAllPage> ReadAllForwardsInternal(
long fromPosition,
int maxCount,
bool prefetch,
ReadNextAllPage readNext,
CancellationToken cancellationToken)
{
maxCount = maxCount == int.MaxValue ? maxCount - 1 : maxCount;
long position = fromPosition;
using (var connection = _createConnection())
{
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
var commandText = prefetch ? _scripts.ReadAllForwardWithData : _scripts.ReadAllForward;
using (var command = new SqlCommand(commandText, connection))
{
command.CommandTimeout = _commandTimeout;
command.Parameters.AddWithValue("position", position);
command.Parameters.AddWithValue("count", maxCount + 1); //Read extra row to see if at end or not
var reader = await command
.ExecuteReaderAsync(CommandBehavior.SequentialAccess, cancellationToken)
.ConfigureAwait(false);
List<StreamMessage> messages = new List<StreamMessage>();
if (!reader.HasRows)
{
return new ReadAllPage(
fromPosition,
fromPosition,
true,
ReadDirection.Forward,
readNext,
messages.ToArray());
}
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
if(messages.Count == maxCount)
{
messages.Add(default);
}
else
{
var streamId = reader.GetString(0);
var streamVersion = reader.GetInt32(1);
position = reader.GetInt64(2);
var messageId = reader.GetGuid(3);
var created = reader.GetDateTime(4);
var type = reader.GetString(5);
var jsonMetadata = reader.GetString(6);
Func<CancellationToken, Task<string>> getJsonData;
if(prefetch)
{
var jsonData = await reader.GetTextReader(7).ReadToEndAsync();
getJsonData = _ => Task.FromResult(jsonData);
}
else
{
var streamIdInfo = new StreamIdInfo(streamId);
getJsonData = ct => GetJsonData(streamIdInfo.SqlStreamId.Id, streamVersion, ct);
}
var message = new StreamMessage(streamId,
messageId,
streamVersion,
position,
created,
type,
jsonMetadata,
getJsonData);
messages.Add(message);
}
}
bool isEnd = true;
if (messages.Count == maxCount + 1) // An extra row was read, we're not at the end
{
isEnd = false;
messages.RemoveAt(maxCount);
}
var nextPosition = messages[messages.Count - 1].Position + 1;
return new ReadAllPage(
fromPosition,
nextPosition,
isEnd,
ReadDirection.Forward,
readNext,
messages.ToArray());
}
}
}
protected override async Task<ReadAllPage> ReadAllBackwardsInternal(
long fromPositionExclusive,
int maxCount,
bool prefetch,
ReadNextAllPage readNext,
CancellationToken cancellationToken)
{
maxCount = maxCount == int.MaxValue ? maxCount - 1 : maxCount;
long position = fromPositionExclusive == Position.End ? long.MaxValue : fromPositionExclusive;
using (var connection = _createConnection())
{
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
var commandText = prefetch ? _scripts.ReadAllBackwardWithData : _scripts.ReadAllBackward;
using (var command = new SqlCommand(commandText, connection))
{
command.CommandTimeout = _commandTimeout;
command.Parameters.AddWithValue("position", position);
command.Parameters.AddWithValue("count", maxCount + 1); //Read extra row to see if at end or not
var reader = await command
.ExecuteReaderAsync(CommandBehavior.SequentialAccess, cancellationToken)
.ConfigureAwait(false);
List<StreamMessage> messages = new List<StreamMessage>();
if (!reader.HasRows)
{
// When reading backwards and there are no more items, then next position is LongPosition.Start,
// regardless of what the fromPosition is.
return new ReadAllPage(
Position.Start,
Position.Start,
true,
ReadDirection.Backward,
readNext,
messages.ToArray());
}
long lastPosition = 0;
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
var streamId = reader.GetString(0);
var streamVersion = reader.GetInt32(1);
position = reader.GetInt64(2);
var messageId = reader.GetGuid(3);
var created = reader.GetDateTime(4);
var type = reader.GetString(5);
var jsonMetadata = reader.GetString(6);
Func<CancellationToken, Task<string>> getJsonData;
if (prefetch)
{
var jsonData = await reader.GetTextReader(7).ReadToEndAsync();
getJsonData = _ => Task.FromResult(jsonData);
}
else
{
var streamIdInfo = new StreamIdInfo(streamId);
getJsonData = ct => GetJsonData(streamIdInfo.SqlStreamId.Id, streamVersion, ct);
}
var message = new StreamMessage(
streamId,
messageId,
streamVersion,
position,
created,
type,
jsonMetadata, getJsonData);
messages.Add(message);
lastPosition = position;
}
bool isEnd = true;
var nextPosition = lastPosition;
if (messages.Count == maxCount + 1) // An extra row was read, we're not at the end
{
isEnd = false;
messages.RemoveAt(maxCount);
}
fromPositionExclusive = messages.Any() ? messages[0].Position : 0;
return new ReadAllPage(
fromPositionExclusive,
nextPosition,
isEnd,
ReadDirection.Backward,
readNext,
messages.ToArray());
}
}
}
}
}
| |
//
// 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.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Network.Models;
namespace Microsoft.WindowsAzure.Management.Network.Models
{
/// <summary>
/// The response to a ListVirtualNetworkGateways request.
/// </summary>
public partial class ListVirtualNetworkGatewaysResponse : AzureOperationResponse, IEnumerable<ListVirtualNetworkGatewaysResponse.VirtualNetworkGateway>
{
private IList<ListVirtualNetworkGatewaysResponse.VirtualNetworkGateway> _virtualNetworkGateways;
/// <summary>
/// Optional. The list of virtual network gateways.
/// </summary>
public IList<ListVirtualNetworkGatewaysResponse.VirtualNetworkGateway> VirtualNetworkGateways
{
get { return this._virtualNetworkGateways; }
set { this._virtualNetworkGateways = value; }
}
/// <summary>
/// Initializes a new instance of the
/// ListVirtualNetworkGatewaysResponse class.
/// </summary>
public ListVirtualNetworkGatewaysResponse()
{
this.VirtualNetworkGateways = new LazyList<ListVirtualNetworkGatewaysResponse.VirtualNetworkGateway>();
}
/// <summary>
/// Gets the sequence of VirtualNetworkGateways.
/// </summary>
public IEnumerator<ListVirtualNetworkGatewaysResponse.VirtualNetworkGateway> GetEnumerator()
{
return this.VirtualNetworkGateways.GetEnumerator();
}
/// <summary>
/// Gets the sequence of VirtualNetworkGateways.
/// </summary>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public partial class VirtualNetworkGateway
{
private BgpSettings _bgpSettings;
/// <summary>
/// Optional. Virtual network gateway's BGP settings
/// </summary>
public BgpSettings BgpSettings
{
get { return this._bgpSettings; }
set { this._bgpSettings = value; }
}
private GatewayDefaultSite _defaultSite;
/// <summary>
/// Optional. The default site on the gateway.
/// </summary>
public GatewayDefaultSite DefaultSite
{
get { return this._defaultSite; }
set { this._defaultSite = value; }
}
private bool _enableBgp;
/// <summary>
/// Optional. EnableBgp flag
/// </summary>
public bool EnableBgp
{
get { return this._enableBgp; }
set { this._enableBgp = value; }
}
private Guid _gatewayId;
/// <summary>
/// Optional. The local network Gateway Id
/// </summary>
public Guid GatewayId
{
get { return this._gatewayId; }
set { this._gatewayId = value; }
}
private string _gatewayName;
/// <summary>
/// Optional. The virtual network gateway Name.
/// </summary>
public string GatewayName
{
get { return this._gatewayName; }
set { this._gatewayName = value; }
}
private string _gatewaySKU;
/// <summary>
/// Optional. The SKU for this virtual network gateway.
/// </summary>
public string GatewaySKU
{
get { return this._gatewaySKU; }
set { this._gatewaySKU = value; }
}
private string _gatewayType;
/// <summary>
/// Optional. The type of gateway routing used for this virtual
/// network.
/// </summary>
public string GatewayType
{
get { return this._gatewayType; }
set { this._gatewayType = value; }
}
private GatewayEvent _lastEvent;
/// <summary>
/// Optional. The last recorded event for this virtual network
/// gateway.
/// </summary>
public GatewayEvent LastEvent
{
get { return this._lastEvent; }
set { this._lastEvent = value; }
}
private string _location;
/// <summary>
/// Optional. Location
/// </summary>
public string Location
{
get { return this._location; }
set { this._location = value; }
}
private string _state;
/// <summary>
/// Optional. The provisioning state of the virtual network gateway.
/// </summary>
public string State
{
get { return this._state; }
set { this._state = value; }
}
private string _subnetId;
/// <summary>
/// Optional. SubnetId
/// </summary>
public string SubnetId
{
get { return this._subnetId; }
set { this._subnetId = value; }
}
private string _vipAddress;
/// <summary>
/// Optional. The virtual IP address for this virtual network
/// gateway.
/// </summary>
public string VipAddress
{
get { return this._vipAddress; }
set { this._vipAddress = value; }
}
private string _vnetId;
/// <summary>
/// Optional. VnetId
/// </summary>
public string VnetId
{
get { return this._vnetId; }
set { this._vnetId = value; }
}
/// <summary>
/// Initializes a new instance of the VirtualNetworkGateway class.
/// </summary>
public VirtualNetworkGateway()
{
}
}
}
}
| |
/*
###
# # ######### _______ _ _ ______ _ _
## ######## @ ## |______ | | | ____ | |
################## | |_____| |_____| |_____|
## ############# f r a m e w o r k
# # #########
###
(c) 2015 - 2017 FUGU framework project
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 Fugu.Logging.Configuration;
using Fugu.Logging.Serialization;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
namespace Fugu.Logging
{
public class FileSystemLogger : ILogger
{
private readonly IFileSystemLoggerConfiguration _configuration;
private readonly string _name;
private readonly IFileSystemLogSerializer _serializer;
private static readonly ConcurrentDictionary<string, ReaderWriterLockSlim> _logFilesLocks = new ConcurrentDictionary<string, ReaderWriterLockSlim>();
private static readonly object _buildFoldersStructureLock = new object();
public FileSystemLogger(string name, IFileSystemLoggerConfiguration configuration)
{
Contract.NotNullOrWhiteSpace(name, nameof(name));
Contract.NotNull(configuration, nameof(configuration));
_name = name;
_configuration = configuration;
_serializer = new FileSystemLogJsonSerializer();
}
/// <summary>Writes a log entry.</summary>
/// <typeparam name="TState"></typeparam>
/// <param name="logLevel">Entry will be written on this level.</param>
/// <param name="eventId">Id of the event.</param>
/// <param name="state">The entry to be written. Can be also an object.</param>
/// <param name="exception">The exception related to this entry.</param>
/// <param name="formatter">
/// Function to create a <c>string</c> message of the <paramref name="state" /> and
/// <paramref name="exception" />.
/// </param>
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
Contract.NotNull(formatter, nameof(formatter));
if (!IsEnabled(logLevel))
{
return;
}
var message = formatter(state, exception);
if (string.IsNullOrEmpty(message))
{
return;
}
if (exception != null)
{
message = $"{message}{Environment.NewLine}{Environment.NewLine}{exception}";
}
try
{
Log(logLevel, message);
}
catch
{
}
}
/// <summary>
/// Checks if the given <paramref name="logLevel" /> is enabled.
/// </summary>
/// <param name="logLevel">level to be checked.</param>
/// <returns><c>true</c> if enabled.</returns>
public bool IsEnabled(LogLevel logLevel)
{
if (!_configuration.Enabled)
{
return false;
}
var logLevelConfiguration = _configuration[logLevel];
return logLevelConfiguration?.Enabled == true;
}
/// <summary>Begins a logical operation scope.</summary>
/// <typeparam name="TState"></typeparam>
/// <param name="state">The identifier for the scope.</param>
/// <returns>An IDisposable that ends the logical operation scope on dispose.</returns>
public IDisposable BeginScope<TState>(TState state)
{
return NoopDisposable.Instance;
}
private void Log(LogLevel logLevel, string message)
{
var logData = BuildLogData(logLevel, message);
Log(logData);
}
private LogData BuildLogData(LogLevel logLevel, string message)
{
var logData = new LogData
{
LogLevel = logLevel,
Application = string.Format("{0}{1}", _configuration.ApplicationName, !string.IsNullOrWhiteSpace(_name) ? "_" + _name : string.Empty),
Version = _configuration.ApplicationVersion,
Message = message,
DateTime = DateTime.Now,
User = _configuration.UserName,
ComputerName = _configuration.ComputerName
};
return logData;
}
private void Log(LogData logData)
{
var logLevel = logData.LogLevel;
var folderPath = GetFolderPath(logLevel);
CheckIfDirectoryExists(folderPath);
var filePath = GetLogFilePath(folderPath, logLevel);
WriteToFile(filePath, logData);
}
private string GetFolderPath(LogLevel logLevel)
{
var logLevelConfig = _configuration[logLevel];
string result;
if (!string.IsNullOrWhiteSpace(logLevelConfig.Folder))
{
if (Path.IsPathRooted(logLevelConfig.Folder))
{
result = logLevelConfig.Folder;
}
else
{
result = Path.Combine(_configuration.Path, logLevelConfig.Folder);
}
}
else
{
result = _configuration.Path;
}
return result;
}
private string GetLogFilePath(string folderPath, LogLevel logLevel)
{
var logFileName = GetLogFileName(logLevel);
return Path.Combine(folderPath, logFileName);
}
private string GetLogFileName(LogLevel logLevel)
{
var logLevelConfig = _configuration[logLevel];
string fileNameSuffix;
switch (logLevelConfig.GroupingType)
{
case FileSystemGroupingType.Request:
fileNameSuffix = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffffff-") + Guid.NewGuid().ToString();
break;
case FileSystemGroupingType.Hour:
fileNameSuffix = DateTime.Now.ToString("yyyy-MM-dd-HH");
break;
case FileSystemGroupingType.Day:
fileNameSuffix = DateTime.Today.ToString("yyyy-MM-dd");
break;
case FileSystemGroupingType.Week:
fileNameSuffix = DateTime.Today.ToString("yyyy-MM-") + DateTime.Today.GetWeekOfMonth().ToString();
break;
case FileSystemGroupingType.Month:
fileNameSuffix = DateTime.Today.ToString("yyyy-MM");
break;
case FileSystemGroupingType.Year:
fileNameSuffix = DateTime.Today.ToString("yyyy");
break;
case FileSystemGroupingType.SingleFile:
fileNameSuffix = null;
break;
default:
#pragma warning disable RCS1079 // Throwing of new NotImplementedException.
throw new NotImplementedException();
#pragma warning restore RCS1079 // Throwing of new NotImplementedException.
}
if (fileNameSuffix != null)
{
fileNameSuffix = "_" + fileNameSuffix;
}
return $"{logLevel}{fileNameSuffix ?? string.Empty}.log";
}
private void WriteToFile(string filePath, LogData logData)
{
var contentToWrite = _serializer.Serialize(logData);
var fileLock = GetFileLock(filePath);
try
{
fileLock.EnterWriteLock();
File.AppendAllText(filePath, contentToWrite);
}
finally
{
fileLock.ExitWriteLock();
}
}
private ReaderWriterLockSlim GetFileLock(string filePath)
{
return _logFilesLocks.GetOrAdd(filePath, f => new ReaderWriterLockSlim());
}
private void CheckIfDirectoryExists(string folderPath)
{
if (!Directory.Exists(folderPath))
{
lock (_buildFoldersStructureLock)
{
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
}
}
}
private class NoopDisposable : IDisposable
{
public static readonly NoopDisposable Instance = new NoopDisposable();
public void Dispose()
{
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008-2018 Charlie Poole, Rob Prouse
//
// 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 System.Reflection;
using System.Security;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
namespace NUnit.Framework
{
/// <summary>
/// TestCaseSourceAttribute indicates the source to be used to
/// provide test cases for a test method.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
public class TestCaseSourceAttribute : NUnitAttribute, ITestBuilder, IImplyFixture
{
private readonly NUnitTestCaseBuilder _builder = new NUnitTestCaseBuilder();
#region Constructors
/// <summary>
/// Construct with the name of the method, property or field that will provide data
/// </summary>
/// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
public TestCaseSourceAttribute(string sourceName)
{
this.SourceName = sourceName;
}
/// <summary>
/// Construct with a Type and name
/// </summary>
/// <param name="sourceType">The Type that will provide data</param>
/// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
/// <param name="methodParams">A set of parameters passed to the method, works only if the Source Name is a method.
/// If the source name is a field or property has no effect.</param>
public TestCaseSourceAttribute(Type sourceType, string sourceName, object[] methodParams)
{
this.MethodParams = methodParams;
this.SourceType = sourceType;
this.SourceName = sourceName;
}
/// <summary>
/// Construct with a Type and name
/// </summary>
/// <param name="sourceType">The Type that will provide data</param>
/// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
public TestCaseSourceAttribute(Type sourceType, string sourceName)
{
this.SourceType = sourceType;
this.SourceName = sourceName;
}
/// <summary>
/// Construct with a name
/// </summary>
/// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
/// <param name="methodParams">A set of parameters passed to the method, works only if the Source Name is a method.
/// If the source name is a field or property has no effect.</param>
public TestCaseSourceAttribute(string sourceName, object[] methodParams)
{
this.MethodParams = methodParams;
this.SourceName = sourceName;
}
/// <summary>
/// Construct with a Type
/// </summary>
/// <param name="sourceType">The type that will provide data</param>
public TestCaseSourceAttribute(Type sourceType)
{
this.SourceType = sourceType;
}
#endregion
#region Properties
/// <summary>
/// A set of parameters passed to the method, works only if the Source Name is a method.
/// If the source name is a field or property has no effect.
/// </summary>
public object[] MethodParams { get; }
/// <summary>
/// The name of a the method, property or fiend to be used as a source
/// </summary>
public string SourceName { get; }
/// <summary>
/// A Type to be used as a source
/// </summary>
public Type SourceType { get; }
/// <summary>
/// Gets or sets the category associated with every fixture created from
/// this attribute. May be a single category or a comma-separated list.
/// </summary>
public string Category { get; set; }
#endregion
#region ITestBuilder Members
/// <summary>
/// Builds any number of tests from the specified method and context.
/// </summary>
/// <param name="method">The method to be used as a test.</param>
/// <param name="suite">The parent to which the test will be added.</param>
public IEnumerable<TestMethod> BuildFrom(FixtureMethod method, Test suite)
{
int count = 0;
foreach (TestCaseParameters parms in GetTestCasesFor(method))
{
count++;
yield return _builder.BuildTestMethod(method, suite, parms);
}
// If count > 0, error messages will be shown for each case
// but if it's 0, we need to add an extra "test" to show the message.
if (count == 0 && method.Method.GetParameters().Length == 0)
{
var parms = new TestCaseParameters();
parms.RunState = RunState.NotRunnable;
parms.Properties.Set(PropertyNames.SkipReason, "TestCaseSourceAttribute may not be used on a method without parameters");
yield return _builder.BuildTestMethod(method, suite, parms);
}
}
#endregion
#region Helper Methods
[SecuritySafeCritical]
private IEnumerable<ITestCaseData> GetTestCasesFor(FixtureMethod method)
{
List<ITestCaseData> data = new List<ITestCaseData>();
try
{
IEnumerable source;
var previousState = SandboxedThreadState.Capture();
try
{
source = GetTestCaseSource(method.FixtureType);
}
finally
{
previousState.Restore();
}
if (source != null)
{
foreach (object item in source)
{
// First handle two easy cases:
// 1. Source is null. This is really an error but if we
// throw an exception we simply get an invalid fixture
// without good info as to what caused it. Passing a
// single null argument will cause an error to be
// reported at the test level, in most cases.
// 2. User provided an ITestCaseData and we just use it.
ITestCaseData parms = item == null
? new TestCaseParameters(new object[] { null })
: item as ITestCaseData;
if (parms == null)
{
object[] args = null;
// 3. An array was passed, it may be an object[]
// or possibly some other kind of array, which
// TestCaseSource can accept.
var array = item as Array;
if (array != null)
{
// If array has the same number of elements as parameters
// and it does not fit exactly into single existing parameter
// we believe that this array contains arguments, not is a bare
// argument itself.
var parameters = method.Method.GetParameters();
var argsNeeded = parameters.Length;
if (argsNeeded > 0 && argsNeeded == array.Length && parameters[0].ParameterType != array.GetType())
{
args = new object[array.Length];
for (var i = 0; i < array.Length; i++)
args[i] = array.GetValue(i);
}
}
if (args == null)
{
args = new object[] { item };
}
parms = new TestCaseParameters(args);
}
if (this.Category != null)
foreach (string cat in this.Category.Split(new char[] { ',' }))
parms.Properties.Add(PropertyNames.Category, cat);
data.Add(parms);
}
}
else
{
data.Clear();
data.Add(new TestCaseParameters(new Exception("The test case source could not be found.")));
}
}
catch (Exception ex)
{
data.Clear();
data.Add(new TestCaseParameters(ex));
}
return data;
}
private IEnumerable GetTestCaseSource(Type type)
{
Type sourceType = SourceType ?? type;
// Handle Type implementing IEnumerable separately
if (SourceName == null)
return Reflect.Construct(sourceType, null) as IEnumerable;
MemberInfo[] members = sourceType.GetMember(SourceName,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
if (members.Length == 1)
{
MemberInfo member = members[0];
var field = member as FieldInfo;
if (field != null)
return field.IsStatic
? (MethodParams == null ? (IEnumerable)field.GetValue(null)
: ReturnErrorAsParameter(ParamGivenToField))
: ReturnErrorAsParameter(SourceMustBeStatic);
var property = member as PropertyInfo;
if (property != null)
return property.GetGetMethod(true).IsStatic
? (MethodParams == null ? (IEnumerable)property.GetValue(null, null)
: ReturnErrorAsParameter(ParamGivenToProperty))
: ReturnErrorAsParameter(SourceMustBeStatic);
var m = member as MethodInfo;
if (m != null)
return m.IsStatic
? (MethodParams == null || m.GetParameters().Length == MethodParams.Length
? (IEnumerable)m.Invoke(null, MethodParams)
: ReturnErrorAsParameter(NumberOfArgsDoesNotMatch))
: ReturnErrorAsParameter(SourceMustBeStatic);
}
return null;
}
private static IEnumerable ReturnErrorAsParameter(string errorMessage)
{
var parms = new TestCaseParameters();
parms.RunState = RunState.NotRunnable;
parms.Properties.Set(PropertyNames.SkipReason, errorMessage);
return new TestCaseParameters[] { parms };
}
private const string SourceMustBeStatic =
"The sourceName specified on a TestCaseSourceAttribute must refer to a static field, property or method.";
private const string ParamGivenToField = "You have specified a data source field but also given a set of parameters. Fields cannot take parameters, " +
"please revise the 3rd parameter passed to the TestCaseSourceAttribute and either remove " +
"it or specify a method.";
private const string ParamGivenToProperty = "You have specified a data source property but also given a set of parameters. " +
"Properties cannot take parameters, please revise the 3rd parameter passed to the " +
"TestCaseSource attribute and either remove it or specify a method.";
private const string NumberOfArgsDoesNotMatch = "You have given the wrong number of arguments to the method in the TestCaseSourceAttribute" +
", please check the number of parameters passed in the object is correct in the 3rd parameter for the " +
"TestCaseSourceAttribute and this matches the number of parameters in the target method and try again.";
#endregion
}
}
| |
//
// ImageReader.cs
//
// Author:
// Jb Evain ([email protected])
//
// (C) 2005 - 2007 Jb Evain
//
// 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.
//
namespace Mono.Cecil.Binary {
using System;
using System.IO;
using System.Text;
using Mono.Cecil.Metadata;
class ImageReader : BaseImageVisitor {
MetadataReader m_mdReader;
BinaryReader m_binaryReader;
Image m_image;
public MetadataReader MetadataReader {
get { return m_mdReader; }
}
public Image Image {
get { return m_image; }
}
ImageReader (Image img, BinaryReader reader)
{
m_image = img;
m_binaryReader = reader;
}
static ImageReader Read (Image img, Stream stream)
{
ImageReader reader = new ImageReader (img, new BinaryReader (stream));
img.Accept (reader);
return reader;
}
public static ImageReader Read (string file)
{
if (file == null)
throw new ArgumentNullException ("file");
FileInfo fi = new FileInfo (file);
if (!File.Exists (fi.FullName))
#if CF_1_0 || CF_2_0
throw new FileNotFoundException (fi.FullName);
#else
throw new FileNotFoundException (string.Format ("File '{0}' not found.", fi.FullName), fi.FullName);
#endif
return Read (new Image (fi), new FileStream (
fi.FullName, FileMode.Open,
FileAccess.Read, FileShare.Read));
}
public static ImageReader Read (byte [] image)
{
if (image == null)
throw new ArgumentNullException ("image");
if (image.Length == 0)
throw new ArgumentException ("Empty image array");
return Read (new Image (), new MemoryStream (image));
}
public static ImageReader Read (Stream stream)
{
if (stream == null)
throw new ArgumentNullException ("stream");
if (!stream.CanRead)
throw new ArgumentException ("Can not read from stream");
return Read (new Image (), stream);
}
public BinaryReader GetReader ()
{
return m_binaryReader;
}
public override void VisitImage (Image img)
{
m_mdReader = new MetadataReader (this);
}
void SetPositionToAddress (RVA address)
{
m_binaryReader.BaseStream.Position = m_image.ResolveVirtualAddress (address);
}
public override void VisitDOSHeader (DOSHeader header)
{
header.Start = m_binaryReader.ReadBytes (60);
header.Lfanew = m_binaryReader.ReadUInt32 ();
header.End = m_binaryReader.ReadBytes (64);
m_binaryReader.BaseStream.Position = header.Lfanew;
if (m_binaryReader.ReadUInt16 () != 0x4550 ||
m_binaryReader.ReadUInt16 () != 0)
throw new ImageFormatException ("Invalid PE File Signature");
}
public override void VisitPEFileHeader (PEFileHeader header)
{
header.Machine = m_binaryReader.ReadUInt16 ();
header.NumberOfSections = m_binaryReader.ReadUInt16 ();
header.TimeDateStamp = m_binaryReader.ReadUInt32 ();
header.PointerToSymbolTable = m_binaryReader.ReadUInt32 ();
header.NumberOfSymbols = m_binaryReader.ReadUInt32 ();
header.OptionalHeaderSize = m_binaryReader.ReadUInt16 ();
header.Characteristics = (ImageCharacteristics) m_binaryReader.ReadUInt16 ();
}
ulong ReadIntOrLong ()
{
return m_image.PEOptionalHeader.StandardFields.IsPE64 ?
m_binaryReader.ReadUInt64 () :
m_binaryReader.ReadUInt32 ();
}
RVA ReadRVA ()
{
return m_binaryReader.ReadUInt32 ();
}
DataDirectory ReadDataDirectory ()
{
return new DataDirectory (ReadRVA (), m_binaryReader.ReadUInt32 ());
}
public override void VisitNTSpecificFieldsHeader (PEOptionalHeader.NTSpecificFieldsHeader header)
{
header.ImageBase = ReadIntOrLong ();
header.SectionAlignment = m_binaryReader.ReadUInt32 ();
header.FileAlignment = m_binaryReader.ReadUInt32 ();
header.OSMajor = m_binaryReader.ReadUInt16 ();
header.OSMinor = m_binaryReader.ReadUInt16 ();
header.UserMajor = m_binaryReader.ReadUInt16 ();
header.UserMinor = m_binaryReader.ReadUInt16 ();
header.SubSysMajor = m_binaryReader.ReadUInt16 ();
header.SubSysMinor = m_binaryReader.ReadUInt16 ();
header.Reserved = m_binaryReader.ReadUInt32 ();
header.ImageSize = m_binaryReader.ReadUInt32 ();
header.HeaderSize = m_binaryReader.ReadUInt32 ();
header.FileChecksum = m_binaryReader.ReadUInt32 ();
header.SubSystem = (SubSystem) m_binaryReader.ReadUInt16 ();
header.DLLFlags = m_binaryReader.ReadUInt16 ();
header.StackReserveSize = ReadIntOrLong ();
header.StackCommitSize = ReadIntOrLong ();
header.HeapReserveSize = ReadIntOrLong ();
header.HeapCommitSize = ReadIntOrLong ();
header.LoaderFlags = m_binaryReader.ReadUInt32 ();
header.NumberOfDataDir = m_binaryReader.ReadUInt32 ();
}
public override void VisitStandardFieldsHeader (PEOptionalHeader.StandardFieldsHeader header)
{
header.Magic = m_binaryReader.ReadUInt16 ();
header.LMajor = m_binaryReader.ReadByte ();
header.LMinor = m_binaryReader.ReadByte ();
header.CodeSize = m_binaryReader.ReadUInt32 ();
header.InitializedDataSize = m_binaryReader.ReadUInt32 ();
header.UninitializedDataSize = m_binaryReader.ReadUInt32 ();
header.EntryPointRVA = ReadRVA ();
header.BaseOfCode = ReadRVA ();
if (!header.IsPE64)
header.BaseOfData = ReadRVA ();
}
public override void VisitDataDirectoriesHeader (PEOptionalHeader.DataDirectoriesHeader header)
{
header.ExportTable = ReadDataDirectory ();
header.ImportTable = ReadDataDirectory ();
header.ResourceTable = ReadDataDirectory ();
header.ExceptionTable = ReadDataDirectory ();
header.CertificateTable = ReadDataDirectory ();
header.BaseRelocationTable = ReadDataDirectory ();
header.Debug = ReadDataDirectory ();
header.Copyright = ReadDataDirectory ();
header.GlobalPtr = ReadDataDirectory ();
header.TLSTable = ReadDataDirectory ();
header.LoadConfigTable = ReadDataDirectory ();
header.BoundImport = ReadDataDirectory ();
header.IAT = ReadDataDirectory ();
header.DelayImportDescriptor = ReadDataDirectory ();
header.CLIHeader = ReadDataDirectory ();
header.Reserved = ReadDataDirectory ();
if (header.CLIHeader != DataDirectory.Zero)
m_image.CLIHeader = new CLIHeader ();
if (header.ExportTable != DataDirectory.Zero)
m_image.ExportTable = new ExportTable ();
}
public override void VisitSectionCollection (SectionCollection coll)
{
for (int i = 0; i < m_image.PEFileHeader.NumberOfSections; i++)
coll.Add (new Section ());
}
public override void VisitSection (Section sect)
{
char [] buffer = new char [8];
int read = 0;
while (read < 8) {
char cur = (char) m_binaryReader.ReadSByte ();
if (cur == '\0') {
m_binaryReader.BaseStream.Position += 8 - read - 1;
break;
}
buffer [read++] = cur;
}
sect.Name = read == 0 ? string.Empty : new string (buffer, 0, read);
if (sect.Name == Section.Text)
m_image.TextSection = sect;
sect.VirtualSize = m_binaryReader.ReadUInt32 ();
sect.VirtualAddress = ReadRVA ();
sect.SizeOfRawData = m_binaryReader.ReadUInt32 ();
sect.PointerToRawData = ReadRVA ();
sect.PointerToRelocations = ReadRVA ();
sect.PointerToLineNumbers = ReadRVA ();
sect.NumberOfRelocations = m_binaryReader.ReadUInt16 ();
sect.NumberOfLineNumbers = m_binaryReader.ReadUInt16 ();
sect.Characteristics = (SectionCharacteristics) m_binaryReader.ReadUInt32 ();
long pos = m_binaryReader.BaseStream.Position;
m_binaryReader.BaseStream.Position = sect.PointerToRawData;
sect.Data = m_binaryReader.ReadBytes ((int) sect.SizeOfRawData);
m_binaryReader.BaseStream.Position = pos;
}
public override void VisitImportAddressTable (ImportAddressTable iat)
{
if (m_image.PEOptionalHeader.DataDirectories.IAT.VirtualAddress == RVA.Zero)
return;
SetPositionToAddress (m_image.PEOptionalHeader.DataDirectories.IAT.VirtualAddress);
iat.HintNameTableRVA = ReadRVA ();
}
public override void VisitCLIHeader (CLIHeader header)
{
if (m_image.PEOptionalHeader.DataDirectories.Debug != DataDirectory.Zero) {
m_image.DebugHeader = new DebugHeader ();
VisitDebugHeader (m_image.DebugHeader);
}
SetPositionToAddress (m_image.PEOptionalHeader.DataDirectories.CLIHeader.VirtualAddress);
header.Cb = m_binaryReader.ReadUInt32 ();
header.MajorRuntimeVersion = m_binaryReader.ReadUInt16 ();
header.MinorRuntimeVersion = m_binaryReader.ReadUInt16 ();
header.Metadata = ReadDataDirectory ();
header.Flags = (RuntimeImage) m_binaryReader.ReadUInt32 ();
header.EntryPointToken = m_binaryReader.ReadUInt32 ();
header.Resources = ReadDataDirectory ();
header.StrongNameSignature = ReadDataDirectory ();
header.CodeManagerTable = ReadDataDirectory ();
header.VTableFixups = ReadDataDirectory ();
header.ExportAddressTableJumps = ReadDataDirectory ();
header.ManagedNativeHeader = ReadDataDirectory ();
if (header.StrongNameSignature != DataDirectory.Zero) {
SetPositionToAddress (header.StrongNameSignature.VirtualAddress);
header.ImageHash = m_binaryReader.ReadBytes ((int) header.StrongNameSignature.Size);
} else
header.ImageHash = new byte [0];
SetPositionToAddress (m_image.CLIHeader.Metadata.VirtualAddress);
m_image.MetadataRoot.Accept (m_mdReader);
}
public override void VisitDebugHeader (DebugHeader header)
{
if (m_image.PEOptionalHeader.DataDirectories.Debug == DataDirectory.Zero)
return;
long pos = m_binaryReader.BaseStream.Position;
SetPositionToAddress (m_image.PEOptionalHeader.DataDirectories.Debug.VirtualAddress);
header.Characteristics = m_binaryReader.ReadUInt32 ();
header.TimeDateStamp = m_binaryReader.ReadUInt32 ();
header.MajorVersion = m_binaryReader.ReadUInt16 ();
header.MinorVersion = m_binaryReader.ReadUInt16 ();
header.Type = (DebugStoreType) m_binaryReader.ReadUInt32 ();
header.SizeOfData = m_binaryReader.ReadUInt32 ();
header.AddressOfRawData = ReadRVA ();
header.PointerToRawData = m_binaryReader.ReadUInt32 ();
m_binaryReader.BaseStream.Position = header.PointerToRawData;
header.Magic = m_binaryReader.ReadUInt32 ();
header.Signature = new Guid (m_binaryReader.ReadBytes (16));
header.Age = m_binaryReader.ReadUInt32 ();
header.FileName = ReadZeroTerminatedString ();
m_binaryReader.BaseStream.Position = pos;
}
string ReadZeroTerminatedString ()
{
StringBuilder sb = new StringBuilder ();
while (true) {
byte chr = m_binaryReader.ReadByte ();
if (chr == 0)
break;
sb.Append ((char) chr);
}
return sb.ToString ();
}
public override void VisitImportTable (ImportTable it)
{
if (m_image.PEOptionalHeader.DataDirectories.ImportTable.VirtualAddress == RVA.Zero)
return;
SetPositionToAddress (m_image.PEOptionalHeader.DataDirectories.ImportTable.VirtualAddress);
it.ImportLookupTable = ReadRVA ();
it.DateTimeStamp = m_binaryReader.ReadUInt32 ();
it.ForwardChain = m_binaryReader.ReadUInt32 ();
it.Name = ReadRVA ();
it.ImportAddressTable = ReadRVA ();
}
public override void VisitImportLookupTable (ImportLookupTable ilt)
{
if (m_image.ImportTable.ImportLookupTable == RVA.Zero)
return;
SetPositionToAddress (m_image.ImportTable.ImportLookupTable);
ilt.HintNameRVA = ReadRVA ();
}
public override void VisitHintNameTable (HintNameTable hnt)
{
if (m_image.ImportAddressTable.HintNameTableRVA == RVA.Zero)
return;
if ((m_image.ImportAddressTable.HintNameTableRVA & 0x80000000) != 0)
return;
SetPositionToAddress (m_image.ImportAddressTable.HintNameTableRVA);
hnt.Hint = m_binaryReader.ReadUInt16 ();
byte [] bytes = m_binaryReader.ReadBytes (11);
hnt.RuntimeMain = Encoding.ASCII.GetString (bytes, 0, bytes.Length);
SetPositionToAddress (m_image.ImportTable.Name);
bytes = m_binaryReader.ReadBytes (11);
hnt.RuntimeLibrary = Encoding.ASCII.GetString (bytes, 0, bytes.Length);
SetPositionToAddress (m_image.PEOptionalHeader.StandardFields.EntryPointRVA);
hnt.EntryPoint = m_binaryReader.ReadUInt16 ();
hnt.RVA = ReadRVA ();
}
public override void VisitExportTable (ExportTable et)
{
SetPositionToAddress (m_image.PEOptionalHeader.DataDirectories.ExportTable.VirtualAddress);
et.Characteristics = m_binaryReader.ReadUInt32 ();
et.TimeDateStamp = m_binaryReader.ReadUInt32 ();
et.MajorVersion = m_binaryReader.ReadUInt16 ();
et.MinorVersion = m_binaryReader.ReadUInt16 ();
//et.Name =
m_binaryReader.ReadUInt32 ();
et.Base = m_binaryReader.ReadUInt32 ();
et.NumberOfFunctions = m_binaryReader.ReadUInt32 ();
et.NumberOfNames = m_binaryReader.ReadUInt32 ();
et.AddressOfFunctions = m_binaryReader.ReadUInt32 ();
et.AddressOfNames = m_binaryReader.ReadUInt32 ();
et.AddressOfNameOrdinals = m_binaryReader.ReadUInt32 ();
et.AddressesOfFunctions = ReadArrayOfRVA (et.AddressOfFunctions, et.NumberOfFunctions);
et.AddressesOfNames = ReadArrayOfRVA (et.AddressOfNames, et.NumberOfNames);
et.NameOrdinals = ReadArrayOfUInt16 (et.AddressOfNameOrdinals, et.NumberOfNames);
et.Names = new string [et.NumberOfFunctions];
for (int i = 0; i < et.NumberOfFunctions; i++) {
if (et.AddressesOfFunctions [i] == 0)
continue;
et.Names [i] = ReadFunctionName (et, i);
}
}
string ReadFunctionName (ExportTable et, int index)
{
for (int i = 0; i < et.NumberOfNames; i++) {
if (et.NameOrdinals [i] != index)
continue;
SetPositionToAddress (et.AddressesOfNames [i]);
return ReadZeroTerminatedString ();
}
return string.Empty;
}
ushort [] ReadArrayOfUInt16 (RVA position, uint length)
{
if (position == RVA.Zero)
return new ushort [0];
SetPositionToAddress (position);
ushort [] array = new ushort [length];
for (int i = 0; i < length; i++)
array [i] = m_binaryReader.ReadUInt16 ();
return array;
}
RVA [] ReadArrayOfRVA (RVA position, uint length)
{
if (position == RVA.Zero)
return new RVA [0];
SetPositionToAddress (position);
RVA [] addresses = new RVA [length];
for (int i = 0; i < length; i++)
addresses [i] = m_binaryReader.ReadUInt32 ();
return addresses;
}
public override void TerminateImage(Image img)
{
m_binaryReader.Close ();
try {
ResourceReader resReader = new ResourceReader (img);
img.ResourceDirectoryRoot = resReader.Read ();
} catch {
img.ResourceDirectoryRoot = null;
}
}
}
}
| |
//
// Copyright (c) 2004-2016 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.Diagnostics;
using System.Linq;
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class BufferingTargetWrapperTests : NLogTestBase
{
[Fact]
public void BufferingTargetWrapperSyncTest1()
{
var myTarget = new MyTarget();
var targetWrapper = new BufferingTargetWrapper
{
WrappedTarget = myTarget,
BufferSize = 10,
};
InitializeTargets(myTarget, targetWrapper);
const int totalEvents = 100;
var continuationHit = new bool[totalEvents];
var lastException = new Exception[totalEvents];
var continuationThread = new Thread[totalEvents];
var hitCount = 0;
CreateContinuationFunc createAsyncContinuation =
eventNumber =>
ex =>
{
lastException[eventNumber] = ex;
continuationThread[eventNumber] = Thread.CurrentThread;
continuationHit[eventNumber] = true;
Interlocked.Increment(ref hitCount);
};
// write 9 events - they will all be buffered and no final continuation will be reached
var eventCounter = 0;
for (var i = 0; i < 9; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
Assert.Equal(0, hitCount);
Assert.Equal(0, myTarget.WriteCount);
// write one more event - everything will be flushed
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
Assert.Equal(10, hitCount);
Assert.Equal(1, myTarget.BufferedWriteCount);
Assert.Equal(10, myTarget.BufferedTotalEvents);
Assert.Equal(10, myTarget.WriteCount);
for (var i = 0; i < hitCount; ++i)
{
Assert.Same(Thread.CurrentThread, continuationThread[i]);
Assert.Null(lastException[i]);
}
// write 9 more events - they will all be buffered and no final continuation will be reached
for (var i = 0; i < 9; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
// no change
Assert.Equal(10, hitCount);
Assert.Equal(1, myTarget.BufferedWriteCount);
Assert.Equal(10, myTarget.BufferedTotalEvents);
Assert.Equal(10, myTarget.WriteCount);
Exception flushException = null;
var flushHit = new ManualResetEvent(false);
targetWrapper.Flush(
ex =>
{
flushException = ex;
flushHit.Set();
});
Thread.Sleep(1000);
flushHit.WaitOne();
Assert.Null(flushException);
// make sure remaining events were written
Assert.Equal(19, hitCount);
Assert.Equal(2, myTarget.BufferedWriteCount);
Assert.Equal(19, myTarget.BufferedTotalEvents);
Assert.Equal(19, myTarget.WriteCount);
Assert.Equal(1, myTarget.FlushCount);
// flushes happen on the same thread
for (var i = 10; i < hitCount; ++i)
{
Assert.NotNull(continuationThread[i]);
Assert.Same(Thread.CurrentThread, continuationThread[i]);
Assert.Null(lastException[i]);
}
// flush again - should just invoke Flush() on the wrapped target
flushHit.Reset();
targetWrapper.Flush(
ex =>
{
flushException = ex;
flushHit.Set();
});
flushHit.WaitOne();
Assert.Equal(19, hitCount);
Assert.Equal(2, myTarget.BufferedWriteCount);
Assert.Equal(19, myTarget.BufferedTotalEvents);
Assert.Equal(19, myTarget.WriteCount);
Assert.Equal(2, myTarget.FlushCount);
targetWrapper.Close();
myTarget.Close();
}
[Fact]
public void BufferingTargetWithFallbackGroupAndFirstTargetFails_Write_SecondTargetWritesEvents()
{
var myTarget = new MyTarget { FailCounter = 1 };
var myTarget2 = new MyTarget();
var fallbackGroup = new FallbackGroupTarget(myTarget, myTarget2);
var targetWrapper = new BufferingTargetWrapper
{
WrappedTarget = fallbackGroup,
BufferSize = 10,
};
InitializeTargets(myTarget, targetWrapper, myTarget2, fallbackGroup);
const int totalEvents = 100;
var continuationHit = new bool[totalEvents];
var lastException = new Exception[totalEvents];
var continuationThread = new Thread[totalEvents];
CreateContinuationFunc createAsyncContinuation =
eventNumber =>
ex =>
{
lastException[eventNumber] = ex;
continuationThread[eventNumber] = Thread.CurrentThread;
continuationHit[eventNumber] = true;
};
// write 9 events - they will all be buffered and no final continuation will be reached
var eventCounter = 0;
for (var i = 0; i < 9; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
Assert.Equal(0, myTarget.WriteCount);
// write one more event - everything will be flushed
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
Assert.Equal(1, myTarget.WriteCount);
Assert.Equal(10, myTarget2.WriteCount);
targetWrapper.Close();
myTarget.Close();
}
[Fact]
public void BufferingTargetWrapperSyncWithTimedFlushTest()
{
var myTarget = new MyTarget();
var targetWrapper = new BufferingTargetWrapper
{
WrappedTarget = myTarget,
BufferSize = 10,
FlushTimeout = 1000,
};
InitializeTargets(myTarget, targetWrapper);
const int totalEvents = 100;
var continuationHit = new bool[totalEvents];
var lastException = new Exception[totalEvents];
var continuationThread = new Thread[totalEvents];
var hitCount = 0;
CreateContinuationFunc createAsyncContinuation =
eventNumber =>
ex =>
{
lastException[eventNumber] = ex;
continuationThread[eventNumber] = Thread.CurrentThread;
continuationHit[eventNumber] = true;
Interlocked.Increment(ref hitCount);
};
// write 9 events - they will all be buffered and no final continuation will be reached
var eventCounter = 0;
for (var i = 0; i < 9; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
Assert.Equal(0, hitCount);
Assert.Equal(0, myTarget.WriteCount);
// sleep 2 seconds, this will trigger the timer and flush all events
Thread.Sleep(1500);
Assert.Equal(9, hitCount);
Assert.Equal(1, myTarget.BufferedWriteCount);
Assert.Equal(9, myTarget.BufferedTotalEvents);
Assert.Equal(9, myTarget.WriteCount);
for (var i = 0; i < hitCount; ++i)
{
Assert.NotSame(Thread.CurrentThread, continuationThread[i]);
Assert.Null(lastException[i]);
}
// write 11 more events, 10 will be hit immediately because the buffer will fill up
// 1 will be pending
for (var i = 0; i < 11; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
Assert.Equal(19, hitCount);
Assert.Equal(2, myTarget.BufferedWriteCount);
Assert.Equal(19, myTarget.BufferedTotalEvents);
Assert.Equal(19, myTarget.WriteCount);
// sleep 2 seconds and the last remaining one will be flushed
Thread.Sleep(1500);
Assert.Equal(20, hitCount);
Assert.Equal(3, myTarget.BufferedWriteCount);
Assert.Equal(20, myTarget.BufferedTotalEvents);
Assert.Equal(20, myTarget.WriteCount);
}
[Fact]
public void BufferingTargetWrapperAsyncTest1()
{
var myTarget = new MyAsyncTarget();
var targetWrapper = new BufferingTargetWrapper
{
WrappedTarget = myTarget,
BufferSize = 10,
};
InitializeTargets(myTarget, targetWrapper);
const int totalEvents = 100;
var continuationHit = new bool[totalEvents];
var lastException = new Exception[totalEvents];
var continuationThread = new Thread[totalEvents];
var hitCount = 0;
CreateContinuationFunc createAsyncContinuation =
eventNumber =>
ex =>
{
lastException[eventNumber] = ex;
continuationThread[eventNumber] = Thread.CurrentThread;
continuationHit[eventNumber] = true;
Interlocked.Increment(ref hitCount);
};
// write 9 events - they will all be buffered and no final continuation will be reached
var eventCounter = 0;
for (var i = 0; i < 9; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
Assert.Equal(0, hitCount);
// write one more event - everything will be flushed
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
while (hitCount < 10)
{
Thread.Sleep(10);
}
Assert.Equal(10, hitCount);
Assert.Equal(1, myTarget.BufferedWriteCount);
Assert.Equal(10, myTarget.BufferedTotalEvents);
for (var i = 0; i < hitCount; ++i)
{
Assert.NotSame(Thread.CurrentThread, continuationThread[i]);
Assert.Null(lastException[i]);
}
// write 9 more events - they will all be buffered and no final continuation will be reached
for (var i = 0; i < 9; ++i)
{
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
}
// no change
Assert.Equal(10, hitCount);
Assert.Equal(1, myTarget.BufferedWriteCount);
Assert.Equal(10, myTarget.BufferedTotalEvents);
Exception flushException = null;
var flushHit = new ManualResetEvent(false);
targetWrapper.Flush(
ex =>
{
flushException = ex;
flushHit.Set();
});
flushHit.WaitOne();
Assert.Null(flushException);
// make sure remaining events were written
Assert.Equal(19, hitCount);
Assert.Equal(2, myTarget.BufferedWriteCount);
Assert.Equal(19, myTarget.BufferedTotalEvents);
// flushes happen on another thread
for (var i = 10; i < hitCount; ++i)
{
Assert.NotNull(continuationThread[i]);
Assert.NotSame(Thread.CurrentThread, continuationThread[i]);
Assert.Null(lastException[i]);
}
// flush again - should not do anything
flushHit.Reset();
targetWrapper.Flush(
ex =>
{
flushException = ex;
flushHit.Set();
});
flushHit.WaitOne();
Assert.Equal(19, hitCount);
Assert.Equal(2, myTarget.BufferedWriteCount);
Assert.Equal(19, myTarget.BufferedTotalEvents);
targetWrapper.Close();
myTarget.Close();
}
[Fact]
public void BufferingTargetWrapperSyncWithTimedFlushNonSlidingTest()
{
var myTarget = new MyTarget();
var targetWrapper = new BufferingTargetWrapper
{
WrappedTarget = myTarget,
BufferSize = 10,
FlushTimeout = 400,
SlidingTimeout = false,
};
InitializeTargets(myTarget, targetWrapper);
const int totalEvents = 100;
var continuationHit = new bool[totalEvents];
var lastException = new Exception[totalEvents];
var continuationThread = new Thread[totalEvents];
var hitCount = 0;
var resetEvent = new ManualResetEvent(false);
CreateContinuationFunc createAsyncContinuation =
eventNumber =>
ex =>
{
lastException[eventNumber] = ex;
continuationThread[eventNumber] = Thread.CurrentThread;
continuationHit[eventNumber] = true;
Interlocked.Increment(ref hitCount);
if (eventNumber > 0)
{
resetEvent.Set();
}
};
var eventCounter = 0;
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
Assert.Equal(0, hitCount);
Assert.Equal(0, myTarget.WriteCount);
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
Assert.True(resetEvent.WaitOne(5000));
Assert.Equal(2, hitCount);
Assert.Equal(2, myTarget.WriteCount);
}
[Fact]
public void BufferingTargetWrapperSyncWithTimedFlushSlidingTest()
{
var myTarget = new MyTarget();
var targetWrapper = new BufferingTargetWrapper
{
WrappedTarget = myTarget,
BufferSize = 10,
FlushTimeout = 400,
};
InitializeTargets(myTarget, targetWrapper);
const int totalEvents = 100;
var continuationHit = new bool[totalEvents];
var lastException = new Exception[totalEvents];
var continuationThread = new Thread[totalEvents];
var hitCount = 0;
CreateContinuationFunc createAsyncContinuation =
eventNumber =>
ex =>
{
lastException[eventNumber] = ex;
continuationThread[eventNumber] = Thread.CurrentThread;
continuationHit[eventNumber] = true;
Interlocked.Increment(ref hitCount);
};
var eventCounter = 0;
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
Thread.Sleep(100);
Assert.Equal(0, hitCount);
Assert.Equal(0, myTarget.WriteCount);
targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
Thread.Sleep(100);
Assert.Equal(0, hitCount);
Assert.Equal(0, myTarget.WriteCount);
Thread.Sleep(600);
Assert.Equal(2, hitCount);
Assert.Equal(2, myTarget.WriteCount);
}
[Fact]
public void WhenWrappedTargetThrowsExceptionThisIsHandled()
{
var myTarget = new MyTarget { ThrowException = true };
var bufferingTargetWrapper = new BufferingTargetWrapper
{
WrappedTarget = myTarget,
FlushTimeout = -1
};
InitializeTargets(myTarget, bufferingTargetWrapper);
bufferingTargetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(_ => { }));
var flushHit = new ManualResetEvent(false);
bufferingTargetWrapper.Flush(ex => flushHit.Set());
flushHit.WaitOne();
Assert.Equal(1, myTarget.FlushCount);
}
private static void InitializeTargets(params Target[] targets)
{
foreach (var target in targets)
{
target.Initialize(null);
}
}
private class MyAsyncTarget : Target
{
public int BufferedWriteCount { get; private set; }
public int BufferedTotalEvents { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
throw new NotSupportedException();
}
protected override void Write(AsyncLogEventInfo[] logEvents)
{
this.Write(new ArraySegment<AsyncLogEventInfo>(logEvents));
}
protected override void Write(ArraySegment<AsyncLogEventInfo> logEvents)
{
this.BufferedWriteCount++;
this.BufferedTotalEvents += logEvents.Count;
for(int x=0;x<logEvents.Count;x++)
{
var evt = logEvents.Array[x];
var @event = evt;
ThreadPool.QueueUserWorkItem(
s =>
{
if (this.ThrowExceptions)
{
@event.Continuation(new InvalidOperationException("Some problem!"));
@event.Continuation(new InvalidOperationException("Some problem!"));
}
else
{
@event.Continuation(null);
@event.Continuation(null);
}
});
}
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
ThreadPool.QueueUserWorkItem(
s => asyncContinuation(null));
}
public bool ThrowExceptions { get; set; }
}
private class MyTarget : Target
{
public int FlushCount { get; private set; }
public int WriteCount { get; private set; }
public int BufferedWriteCount { get; private set; }
public int BufferedTotalEvents { get; private set; }
public bool ThrowException { get; set; }
public int FailCounter { get; set; }
protected override void Write(AsyncLogEventInfo[] logEvents)
{
this.BufferedWriteCount++;
this.BufferedTotalEvents += logEvents.Length;
base.Write(logEvents);
}
protected override void Write(ArraySegment<AsyncLogEventInfo> logEvents)
{
this.BufferedWriteCount++;
this.BufferedTotalEvents += logEvents.Count;
base.Write(logEvents);
}
protected override void Write(LogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
this.WriteCount++;
if (ThrowException)
{
throw new Exception("Target exception");
}
if (this.FailCounter > 0)
{
this.FailCounter--;
throw new InvalidOperationException("Some failure.");
}
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
this.FlushCount++;
asyncContinuation(null);
}
}
private delegate AsyncContinuation CreateContinuationFunc(int eventNumber);
}
}
| |
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using Should;
using NUnit.Framework;
namespace AutoMapper.UnitTests
{
[TestFixture]
public class DelegateFactoryTests
{
[Test]
public void MethodTests()
{
MethodInfo method = typeof(String).GetMethod("StartsWith", new[] { typeof(string) });
LateBoundMethod callback = DelegateFactory.CreateGet(method);
string foo = "this is a test";
bool result = (bool)callback(foo, new[] { "this" });
result.ShouldBeTrue();
}
[Test]
public void PropertyTests()
{
PropertyInfo property = typeof(Source).GetProperty("Value", typeof(int));
LateBoundPropertyGet callback = DelegateFactory.CreateGet(property);
var source = new Source {Value = 5};
int result = (int)callback(source);
result.ShouldEqual(5);
}
[Test]
public void FieldTests()
{
FieldInfo field = typeof(Source).GetField("Value2");
LateBoundFieldGet callback = DelegateFactory.CreateGet(field);
var source = new Source {Value2 = 15};
int result = (int)callback(source);
result.ShouldEqual(15);
}
[Test]
public void Should_set_field_when_field_is_a_value_type()
{
var sourceType = typeof (Source);
FieldInfo field = sourceType.GetField("Value2");
LateBoundFieldSet callback = DelegateFactory.CreateSet(field);
var source = new Source();
callback(source, 5);
source.Value2.ShouldEqual(5);
}
[Test]
public void Should_set_field_when_field_is_a_reference_type()
{
var sourceType = typeof (Source);
FieldInfo field = sourceType.GetField("Value3");
LateBoundFieldSet callback = DelegateFactory.CreateSet(field);
var source = new Source();
callback(source, "hello");
source.Value3.ShouldEqual("hello");
}
[Test]
public void Should_set_property_when_property_is_a_value_type()
{
var sourceType = typeof (Source);
PropertyInfo property = sourceType.GetProperty("Value");
LateBoundPropertySet callback = DelegateFactory.CreateSet(property);
var source = new Source();
callback(source, 5);
source.Value.ShouldEqual(5);
}
[Test]
public void Should_set_property_when_property_is_a_value_type_and_type_is_interface()
{
var sourceType = typeof (ISource);
PropertyInfo property = sourceType.GetProperty("Value");
LateBoundPropertySet callback = DelegateFactory.CreateSet(property);
var source = new Source();
callback(source, 5);
source.Value.ShouldEqual(5);
}
[Test]
public void Should_set_property_when_property_is_a_reference_type()
{
var sourceType = typeof(Source);
PropertyInfo property = sourceType.GetProperty("Value4");
LateBoundPropertySet callback = DelegateFactory.CreateSet(property);
var source = new Source();
callback(source, "hello");
source.Value4.ShouldEqual("hello");
}
internal delegate void DoIt3(ref ValueSource source, string value);
private void SetValue(object thing, object value)
{
var source = ((ValueSource) thing);
source.Value = (string)value;
}
[Test, Explicit]
public void WhatIWantToDo()
{
var sourceType = typeof(Source);
var property = sourceType.GetProperty("Value");
var setter = property.GetSetMethod();
var method = new DynamicMethod("GetValue", null, new[] { typeof(object), typeof(object) }, sourceType);
var gen = method.GetILGenerator();
//gen.Emit(OpCodes.Ldarg_0); // Load input to stack
//gen.Emit(OpCodes.Ldarg_1); // Load value to stack
//gen.Emit(OpCodes.Stfld, field); // Set the value to the input field
//gen.Emit(OpCodes.Ret);
gen.Emit(OpCodes.Ldarg_0); // Load input to stack
gen.Emit(OpCodes.Castclass, sourceType); // Cast to source type
gen.Emit(OpCodes.Ldarg_1); // Load value to stack
gen.Emit(OpCodes.Unbox_Any, property.PropertyType); // Unbox the value to its proper value type
gen.Emit(OpCodes.Callvirt, property.GetSetMethod()); // Set the value to the input field
gen.Emit(OpCodes.Ret);
var result = (LateBoundPropertySet)method.CreateDelegate(typeof(LateBoundPropertySet));
var source = new Source();
DateTime start = DateTime.Now;
for (int i = 0; i < 1000000; i++)
{
source.Value = 5;
}
var span = DateTime.Now - start;
Console.WriteLine("Raw:" + span.Ticks);
start = DateTime.Now;
for (int i = 0; i < 1000000; i++)
{
setter.Invoke(source, new object[] { 5 });
}
span = DateTime.Now - start;
Console.WriteLine("MethodInfo:" + span.Ticks);
start = DateTime.Now;
for (int i = 0; i < 1000000; i++)
{
result(source, 5);
}
span = DateTime.Now - start;
Console.WriteLine("LCG:" + span.Ticks);
}
[Test, Explicit]
public void Test_with_DynamicMethod2()
{
var sourceType = typeof(DelegateFactoryTests);
MethodInfo property = sourceType.GetMethod("SetValue2", BindingFlags.Static | BindingFlags.NonPublic);
var d = (LateBoundValueTypePropertySet)Delegate.CreateDelegate(typeof(LateBoundValueTypePropertySet), property);
object othersource = new ValueSource();
DoIt4(othersource, "Asdf");
var source = new ValueSource();
var value = (object) source;
d(ref value, "hello");
source.Value.ShouldEqual("hello");
}
[Test, Explicit]
public void Test_with_CreateDelegate()
{
var sourceType = typeof(ValueSource);
PropertyInfo property = sourceType.GetProperty("Value");
LateBoundValueTypePropertySet callback = DelegateFactory.CreateValueTypeSet(property);
var source = new ValueSource();
var target = ((object)source);
callback(ref target, "hello");
source.Value.ShouldEqual("hello");
}
[Test]
public void Test_with_create_ctor()
{
var sourceType = typeof(Source);
LateBoundCtor ctor = DelegateFactory.CreateCtor(sourceType);
var target = ctor();
target.ShouldBeType<Source>();
}
[Test]
public void Test_with_value_object_create_ctor()
{
var sourceType = typeof(ValueSource);
LateBoundCtor ctor = DelegateFactory.CreateCtor(sourceType);
var target = ctor();
target.ShouldBeType<ValueSource>();
}
public object CreateValueSource()
{
return new ValueSource();
}
#if !SILVERLIGHT
[Test, Explicit]
public void Test_with_DynamicMethod()
{
var sourceType = typeof(ValueSource);
PropertyInfo property = sourceType.GetProperty("Value");
var setter = property.GetSetMethod(true);
var method = new DynamicMethod("Set" + property.Name, null, new[] { typeof(object).MakeByRefType(), typeof(object) }, false);
var gen = method.GetILGenerator();
method.InitLocals = true;
gen.Emit(OpCodes.Ldarg_0); // Load input to stack
gen.Emit(OpCodes.Ldind_Ref);
gen.Emit(OpCodes.Unbox_Any, sourceType); // Unbox the source to its correct type
gen.Emit(OpCodes.Stloc_0); // Store the unboxed input on the stack
gen.Emit(OpCodes.Ldloca_S, 0);
gen.Emit(OpCodes.Ldarg_1); // Load value to stack
gen.Emit(OpCodes.Castclass, property.PropertyType); // Unbox the value to its proper value type
gen.Emit(OpCodes.Call, setter); // Call the setter method
gen.Emit(OpCodes.Ret);
var result = (LateBoundValueTypePropertySet)method.CreateDelegate(typeof(LateBoundValueTypePropertySet));
var source = new ValueSource();
var value = (object) source;
result(ref value, "hello");
source.Value.ShouldEqual("hello");
}
#endif
public delegate void SetValueDelegate(ref ValueSource source, string value);
private static void SetValue2(ref object thing, object value)
{
var source = ((ValueSource)thing);
source.Value = (string)value;
thing = source;
}
private void SetValue(ref ValueSource thing, string value)
{
thing.Value = value;
}
private void DoIt(object source, object value)
{
((Source)source).Value2 = (int)value;
}
private void DoIt4(object source, object value)
{
var valueSource = ((ValueSource)source);
valueSource.Value = (string)value;
}
private void DoIt2(object source, object value)
{
int toSet = value == null ? default(int) : (int) value;
((Source)source).Value = toSet;
}
private void DoIt4(ref object source, object value)
{
var valueSource = (ValueSource) source;
valueSource.Value = (string) value;
}
private static class Test<T>
{
private static T DoIt()
{
return default(T);
}
}
public struct ValueSource
{
public string Value { get; set; }
}
public interface ISource
{
int Value { get; set; }
}
public class Source : ISource
{
public int Value { get; set; }
public int Value2;
public string Value3;
public string Value4 { get; set; }
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.Extensions.GetReplicaInfoResponse.cs
//
// Author:
// Sunil Kumar ([email protected])
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using Novell.Directory.Ldap;
using Novell.Directory.Ldap.Asn1;
using Novell.Directory.Ldap.Utilclass;
using Novell.Directory.Ldap.Rfc2251;
namespace Novell.Directory.Ldap.Extensions
{
/// <summary> Retrieves the replica information from a GetReplicaInfoResponse object.
///
/// An object in this class is generated from an ExtendedResponse using the
/// ExtendedResponseFactory class.
///
/// The getReplicaInfoResponse extension uses the following OID:
/// 2.16.840.1.113719.1.27.100.18
///
/// </summary>
public class GetReplicaInfoResponse:LdapExtendedResponse
{
// Other info as returned by the server
private int partitionID;
private int replicaState;
private int modificationTime;
private int purgeTime;
private int localPartitionID;
private System.String partitionDN;
private int replicaType;
private int flags;
/// <summary> Constructs an object from the responseValue which contains the
/// replica information.
///
/// The constructor parses the responseValue which has the following
/// format:
/// responseValue ::=
/// partitionID INTEGER
/// replicaState INTEGER
/// modificationTime INTEGER
/// purgeTime INTEGER
/// localPartitionID INTEGER
/// partitionDN OCTET STRING
/// replicaType INTEGER
/// flags INTEGER
///
/// </summary>
/// <exception> IOException The response value could not be decoded.
/// </exception>
public GetReplicaInfoResponse(RfcLdapMessage rfcMessage):base(rfcMessage)
{
if (ResultCode == LdapException.SUCCESS)
{
// parse the contents of the reply
sbyte[] returnedValue = this.Value;
if (returnedValue == null)
throw new System.IO.IOException("No returned value");
// Create a decoder object
LBERDecoder decoder = new LBERDecoder();
if (decoder == null)
throw new System.IO.IOException("Decoding error");
// Parse the parameters in the order
System.IO.MemoryStream currentPtr = new System.IO.MemoryStream(SupportClass.ToByteArray(returnedValue));
// Parse partitionID
Asn1Integer asn1_partitionID = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_partitionID == null)
throw new System.IO.IOException("Decoding error");
partitionID = asn1_partitionID.intValue();
// Parse replicaState
Asn1Integer asn1_replicaState = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_replicaState == null)
throw new System.IO.IOException("Decoding error");
replicaState = asn1_replicaState.intValue();
// Parse modificationTime
Asn1Integer asn1_modificationTime = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_modificationTime == null)
throw new System.IO.IOException("Decoding error");
modificationTime = asn1_modificationTime.intValue();
// Parse purgeTime
Asn1Integer asn1_purgeTime = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_purgeTime == null)
throw new System.IO.IOException("Decoding error");
purgeTime = asn1_purgeTime.intValue();
// Parse localPartitionID
Asn1Integer asn1_localPartitionID = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_localPartitionID == null)
throw new System.IO.IOException("Decoding error");
localPartitionID = asn1_localPartitionID.intValue();
// Parse partitionDN
Asn1OctetString asn1_partitionDN = (Asn1OctetString) decoder.decode(currentPtr);
if (asn1_partitionDN == null)
throw new System.IO.IOException("Decoding error");
partitionDN = asn1_partitionDN.stringValue();
if ((System.Object) partitionDN == null)
throw new System.IO.IOException("Decoding error");
// Parse replicaType
Asn1Integer asn1_replicaType = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_replicaType == null)
throw new System.IO.IOException("Decoding error");
replicaType = asn1_replicaType.intValue();
// Parse flags
Asn1Integer asn1_flags = (Asn1Integer) decoder.decode(currentPtr);
if (asn1_flags == null)
throw new System.IO.IOException("Decoding error");
flags = asn1_flags.intValue();
}
else
{
partitionID = 0;
replicaState = 0;
modificationTime = 0;
purgeTime = 0;
localPartitionID = 0;
partitionDN = "";
replicaType = 0;
flags = 0;
}
}
/// <summary> Returns the numeric identifier for the partition.
///
/// </summary>
/// <returns> Integer value specifying the partition ID.
/// </returns>
public virtual int getpartitionID()
{
return partitionID;
}
/// <summary> Returns the current state of the replica.
///
/// </summary>
/// <returns> Integer value specifying the current state of the replica. See
/// ReplicationConstants class for possible values for this field.
///
/// </returns>
/// <seealso cref="ReplicationConstants.Ldap_RS_BEGIN_ADD">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_DEAD_REPLICA">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_DYING_REPLICA">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_JS_0">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_JS_1">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_JS_2">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_LOCKED">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_MASTER_DONE">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_MASTER_START">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_SS_0">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RS_TRANSITION_ON">
/// </seealso>
public virtual int getreplicaState()
{
return replicaState;
}
/// <summary> Returns the time of the most recent modification.
///
/// </summary>
/// <returns> Integer value specifying the last modification time.
/// </returns>
public virtual int getmodificationTime()
{
return modificationTime;
}
/// <summary> Returns the most recent time in which all data has been synchronized.
///
/// </summary>
/// <returns> Integer value specifying the last purge time.
/// </returns>
public virtual int getpurgeTime()
{
return purgeTime;
}
/// <summary> Returns the local numeric identifier for the replica.
///
/// </summary>
/// <returns> Integer value specifying the local ID of the partition.
/// </returns>
public virtual int getlocalPartitionID()
{
return localPartitionID;
}
/// <summary> Returns the distinguished name of the partition.
///
/// </summary>
/// <returns> String value specifying the name of the partition read.
/// </returns>
public virtual System.String getpartitionDN()
{
return partitionDN;
}
/// <summary> Returns the replica type.
///
/// See the ReplicationConstants class for possible values for
/// this field.
///
/// </summary>
/// <returns> Integer identifying the type of the replica.
///
/// </returns>
/// <seealso cref="ReplicationConstants.Ldap_RT_MASTER">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RT_SECONDARY">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RT_READONLY">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RT_SUBREF">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RT_SPARSE_WRITE">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_RT_SPARSE_READ">
/// </seealso>
public virtual int getreplicaType()
{
return replicaType;
}
/// <summary> Returns flags that specify whether the replica is busy or is a boundary.
///
/// See the ReplicationConstants class for possible values for
/// this field.
///
/// </summary>
/// <returns> Integer value specifying the flags for the replica.
///
/// </returns>
/// <seealso cref="ReplicationConstants.Ldap_DS_FLAG_BUSY">
/// </seealso>
/// <seealso cref="ReplicationConstants.Ldap_DS_FLAG_BOUNDARY">
/// </seealso>
public virtual int getflags()
{
return flags;
}
}
}
| |
// 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 Microsoft.Win32;
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Xml;
namespace System.Security.Cryptography.Xml
{
internal class Utils
{
// The maximum number of characters in an XML document (0 means no limit).
internal const int MaxCharactersInDocument = 0;
// The entity expansion limit. This is used to prevent entity expansion denial of service attacks.
internal const long MaxCharactersFromEntities = (long)1e7;
// The default XML Dsig recursion limit.
// This should be within limits of real world scenarios.
// Keeping this number low will preserve some stack space
internal const int XmlDsigSearchDepth = 20;
private Utils() { }
private static bool HasNamespace(XmlElement element, string prefix, string value)
{
if (IsCommittedNamespace(element, prefix, value)) return true;
if (element.Prefix == prefix && element.NamespaceURI == value) return true;
return false;
}
// A helper function that determines if a namespace node is a committed attribute
internal static bool IsCommittedNamespace(XmlElement element, string prefix, string value)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
string name = ((prefix.Length > 0) ? "xmlns:" + prefix : "xmlns");
if (element.HasAttribute(name) && element.GetAttribute(name) == value) return true;
return false;
}
internal static bool IsRedundantNamespace(XmlElement element, string prefix, string value)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
XmlNode ancestorNode = ((XmlNode)element).ParentNode;
while (ancestorNode != null)
{
XmlElement ancestorElement = ancestorNode as XmlElement;
if (ancestorElement != null)
if (HasNamespace(ancestorElement, prefix, value)) return true;
ancestorNode = ancestorNode.ParentNode;
}
return false;
}
internal static string GetAttribute(XmlElement element, string localName, string namespaceURI)
{
string s = (element.HasAttribute(localName) ? element.GetAttribute(localName) : null);
if (s == null && element.HasAttribute(localName, namespaceURI))
s = element.GetAttribute(localName, namespaceURI);
return s;
}
internal static bool HasAttribute(XmlElement element, string localName, string namespaceURI)
{
return element.HasAttribute(localName) || element.HasAttribute(localName, namespaceURI);
}
internal static bool VerifyAttributes(XmlElement element, string expectedAttrName)
{
return VerifyAttributes(element, expectedAttrName == null ? null : new string[] { expectedAttrName });
}
internal static bool VerifyAttributes(XmlElement element, string[] expectedAttrNames)
{
foreach (XmlAttribute attr in element.Attributes)
{
// There are a few Xml Special Attributes that are always allowed on any node. Make sure we allow those here.
bool attrIsAllowed = attr.Name == "xmlns" || attr.Name.StartsWith("xmlns:") || attr.Name == "xml:space" || attr.Name == "xml:lang" || attr.Name == "xml:base";
int expectedInd = 0;
while (!attrIsAllowed && expectedAttrNames != null && expectedInd < expectedAttrNames.Length)
{
attrIsAllowed = attr.Name == expectedAttrNames[expectedInd];
expectedInd++;
}
if (!attrIsAllowed)
return false;
}
return true;
}
internal static bool IsNamespaceNode(XmlNode n)
{
return n.NodeType == XmlNodeType.Attribute && (n.Prefix.Equals("xmlns") || (n.Prefix.Length == 0 && n.LocalName.Equals("xmlns")));
}
internal static bool IsXmlNamespaceNode(XmlNode n)
{
return n.NodeType == XmlNodeType.Attribute && n.Prefix.Equals("xml");
}
// We consider xml:space style attributes as default namespace nodes since they obey the same propagation rules
internal static bool IsDefaultNamespaceNode(XmlNode n)
{
bool b1 = n.NodeType == XmlNodeType.Attribute && n.Prefix.Length == 0 && n.LocalName.Equals("xmlns");
bool b2 = IsXmlNamespaceNode(n);
return b1 || b2;
}
internal static bool IsEmptyDefaultNamespaceNode(XmlNode n)
{
return IsDefaultNamespaceNode(n) && n.Value.Length == 0;
}
internal static string GetNamespacePrefix(XmlAttribute a)
{
Debug.Assert(IsNamespaceNode(a) || IsXmlNamespaceNode(a));
return a.Prefix.Length == 0 ? string.Empty : a.LocalName;
}
internal static bool HasNamespacePrefix(XmlAttribute a, string nsPrefix)
{
return GetNamespacePrefix(a).Equals(nsPrefix);
}
internal static bool IsNonRedundantNamespaceDecl(XmlAttribute a, XmlAttribute nearestAncestorWithSamePrefix)
{
if (nearestAncestorWithSamePrefix == null)
return !IsEmptyDefaultNamespaceNode(a);
else
return !nearestAncestorWithSamePrefix.Value.Equals(a.Value);
}
internal static bool IsXmlPrefixDefinitionNode(XmlAttribute a)
{
return false;
// return a.Prefix.Equals("xmlns") && a.LocalName.Equals("xml") && a.Value.Equals(NamespaceUrlForXmlPrefix);
}
internal static string DiscardWhiteSpaces(string inputBuffer)
{
return DiscardWhiteSpaces(inputBuffer, 0, inputBuffer.Length);
}
internal static string DiscardWhiteSpaces(string inputBuffer, int inputOffset, int inputCount)
{
int i, iCount = 0;
for (i = 0; i < inputCount; i++)
if (char.IsWhiteSpace(inputBuffer[inputOffset + i])) iCount++;
char[] rgbOut = new char[inputCount - iCount];
iCount = 0;
for (i = 0; i < inputCount; i++)
if (!char.IsWhiteSpace(inputBuffer[inputOffset + i]))
{
rgbOut[iCount++] = inputBuffer[inputOffset + i];
}
return new string(rgbOut);
}
internal static void SBReplaceCharWithString(StringBuilder sb, char oldChar, string newString)
{
int i = 0;
int newStringLength = newString.Length;
while (i < sb.Length)
{
if (sb[i] == oldChar)
{
sb.Remove(i, 1);
sb.Insert(i, newString);
i += newStringLength;
}
else i++;
}
}
internal static XmlReader PreProcessStreamInput(Stream inputStream, XmlResolver xmlResolver, string baseUri)
{
XmlReaderSettings settings = GetSecureXmlReaderSettings(xmlResolver);
XmlReader reader = XmlReader.Create(inputStream, settings, baseUri);
return reader;
}
internal static XmlReaderSettings GetSecureXmlReaderSettings(XmlResolver xmlResolver)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = xmlResolver;
settings.DtdProcessing = DtdProcessing.Parse;
settings.MaxCharactersFromEntities = MaxCharactersFromEntities;
settings.MaxCharactersInDocument = MaxCharactersInDocument;
return settings;
}
internal static XmlDocument PreProcessDocumentInput(XmlDocument document, XmlResolver xmlResolver, string baseUri)
{
if (document == null)
throw new ArgumentNullException(nameof(document));
MyXmlDocument doc = new MyXmlDocument();
doc.PreserveWhitespace = document.PreserveWhitespace;
// Normalize the document
using (TextReader stringReader = new StringReader(document.OuterXml))
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = xmlResolver;
settings.DtdProcessing = DtdProcessing.Parse;
settings.MaxCharactersFromEntities = MaxCharactersFromEntities;
settings.MaxCharactersInDocument = MaxCharactersInDocument;
XmlReader reader = XmlReader.Create(stringReader, settings, baseUri);
doc.Load(reader);
}
return doc;
}
internal static XmlDocument PreProcessElementInput(XmlElement elem, XmlResolver xmlResolver, string baseUri)
{
if (elem == null)
throw new ArgumentNullException(nameof(elem));
MyXmlDocument doc = new MyXmlDocument();
doc.PreserveWhitespace = true;
// Normalize the document
using (TextReader stringReader = new StringReader(elem.OuterXml))
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = xmlResolver;
settings.DtdProcessing = DtdProcessing.Parse;
settings.MaxCharactersFromEntities = MaxCharactersFromEntities;
settings.MaxCharactersInDocument = MaxCharactersInDocument;
XmlReader reader = XmlReader.Create(stringReader, settings, baseUri);
doc.Load(reader);
}
return doc;
}
internal static XmlDocument DiscardComments(XmlDocument document)
{
XmlNodeList nodeList = document.SelectNodes("//comment()");
if (nodeList != null)
{
foreach (XmlNode node1 in nodeList)
{
node1.ParentNode.RemoveChild(node1);
}
}
return document;
}
internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComments)
{
CanonicalXmlNodeList nodeList = new CanonicalXmlNodeList();
CanonicalXmlNodeList elementList = new CanonicalXmlNodeList();
CanonicalXmlNodeList attribList = new CanonicalXmlNodeList();
CanonicalXmlNodeList namespaceList = new CanonicalXmlNodeList();
int index = 0;
elementList.Add(node);
do
{
XmlNode rootNode = (XmlNode)elementList[index];
// Add the children nodes
XmlNodeList childNodes = rootNode.ChildNodes;
if (childNodes != null)
{
foreach (XmlNode node1 in childNodes)
{
if (includeComments || (!(node1 is XmlComment)))
{
elementList.Add(node1);
}
}
}
// Add the attribute nodes
XmlAttributeCollection attribNodes = rootNode.Attributes;
if (attribNodes != null)
{
foreach (XmlNode attribNode in rootNode.Attributes)
{
if (attribNode.LocalName == "xmlns" || attribNode.Prefix == "xmlns")
namespaceList.Add(attribNode);
else
attribList.Add(attribNode);
}
}
index++;
} while (index < elementList.Count);
foreach (XmlNode elementNode in elementList)
{
nodeList.Add(elementNode);
}
foreach (XmlNode attribNode in attribList)
{
nodeList.Add(attribNode);
}
foreach (XmlNode namespaceNode in namespaceList)
{
nodeList.Add(namespaceNode);
}
return nodeList;
}
internal static bool NodeInList(XmlNode node, XmlNodeList nodeList)
{
foreach (XmlNode nodeElem in nodeList)
{
if (nodeElem == node) return true;
}
return false;
}
internal static string GetIdFromLocalUri(string uri, out bool discardComments)
{
string idref = uri.Substring(1);
// initialize the return value
discardComments = true;
// Deal with XPointer of type #xpointer(id("ID")). Other XPointer support isn't handled here and is anyway optional
if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal))
{
int startId = idref.IndexOf("id(", StringComparison.Ordinal);
int endId = idref.IndexOf(")", StringComparison.Ordinal);
if (endId < 0 || endId < startId + 3)
throw new CryptographicException(SR.Cryptography_Xml_InvalidReference);
idref = idref.Substring(startId + 3, endId - startId - 3);
idref = idref.Replace("\'", "");
idref = idref.Replace("\"", "");
discardComments = false;
}
return idref;
}
internal static string ExtractIdFromLocalUri(string uri)
{
string idref = uri.Substring(1);
// Deal with XPointer of type #xpointer(id("ID")). Other XPointer support isn't handled here and is anyway optional
if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal))
{
int startId = idref.IndexOf("id(", StringComparison.Ordinal);
int endId = idref.IndexOf(")", StringComparison.Ordinal);
if (endId < 0 || endId < startId + 3)
throw new CryptographicException(SR.Cryptography_Xml_InvalidReference);
idref = idref.Substring(startId + 3, endId - startId - 3);
idref = idref.Replace("\'", "");
idref = idref.Replace("\"", "");
}
return idref;
}
// This removes all children of an element.
internal static void RemoveAllChildren(XmlElement inputElement)
{
XmlNode child = inputElement.FirstChild;
XmlNode sibling = null;
while (child != null)
{
sibling = child.NextSibling;
inputElement.RemoveChild(child);
child = sibling;
}
}
// Writes one stream (starting from the current position) into
// an output stream, connecting them up and reading until
// hitting the end of the input stream.
// returns the number of bytes copied
internal static long Pump(Stream input, Stream output)
{
// Use MemoryStream's WriteTo(Stream) method if possible
MemoryStream inputMS = input as MemoryStream;
if (inputMS != null && inputMS.Position == 0)
{
inputMS.WriteTo(output);
return inputMS.Length;
}
const int count = 4096;
byte[] bytes = new byte[count];
int numBytes;
long totalBytes = 0;
while ((numBytes = input.Read(bytes, 0, count)) > 0)
{
output.Write(bytes, 0, numBytes);
totalBytes += numBytes;
}
return totalBytes;
}
internal static Hashtable TokenizePrefixListString(string s)
{
Hashtable set = new Hashtable();
if (s != null)
{
string[] prefixes = s.Split(null);
foreach (string prefix in prefixes)
{
if (prefix.Equals("#default"))
{
set.Add(string.Empty, true);
}
else if (prefix.Length > 0)
{
set.Add(prefix, true);
}
}
}
return set;
}
internal static string EscapeWhitespaceData(string data)
{
StringBuilder sb = new StringBuilder();
sb.Append(data);
Utils.SBReplaceCharWithString(sb, (char)13, "
");
return sb.ToString(); ;
}
internal static string EscapeTextData(string data)
{
StringBuilder sb = new StringBuilder();
sb.Append(data);
sb.Replace("&", "&");
sb.Replace("<", "<");
sb.Replace(">", ">");
SBReplaceCharWithString(sb, (char)13, "
");
return sb.ToString(); ;
}
internal static string EscapeCData(string data)
{
return EscapeTextData(data);
}
internal static string EscapeAttributeValue(string value)
{
StringBuilder sb = new StringBuilder();
sb.Append(value);
sb.Replace("&", "&");
sb.Replace("<", "<");
sb.Replace("\"", """);
SBReplaceCharWithString(sb, (char)9, "	");
SBReplaceCharWithString(sb, (char)10, "
");
SBReplaceCharWithString(sb, (char)13, "
");
return sb.ToString();
}
internal static XmlDocument GetOwnerDocument(XmlNodeList nodeList)
{
foreach (XmlNode node in nodeList)
{
if (node.OwnerDocument != null)
return node.OwnerDocument;
}
return null;
}
internal static void AddNamespaces(XmlElement elem, CanonicalXmlNodeList namespaces)
{
if (namespaces != null)
{
foreach (XmlNode attrib in namespaces)
{
string name = ((attrib.Prefix.Length > 0) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName);
// Skip the attribute if one with the same qualified name already exists
if (elem.HasAttribute(name) || (name.Equals("xmlns") && elem.Prefix.Length == 0)) continue;
XmlAttribute nsattrib = (XmlAttribute)elem.OwnerDocument.CreateAttribute(name);
nsattrib.Value = attrib.Value;
elem.SetAttributeNode(nsattrib);
}
}
}
internal static void AddNamespaces(XmlElement elem, Hashtable namespaces)
{
if (namespaces != null)
{
foreach (string key in namespaces.Keys)
{
if (elem.HasAttribute(key)) continue;
XmlAttribute nsattrib = (XmlAttribute)elem.OwnerDocument.CreateAttribute(key);
nsattrib.Value = namespaces[key] as string;
elem.SetAttributeNode(nsattrib);
}
}
}
// This method gets the attributes that should be propagated
internal static CanonicalXmlNodeList GetPropagatedAttributes(XmlElement elem)
{
if (elem == null)
return null;
CanonicalXmlNodeList namespaces = new CanonicalXmlNodeList();
XmlNode ancestorNode = elem;
if (ancestorNode == null) return null;
bool bDefNamespaceToAdd = true;
while (ancestorNode != null)
{
XmlElement ancestorElement = ancestorNode as XmlElement;
if (ancestorElement == null)
{
ancestorNode = ancestorNode.ParentNode;
continue;
}
if (!Utils.IsCommittedNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI))
{
// Add the namespace attribute to the collection if needed
if (!Utils.IsRedundantNamespace(ancestorElement, ancestorElement.Prefix, ancestorElement.NamespaceURI))
{
string name = ((ancestorElement.Prefix.Length > 0) ? "xmlns:" + ancestorElement.Prefix : "xmlns");
XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name);
nsattrib.Value = ancestorElement.NamespaceURI;
namespaces.Add(nsattrib);
}
}
if (ancestorElement.HasAttributes)
{
XmlAttributeCollection attribs = ancestorElement.Attributes;
foreach (XmlAttribute attrib in attribs)
{
// Add a default namespace if necessary
if (bDefNamespaceToAdd && attrib.LocalName == "xmlns")
{
XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute("xmlns");
nsattrib.Value = attrib.Value;
namespaces.Add(nsattrib);
bDefNamespaceToAdd = false;
continue;
}
// retain the declarations of type 'xml:*' as well
if (attrib.Prefix == "xmlns" || attrib.Prefix == "xml")
{
namespaces.Add(attrib);
continue;
}
if (attrib.NamespaceURI.Length > 0)
{
if (!Utils.IsCommittedNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI))
{
// Add the namespace attribute to the collection if needed
if (!Utils.IsRedundantNamespace(ancestorElement, attrib.Prefix, attrib.NamespaceURI))
{
string name = ((attrib.Prefix.Length > 0) ? "xmlns:" + attrib.Prefix : "xmlns");
XmlAttribute nsattrib = elem.OwnerDocument.CreateAttribute(name);
nsattrib.Value = attrib.NamespaceURI;
namespaces.Add(nsattrib);
}
}
}
}
}
ancestorNode = ancestorNode.ParentNode;
}
return namespaces;
}
// output of this routine is always big endian
internal static byte[] ConvertIntToByteArray(int dwInput)
{
byte[] rgbTemp = new byte[8]; // int can never be greater than Int64
int t1; // t1 is remaining value to account for
int t2; // t2 is t1 % 256
int i = 0;
if (dwInput == 0) return new byte[1];
t1 = dwInput;
while (t1 > 0)
{
t2 = t1 % 256;
rgbTemp[i] = (byte)t2;
t1 = (t1 - t2) / 256;
i++;
}
// Now, copy only the non-zero part of rgbTemp and reverse
byte[] rgbOutput = new byte[i];
// copy and reverse in one pass
for (int j = 0; j < i; j++)
{
rgbOutput[j] = rgbTemp[i - j - 1];
}
return rgbOutput;
}
internal static int ConvertByteArrayToInt(byte[] input)
{
// Input to this routine is always big endian
int dwOutput = 0;
for (int i = 0; i < input.Length; i++)
{
dwOutput *= 256;
dwOutput += input[i];
}
return (dwOutput);
}
internal static int GetHexArraySize(byte[] hex)
{
int index = hex.Length;
while (index-- > 0)
{
if (hex[index] != 0)
break;
}
return index + 1;
}
// Mimic the behavior of the X509IssuerSerial constructor with null and empty checks
internal static X509IssuerSerial CreateX509IssuerSerial(string issuerName, string serialNumber)
{
if (issuerName == null || issuerName.Length == 0)
throw new ArgumentException(SR.Arg_EmptyOrNullString, nameof(issuerName));
if (serialNumber == null || serialNumber.Length == 0)
throw new ArgumentException(SR.Arg_EmptyOrNullString, nameof(serialNumber));
return new X509IssuerSerial()
{
IssuerName = issuerName,
SerialNumber = serialNumber
};
}
internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyInfoX509Data, CertUsageType certUsageType)
{
X509Certificate2Collection collection = new X509Certificate2Collection();
ArrayList decryptionIssuerSerials = (certUsageType == CertUsageType.Decryption ? new ArrayList() : null);
if (keyInfoX509Data.Certificates != null)
{
foreach (X509Certificate2 certificate in keyInfoX509Data.Certificates)
{
switch (certUsageType)
{
case CertUsageType.Verification:
collection.Add(certificate);
break;
case CertUsageType.Decryption:
decryptionIssuerSerials.Add(CreateX509IssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber));
break;
}
}
}
if (keyInfoX509Data.SubjectNames == null && keyInfoX509Data.IssuerSerials == null &&
keyInfoX509Data.SubjectKeyIds == null && decryptionIssuerSerials == null)
return collection;
// Open LocalMachine and CurrentUser "Other People"/"My" stores.
X509Store[] stores = new X509Store[2];
string storeName = (certUsageType == CertUsageType.Verification ? "AddressBook" : "My");
stores[0] = new X509Store(storeName, StoreLocation.CurrentUser);
stores[1] = new X509Store(storeName, StoreLocation.LocalMachine);
for (int index = 0; index < stores.Length; index++)
{
if (stores[index] != null)
{
X509Certificate2Collection filters = null;
// We don't care if we can't open the store.
try
{
stores[index].Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
filters = stores[index].Certificates;
stores[index].Close();
if (keyInfoX509Data.SubjectNames != null)
{
foreach (string subjectName in keyInfoX509Data.SubjectNames)
{
filters = filters.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false);
}
}
if (keyInfoX509Data.IssuerSerials != null)
{
foreach (X509IssuerSerial issuerSerial in keyInfoX509Data.IssuerSerials)
{
filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false);
filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
}
}
if (keyInfoX509Data.SubjectKeyIds != null)
{
foreach (byte[] ski in keyInfoX509Data.SubjectKeyIds)
{
string hex = EncodeHexString(ski);
filters = filters.Find(X509FindType.FindBySubjectKeyIdentifier, hex, false);
}
}
if (decryptionIssuerSerials != null)
{
foreach (X509IssuerSerial issuerSerial in decryptionIssuerSerials)
{
filters = filters.Find(X509FindType.FindByIssuerDistinguishedName, issuerSerial.IssuerName, false);
filters = filters.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
}
}
}
// Store doesn't exist, no read permissions, other system error
catch (CryptographicException) { }
// Opening LocalMachine stores (other than Root or CertificateAuthority) on Linux
catch (PlatformNotSupportedException) { }
if (filters != null)
collection.AddRange(filters);
}
}
return collection;
}
private static readonly char[] s_hexValues = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
internal static string EncodeHexString(byte[] sArray)
{
return EncodeHexString(sArray, 0, (uint)sArray.Length);
}
internal static string EncodeHexString(byte[] sArray, uint start, uint end)
{
string result = null;
if (sArray != null)
{
char[] hexOrder = new char[(end - start) * 2];
uint digit;
for (uint i = start, j = 0; i < end; i++)
{
digit = (uint)((sArray[i] & 0xf0) >> 4);
hexOrder[j++] = s_hexValues[digit];
digit = (uint)(sArray[i] & 0x0f);
hexOrder[j++] = s_hexValues[digit];
}
result = new string(hexOrder);
}
return result;
}
internal static byte[] DecodeHexString(string s)
{
string hexString = Utils.DiscardWhiteSpaces(s);
uint cbHex = (uint)hexString.Length / 2;
byte[] hex = new byte[cbHex];
int i = 0;
for (int index = 0; index < cbHex; index++)
{
hex[index] = (byte)((HexToByte(hexString[i]) << 4) | HexToByte(hexString[i + 1]));
i += 2;
}
return hex;
}
internal static byte HexToByte(char val)
{
if (val <= '9' && val >= '0')
return (byte)(val - '0');
else if (val >= 'a' && val <= 'f')
return (byte)((val - 'a') + 10);
else if (val >= 'A' && val <= 'F')
return (byte)((val - 'A') + 10);
else
return 0xFF;
}
internal static bool IsSelfSigned(X509Chain chain)
{
X509ChainElementCollection elements = chain.ChainElements;
if (elements.Count != 1)
return false;
X509Certificate2 certificate = elements[0].Certificate;
if (string.Equals(certificate.SubjectName.Name, certificate.IssuerName.Name, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
internal static AsymmetricAlgorithm GetAnyPublicKey(X509Certificate2 certificate)
{
return (AsymmetricAlgorithm)certificate.GetRSAPublicKey();
}
internal const int MaxTransformsPerReference = 10;
internal const int MaxReferencesPerSignedInfo = 100;
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Web;
using MbUnit.Framework;
using Moq;
using Subtext.Extensibility;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Routing;
using Subtext.Framework.Syndication;
using Subtext.Framework.Syndication.Admin;
using UnitTests.Subtext.Framework.Util;
namespace UnitTests.Subtext.Framework.Syndication.Admin
{
[TestFixture]
public class ModeratedCommentRssWriterTests : SyndicationTestBase
{
/// <summary>
/// Tests that a valid feed is produced even if a post has no comments.
/// </summary>
[Test]
[RollBack2]
public void CommentRssWriterProducesValidEmptyFeed()
{
UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "blog");
var blogInfo = new Blog();
blogInfo.Host = "localhost";
blogInfo.Subfolder = "blog";
blogInfo.Email = "[email protected]";
blogInfo.RFC3229DeltaEncodingEnabled = true;
blogInfo.Title = "My Blog Rulz";
blogInfo.TimeZoneId = TimeZonesTest.PacificTimeZoneId;
HttpContext.Current.Items.Add("BlogInfo-", blogInfo);
var entry = new Entry(PostType.None);
entry.AllowComments = true;
entry.Title = "Comments requiring your approval.";
entry.Body = "The following items are waiting approval.";
entry.PostType = PostType.None;
var urlHelper = new Mock<BlogUrlHelper>();
urlHelper.Setup(url => url.ImageUrl(It.IsAny<string>())).Returns("/images/RSS2Image.gif");
urlHelper.Setup(url => url.GetVirtualPath(It.IsAny<string>(), It.IsAny<object>())).Returns(
"/blog/Admin/Feedback.aspx?status=2");
urlHelper.Setup(url => url.EntryUrl(It.IsAny<Entry>())).Returns("/blog/Admin/Feedback.aspx?status=2");
urlHelper.Setup(url => url.AdminUrl(It.IsAny<string>(), It.IsAny<object>())).Returns(
"/blog/Admin/Feedback.aspx?status=2");
var subtextContext = new Mock<ISubtextContext>();
subtextContext.Setup(c => c.Blog).Returns(blogInfo);
subtextContext.Setup(c => c.UrlHelper).Returns(urlHelper.Object);
var writer = new ModeratedCommentRssWriter(new StringWriter(), new List<FeedbackItem>(), entry,
subtextContext.Object);
string expected = @"<rss version=""2.0"" "
+ @"xmlns:dc=""http://purl.org/dc/elements/1.1/"" "
+ @"xmlns:trackback=""http://madskills.com/public/xml/rss/module/trackback/"" "
+ @"xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" "
+ @"xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"" "
+ @"xmlns:copyright=""http://blogs.law.harvard.edu/tech/rss"" "
+ @"xmlns:image=""http://purl.org/rss/1.0/modules/image/"">" + Environment.NewLine
+ indent() + @"<channel>" + Environment.NewLine
+ indent(2) + @"<title>Comments requiring your approval.</title>" + Environment.NewLine
+ indent(2) + @"<link>http://localhost/blog/Admin/Feedback.aspx?status=2</link>" +
Environment.NewLine
+ indent(2) + @"<description>The following items are waiting approval.</description>" +
Environment.NewLine
+ indent(2) + @"<language>en-US</language>" + Environment.NewLine
+ indent(2) + @"<copyright>Subtext Weblog</copyright>" + Environment.NewLine
+ indent(2) + @"<generator>{0}</generator>" + Environment.NewLine
+ indent(2) + @"<image>" + Environment.NewLine
+ indent(3) + @"<title>Comments requiring your approval.</title>" + Environment.NewLine
+ indent(3) + @"<url>http://localhost/images/RSS2Image.gif</url>" + Environment.NewLine
+ indent(3) + @"<link>http://localhost/blog/Admin/Feedback.aspx?status=2</link>" +
Environment.NewLine
+ indent(3) + @"<width>77</width>" + Environment.NewLine
+ indent(3) + @"<height>60</height>" + Environment.NewLine
+ indent(2) + @"</image>" + Environment.NewLine
+ indent(1) + @"</channel>" + Environment.NewLine
+ @"</rss>";
expected = string.Format(expected, VersionInfo.VersionDisplayText);
Assert.AreEqual(expected, writer.Xml);
}
/// <summary>
/// Tests that a valid feed is produced even if a post has no comments.
/// </summary>
[Test]
[RollBack2]
public void Xml_WithOneCommentNeedingModeration_ProducesValidRSSFeedWithTheOneComment()
{
// Arrange
UnitTestHelper.SetHttpContextWithBlogRequest("localhost", "", "Subtext.Web");
var blogInfo = new Blog();
blogInfo.Host = "localhost";
blogInfo.Email = "[email protected]";
blogInfo.RFC3229DeltaEncodingEnabled = true;
blogInfo.Title = "My Blog Rulz";
blogInfo.TimeZoneId = TimeZonesTest.PacificTimeZoneId;
HttpContext.Current.Items.Add("BlogInfo-", blogInfo);
var rootEntry = new Entry(PostType.None);
rootEntry.AllowComments = true;
rootEntry.Title = "Comments requiring your approval.";
rootEntry.Body = "The following items are waiting approval.";
rootEntry.PostType = PostType.None;
Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication(blogInfo, "haacked", "title of the post",
"Body of the post.");
entry.EntryName = "titleofthepost";
entry.DateCreatedUtc =
entry.DatePublishedUtc =
entry.DateModifiedUtc = DateTime.ParseExact("2006/02/01 08:00", "yyyy/MM/dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
entry.Id = 1001;
var comment = new FeedbackItem(FeedbackType.Comment);
comment.Id = 1002;
comment.DateCreatedUtc =
comment.DateModifiedUtc = DateTime.ParseExact("2006/02/02 07:00", "yyyy/MM/dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
comment.Title = "re: titleofthepost";
comment.ParentEntryName = entry.EntryName;
comment.ParentDateCreatedUtc = entry.DateCreatedUtc;
comment.Body = "<strong>I rule!</strong>";
comment.Author = "Jane Schmane";
comment.Email = "[email protected]";
comment.EntryId = entry.Id;
comment.Status = FeedbackStatusFlag.NeedsModeration;
var comments = new List<FeedbackItem>();
comments.Add(comment);
var urlHelper = new Mock<BlogUrlHelper>();
urlHelper.Setup(url => url.EntryUrl(It.IsAny<Entry>())).Returns(
"/Subtext.Web/archive/2006/02/01/titleofthepost.aspx");
urlHelper.Setup(url => url.FeedbackUrl(It.IsAny<FeedbackItem>())).Returns(
"/Subtext.Web/archive/2006/02/01/titleofthepost.aspx#1002");
urlHelper.Setup(url => url.ImageUrl(It.IsAny<string>())).Returns("/Subtext.Web/images/RSS2Image.gif");
urlHelper.Setup(url => url.AdminUrl(It.IsAny<string>(), It.IsAny<object>())).Returns(
"/Subtext.Web/Admin/Feedback.aspx?status=2");
var context = new Mock<ISubtextContext>();
context.Setup(c => c.UrlHelper).Returns(urlHelper.Object);
context.Setup(c => c.Blog).Returns(blogInfo);
var writer = new ModeratedCommentRssWriter(new StringWriter(), comments, rootEntry, context.Object);
string expected = @"<rss version=""2.0"" "
+ @"xmlns:dc=""http://purl.org/dc/elements/1.1/"" "
+ @"xmlns:trackback=""http://madskills.com/public/xml/rss/module/trackback/"" "
+ @"xmlns:wfw=""http://wellformedweb.org/CommentAPI/"" "
+ @"xmlns:slash=""http://purl.org/rss/1.0/modules/slash/"" "
+ @"xmlns:copyright=""http://blogs.law.harvard.edu/tech/rss"" "
+ @"xmlns:image=""http://purl.org/rss/1.0/modules/image/"">" + Environment.NewLine
+ indent() + @"<channel>" + Environment.NewLine
+ indent(2) + @"<title>Comments requiring your approval.</title>" + Environment.NewLine
+ indent(2) + @"<link>http://localhost/Subtext.Web/Admin/Feedback.aspx?status=2</link>" +
Environment.NewLine
+ indent(2) + @"<description>The following items are waiting approval.</description>" +
Environment.NewLine
+ indent(2) + @"<language>en-US</language>" + Environment.NewLine
+ indent(2) + @"<copyright>Subtext Weblog</copyright>" + Environment.NewLine
+ indent(2) + @"<generator>{0}</generator>" + Environment.NewLine
+ indent(2) + @"<image>" + Environment.NewLine
+ indent(3) + @"<title>Comments requiring your approval.</title>" + Environment.NewLine
+ indent(3) + @"<url>http://localhost/Subtext.Web/images/RSS2Image.gif</url>" +
Environment.NewLine
+ indent(3) +
@"<link>http://localhost/Subtext.Web/archive/2006/02/01/titleofthepost.aspx</link>" +
Environment.NewLine
+ indent(3) + @"<width>77</width>" + Environment.NewLine
+ indent(3) + @"<height>60</height>" + Environment.NewLine
+ indent(2) + @"</image>" + Environment.NewLine
+ indent(2) + @"<item>" + Environment.NewLine
+ indent(3) + @"<title>re: titleofthepost</title>" + Environment.NewLine
+ indent(3) +
@"<link>http://localhost/Subtext.Web/archive/2006/02/01/titleofthepost.aspx#1002</link>" +
Environment.NewLine
+ indent(3) + @"<description><strong>I rule!</strong></description>" +
Environment.NewLine
+ indent(3) + @"<dc:creator>Jane Schmane</dc:creator>" + Environment.NewLine
+ indent(3) +
@"<guid>http://localhost/Subtext.Web/archive/2006/02/01/titleofthepost.aspx#1002</guid>" +
Environment.NewLine
+ indent(3) + @"<pubDate>Thu, 02 Feb 2006 07:00:00 GMT</pubDate>" + Environment.NewLine
+ indent(2) + @"</item>" + Environment.NewLine
+ indent() + @"</channel>" + Environment.NewLine
+ @"</rss>";
expected = string.Format(expected, VersionInfo.VersionDisplayText);
// Act
string rss = writer.Xml;
// Assert
UnitTestHelper.AssertStringsEqualCharacterByCharacter(expected, rss);
//Assert.AreEqual(expected, writer.Xml);
}
[Test]
public void Ctor_WithNullEntryCollection_ThrowsArgumentNullException()
{
UnitTestHelper.AssertThrowsArgumentNullException(() =>
new CommentRssWriter(new StringWriter(), null, new Entry(PostType.BlogPost),
new Mock<ISubtextContext>().Object)
);
}
[Test]
public void Ctor_WithNullEntry_ThrowsArgumentNullException()
{
UnitTestHelper.AssertThrowsArgumentNullException(() =>
new CommentRssWriter(new StringWriter(), new List<FeedbackItem>(), null, new Mock<ISubtextContext>().Object)
);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Source groups.
//-----------------------------------------------------------------------------
singleton SFXDescription( AudioMaster );
singleton SFXSource( AudioChannelMaster )
{
description = AudioMaster;
};
singleton SFXDescription( AudioChannel )
{
sourceGroup = AudioChannelMaster;
};
singleton SFXSource( AudioChannelDefault )
{
description = AudioChannel;
};
singleton SFXSource( AudioChannelGui )
{
description = AudioChannel;
};
singleton SFXSource( AudioChannelEffects )
{
description = AudioChannel;
};
singleton SFXSource( AudioChannelMessages )
{
description = AudioChannel;
};
singleton SFXSource( AudioChannelMusic )
{
description = AudioChannel;
};
// Set default playback states of the channels.
AudioChannelMaster.play();
AudioChannelDefault.play();
AudioChannelGui.play();
AudioChannelMusic.play();
AudioChannelMessages.play();
// Stop in-game effects channels.
AudioChannelEffects.stop();
//-----------------------------------------------------------------------------
// Master SFXDescriptions.
//-----------------------------------------------------------------------------
// Master description for interface audio.
singleton SFXDescription( AudioGui )
{
volume = 1.0;
sourceGroup = AudioChannelGui;
};
// Master description for game effects audio.
singleton SFXDescription( AudioEffect )
{
volume = 1.0;
sourceGroup = AudioChannelEffects;
};
// Master description for audio in notifications.
singleton SFXDescription( AudioMessage )
{
volume = 1.0;
sourceGroup = AudioChannelMessages;
};
// Master description for music.
singleton SFXDescription( AudioMusic )
{
volume = 1.0;
sourceGroup = AudioChannelMusic;
};
//-----------------------------------------------------------------------------
// SFX Functions.
//-----------------------------------------------------------------------------
/// This initializes the sound system device from
/// the defaults in the $pref::SFX:: globals.
function sfxStartup()
{
echo( "\nsfxStartup..." );
// If we have a provider set, try initialize a device now.
if( $pref::SFX::provider !$= "" )
{
if( sfxInit() )
return;
else
{
// Force auto-detection.
$pref::SFX::autoDetect = true;
}
}
// If enabled autodetect a safe device.
if( ( !isDefined( "$pref::SFX::autoDetect" ) || $pref::SFX::autoDetect ) &&
sfxAutodetect() )
return;
// Failure.
error( " Failed to initialize device!\n\n" );
$pref::SFX::provider = "";
$pref::SFX::device = "";
return;
}
/// This initializes the sound system device from
/// the defaults in the $pref::SFX:: globals.
function sfxInit()
{
// If already initialized, shut down the current device first.
if( sfxGetDeviceInfo() !$= "" )
sfxShutdown();
// Start it up!
%maxBuffers = $pref::SFX::useHardware ? -1 : $pref::SFX::maxSoftwareBuffers;
if ( !sfxCreateDevice( $pref::SFX::provider, $pref::SFX::device, $pref::SFX::useHardware, %maxBuffers ) )
return false;
// This returns a tab seperated string with
// the initialized system info.
%info = sfxGetDeviceInfo();
$pref::SFX::provider = getField( %info, 0 );
$pref::SFX::device = getField( %info, 1 );
$pref::SFX::useHardware = getField( %info, 2 );
%useHardware = $pref::SFX::useHardware ? "Yes" : "No";
%maxBuffers = getField( %info, 3 );
echo( " Provider: " @ $pref::SFX::provider );
echo( " Device: " @ $pref::SFX::device );
echo( " Hardware: " @ %useHardware );
echo( " Buffers: " @ %maxBuffers );
echo( " " );
if( isDefined( "$pref::SFX::distanceModel" ) )
sfxSetDistanceModel( $pref::SFX::distanceModel );
if( isDefined( "$pref::SFX::dopplerFactor" ) )
sfxSetDopplerFactor( $pref::SFX::dopplerFactor );
if( isDefined( "$pref::SFX::rolloffFactor" ) )
sfxSetRolloffFactor( $pref::SFX::rolloffFactor );
// Restore master volume.
sfxSetMasterVolume( $pref::SFX::masterVolume );
// Restore channel volumes.
for( %channel = 0; %channel <= 8; %channel ++ )
sfxSetChannelVolume( %channel, $pref::SFX::channelVolume[ %channel ] );
return true;
}
/// Destroys the current sound system device.
function sfxShutdown()
{
// Store volume prefs.
$pref::SFX::masterVolume = sfxGetMasterVolume();
for( %channel = 0; %channel <= 8; %channel ++ )
$pref::SFX::channelVolume[ %channel ] = sfxGetChannelVolume( %channel );
// We're assuming here that a null info
// string means that no device is loaded.
if( sfxGetDeviceInfo() $= "" )
return;
sfxDeleteDevice();
}
/// Determines which of the two SFX providers is preferable.
function sfxCompareProvider( %providerA, %providerB )
{
if( %providerA $= %providerB )
return 0;
switch$( %providerA )
{
// Always prefer FMOD over anything else.
case "FMOD":
return 1;
// Prefer OpenAL over anything but FMOD.
case "OpenAL":
if( %providerB $= "FMOD" )
return -1;
else
return 1;
// As long as the XAudio SFX provider still has issues,
// choose stable DSound over it.
case "DirectSound":
if( %providerB $= "FMOD" || %providerB $= "OpenAL" )
return -1;
else
return 0;
case "XAudio":
if( %providerB !$= "FMOD" && %providerB !$= "OpenAL" && %providerB !$= "DirectSound" )
return 1;
else
return -1;
default:
return -1;
}
}
/// Try to detect and initalize the best SFX device available.
function sfxAutodetect()
{
// Get all the available devices.
%devices = sfxGetAvailableDevices();
// Collect and sort the devices by preferentiality.
%deviceTrySequence = new ArrayObject();
%bestMatch = -1;
%count = getRecordCount( %devices );
for( %i = 0; %i < %count; %i ++ )
{
%info = getRecord( %devices, %i );
%provider = getField( %info, 0 );
%deviceTrySequence.push_back( %provider, %info );
}
%deviceTrySequence.sortfkd( "sfxCompareProvider" );
// Try the devices in order.
%count = %deviceTrySequence.count();
for( %i = 0; %i < %count; %i ++ )
{
%provider = %deviceTrySequence.getKey( %i );
%info = %deviceTrySequence.getValue( %i );
$pref::SFX::provider = %provider;
$pref::SFX::device = getField( %info, 1 );
$pref::SFX::useHardware = getField( %info, 2 );
// By default we've decided to avoid hardware devices as
// they are buggy and prone to problems.
$pref::SFX::useHardware = false;
if( sfxInit() )
{
$pref::SFX::autoDetect = false;
%deviceTrySequence.delete();
return true;
}
}
// Found no suitable device.
error( "sfxAutodetect - Could not initialize a valid SFX device." );
$pref::SFX::provider = "";
$pref::SFX::device = "";
$pref::SFX::useHardware = "";
%deviceTrySequence.delete();
return false;
}
//-----------------------------------------------------------------------------
// Backwards-compatibility with old channel system.
//-----------------------------------------------------------------------------
// Volume channel IDs for backwards-compatibility.
$GuiAudioType = 1; // Interface.
$SimAudioType = 2; // Game.
$MessageAudioType = 3; // Notifications.
$MusicAudioType = 4; // Music.
$AudioChannels[ 0 ] = AudioChannelDefault;
$AudioChannels[ $GuiAudioType ] = AudioChannelGui;
$AudioChannels[ $SimAudioType ] = AudioChannelEffects;
$AudioChannels[ $MessageAudioType ] = AudioChannelMessages;
$AudioChannels[ $MusicAudioType ] = AudioChannelMusic;
function sfxOldChannelToGroup( %channel )
{
return $AudioChannels[ %channel ];
}
function sfxGroupToOldChannel( %group )
{
%id = %group.getId();
for( %i = 0;; %i ++ )
if( !isObject( $AudioChannels[ %i ] ) )
return -1;
else if( $AudioChannels[ %i ].getId() == %id )
return %i;
return -1;
}
function sfxSetMasterVolume( %volume )
{
AudioChannelMaster.setVolume( %volume );
}
function sfxGetMasterVolume( %volume )
{
return AudioChannelMaster.getVolume();
}
function sfxStopAll( %channel )
{
// Don't stop channel itself since that isn't quite what the function
// here intends.
%channel = sfxOldChannelToGroup( %channel );
if (isObject(%channel))
{
foreach( %source in %channel )
%source.stop();
}
}
function sfxGetChannelVolume( %channel )
{
%obj = sfxOldChannelToGroup( %channel );
if( isObject( %obj ) )
return %obj.getVolume();
}
function sfxSetChannelVolume( %channel, %volume )
{
%obj = sfxOldChannelToGroup( %channel );
if( isObject( %obj ) )
%obj.setVolume( %volume );
}
singleton SimSet( SFXPausedSet );
/// Pauses the playback of active sound sources.
///
/// @param %channels An optional word list of channel indices or an empty
/// string to pause sources on all channels.
/// @param %pauseSet An optional SimSet which is filled with the paused
/// sources. If not specified the global SfxSourceGroup
/// is used.
///
/// @deprecated
///
function sfxPause( %channels, %pauseSet )
{
// Did we get a set to populate?
if ( !isObject( %pauseSet ) )
%pauseSet = SFXPausedSet;
%count = SFXSourceSet.getCount();
for ( %i = 0; %i < %count; %i++ )
{
%source = SFXSourceSet.getObject( %i );
%channel = sfxGroupToOldChannel( %source.getGroup() );
if( %channels $= "" || findWord( %channels, %channel ) != -1 )
{
%source.pause();
%pauseSet.add( %source );
}
}
}
/// Resumes the playback of paused sound sources.
///
/// @param %pauseSet An optional SimSet which contains the paused sound
/// sources to be resumed. If not specified the global
/// SfxSourceGroup is used.
/// @deprecated
///
function sfxResume( %pauseSet )
{
if ( !isObject( %pauseSet ) )
%pauseSet = SFXPausedSet;
%count = %pauseSet.getCount();
for ( %i = 0; %i < %count; %i++ )
{
%source = %pauseSet.getObject( %i );
%source.play();
}
// Clear our pause set... the caller is left
// to clear his own if he passed one.
%pauseSet.clear();
}
| |
/*
* Naiad ver. 0.5
* 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
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Threading;
using Microsoft.Research.Naiad.Dataflow.Channels;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Research.Naiad.Scheduling;
using Microsoft.Research.Naiad.Runtime.Networking;
using Microsoft.Research.Naiad.Diagnostics;
namespace Microsoft.Research.Naiad.Runtime.Networking
{
internal enum NaiadProtocolOpcode
{
InvalidOpcode = -1,
PeerConnect = 0,
ConstructGraph = 1,
LoadDataFromFile = 2,
GetIngressSocket = 3,
GetEgressSocket = 4,
GetComputationStats = 5,
DoReport = 6,
Kill = 7,
List = 8,
Complain = 9
}
internal class NaiadServer : IDisposable
{
private enum ServerState
{
Initalized,
Started,
Stopped
}
private ServerState state;
private struct GuardedAction
{
public GuardedAction(Action<Socket> a, bool mustGuard)
{
Guard = new Task(() => { });
if (!mustGuard)
{
Guard.RunSynchronously();
}
Action = a;
}
public readonly Task Guard;
public readonly Action<Socket> Action;
}
private readonly IPEndPoint endpoint;
private readonly Socket listeningSocket;
private readonly Dictionary<NaiadProtocolOpcode, GuardedAction> serverActions;
private readonly Dictionary<int, TcpNetworkChannel> networkChannels;
private readonly Thread servingThread;
public NaiadServer(ref IPEndPoint endpoint)
{
this.serverActions = new Dictionary<NaiadProtocolOpcode, GuardedAction>();
this.state = ServerState.Initalized;
this.serverActions[NaiadProtocolOpcode.Kill] = new GuardedAction(s => { using (TextWriter writer = new StreamWriter(new NetworkStream(s))) writer.WriteLine("Killed"); s.Close(); System.Environment.Exit(-9); }, false);
this.networkChannels = new Dictionary<int, TcpNetworkChannel>();
this.serverActions[NaiadProtocolOpcode.PeerConnect] = new GuardedAction(s => { int channelId = ReceiveInt(s); this.networkChannels[channelId].PeerConnect(s); }, true);
Socket socket = BindSocket(ref endpoint);
this.endpoint = endpoint;
this.listeningSocket = socket;
this.servingThread = new Thread(this.ThreadStart);
}
public void RegisterNetworkChannel(TcpNetworkChannel channel)
{
if (channel != null)
this.networkChannels[channel.Id] = channel;
}
/// <summary>
/// Registers an Action that will be called when a connection is made with the given opcode.
///
/// The Action receives the socket for the accepted connection, and is responsible for managing that
/// resource by e.g. closing it.
///
/// This method must be called before a call to Start();
/// </summary>
/// <param name="opcode">The opcode to handle.</param>
/// <param name="serverAction">The Action to execute when this opcode is received.</param>
/// <param name="mustGuard">If true, the execution will be guarded.</param>
public void RegisterServerAction(NaiadProtocolOpcode opcode, Action<Socket> serverAction, bool mustGuard)
{
this.serverActions[opcode] = new GuardedAction(serverAction, mustGuard);
}
private Socket TryToBind(IPEndPoint endpoint)
{
Logging.Progress("Trying to bind Naiad server at {0}", endpoint);
Socket s = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
s.Bind(endpoint);
return s;
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.AddressAlreadyInUse)
{
// another process has bound to this socket: we'll pick a different port and try
// again in the calling code
return null;
}
else
{
// unexpected error so we'll just let someone else deal with it
throw;
}
}
}
/// <summary>
/// Binds the server socket to an available port.
/// </summary>
/// <param name="endpoint">If this parameter is not null, try to listen on this endpoint, otherwise one will be picked arbitrarily.</param>
/// <returns>The bound socket.</returns>
private Socket BindSocket(ref IPEndPoint endpoint)
{
Socket socket = null;
if (endpoint == null)
{
int port = 2101;
for (int i = 0; socket == null && i < 1000; ++i)
{
endpoint = new IPEndPoint(IPAddress.Any, port + i);
socket = TryToBind(endpoint);
}
}
else
{
socket = TryToBind(endpoint);
}
if (socket == null)
{
throw new ApplicationException("Unable to find a socket to bind to");
}
Logging.Progress("Starting Naiad server at {0}", endpoint);
return socket;
}
/// <summary>
/// Starts the server accepting connections. To stop the server, call <see cref="Stop"/>.
/// </summary>
public void Start()
{
Debug.Assert(this.state == ServerState.Initalized);
this.servingThread.Start();
}
/// <summary>
/// Accept loop thread. Implements protocol operation demuxing, based on a 4-byte opcode, in the first 4 bytes received
/// from the accept()'ed socket.
/// </summary>
private void ThreadStart()
{
this.state = ServerState.Started;
this.listeningSocket.Listen(100);
while (true)
{
Socket acceptedSocket;
try
{
acceptedSocket = this.listeningSocket.Accept();
}
catch (ObjectDisposedException)
{
break;
}
catch (SocketException se)
{
if (se.SocketErrorCode == SocketError.Interrupted)
{
break;
}
else
{
throw;
}
}
NaiadProtocolOpcode opcode = (NaiadProtocolOpcode) ReceiveInt(acceptedSocket);
GuardedAction acceptAction;
if (this.serverActions.TryGetValue(opcode, out acceptAction))
{
// Ensures that the Action runs after the Guard task has run.
acceptAction.Guard.ContinueWith(
(task) => AcceptInternal(acceptAction.Action, acceptedSocket, opcode));
}
else
{
Logging.Progress("Invalid/unhandled opcode received: {0}", opcode);
acceptedSocket.Close();
}
}
}
public void AcceptPeerConnections()
{
// Allows queued PeerConnect operations to continue.
this.serverActions[NaiadProtocolOpcode.PeerConnect].Guard.RunSynchronously();
}
private void AcceptInternal(Action<Socket> action, Socket peerSocket, NaiadProtocolOpcode opcode)
{
try
{
action(peerSocket);
}
catch (Exception e)
{
Logging.Progress("Error handling a connection with opcode: {0}", opcode);
Logging.Progress(e.ToString());
peerSocket.Close();
}
}
private static int ReceiveInt(Socket peerSocket)
{
byte[] intBuffer = new byte[4];
int n = peerSocket.Receive(intBuffer);
Debug.Assert(n == 4);
return BitConverter.ToInt32(intBuffer, 0);
}
public void Stop()
{
Debug.Assert(this.state == ServerState.Started);
this.listeningSocket.Close();
this.servingThread.Join();
this.state = ServerState.Stopped;
}
public void Dispose()
{
if (this.state == ServerState.Started)
this.Stop();
this.listeningSocket.Dispose();
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2012-2014 Charlie Poole, Rob Prouse
//
// 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 PARALLEL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace NUnit.Framework.Internal.Execution
{
/// <summary>
/// ParallelWorkItemDispatcher handles execution of work items by
/// queuing them for worker threads to process.
/// </summary>
public class ParallelWorkItemDispatcher : IWorkItemDispatcher
{
private static readonly Logger log = InternalTrace.GetLogger("Dispatcher");
private WorkItem _topLevelWorkItem;
private readonly Stack<WorkItem> _savedWorkItems = new Stack<WorkItem>();
#region Events
/// <summary>
/// Event raised whenever a shift is starting.
/// </summary>
public event ShiftChangeEventHandler ShiftStarting;
/// <summary>
/// Event raised whenever a shift has ended.
/// </summary>
public event ShiftChangeEventHandler ShiftFinished;
#endregion
#region Constructor
/// <summary>
/// Construct a ParallelWorkItemDispatcher
/// </summary>
/// <param name="levelOfParallelism">Number of workers to use</param>
public ParallelWorkItemDispatcher(int levelOfParallelism)
{
log.Info("Initializing with {0} workers", levelOfParallelism);
LevelOfParallelism = levelOfParallelism;
InitializeShifts();
}
private void InitializeShifts()
{
foreach (var shift in Shifts)
shift.EndOfShift += OnEndOfShift;
// Assign queues to shifts
ParallelShift.AddQueue(ParallelQueue);
#if APARTMENT_STATE
ParallelShift.AddQueue(ParallelSTAQueue);
#endif
NonParallelShift.AddQueue(NonParallelQueue);
#if APARTMENT_STATE
NonParallelSTAShift.AddQueue(NonParallelSTAQueue);
#endif
// Create workers and assign to shifts and queues
// TODO: Avoid creating all the workers till needed
for (int i = 1; i <= LevelOfParallelism; i++)
{
string name = string.Format("ParallelWorker#" + i.ToString());
ParallelShift.Assign(new TestWorker(ParallelQueue, name));
}
#if APARTMENT_STATE
ParallelShift.Assign(new TestWorker(ParallelSTAQueue, "ParallelSTAWorker"));
#endif
var worker = new TestWorker(NonParallelQueue, "NonParallelWorker");
worker.Busy += OnStartNonParallelWorkItem;
NonParallelShift.Assign(worker);
#if APARTMENT_STATE
worker = new TestWorker(NonParallelSTAQueue, "NonParallelSTAWorker");
worker.Busy += OnStartNonParallelWorkItem;
NonParallelSTAShift.Assign(worker);
#endif
}
private void OnStartNonParallelWorkItem(TestWorker worker, WorkItem work)
{
// This captures the startup of TestFixtures and SetUpFixtures,
// but not their teardown items, which are not composite items
if (work.IsolateChildTests)
IsolateQueues(work);
}
#endregion
#region Properties
/// <summary>
/// Number of parallel worker threads
/// </summary>
public int LevelOfParallelism { get; }
/// <summary>
/// Enumerates all the shifts supported by the dispatcher
/// </summary>
public IEnumerable<WorkShift> Shifts
{
get
{
yield return ParallelShift;
yield return NonParallelShift;
#if APARTMENT_STATE
yield return NonParallelSTAShift;
#endif
}
}
/// <summary>
/// Enumerates all the Queues supported by the dispatcher
/// </summary>
public IEnumerable<WorkItemQueue> Queues
{
get
{
yield return ParallelQueue;
#if APARTMENT_STATE
yield return ParallelSTAQueue;
#endif
yield return NonParallelQueue;
#if APARTMENT_STATE
yield return NonParallelSTAQueue;
#endif
}
}
// WorkShifts - Dispatcher processes tests in three non-overlapping shifts.
// See comment in Workshift.cs for a more detailed explanation.
private WorkShift ParallelShift { get; } = new WorkShift("Parallel");
private WorkShift NonParallelShift { get; } = new WorkShift("NonParallel");
#if APARTMENT_STATE
private WorkShift NonParallelSTAShift { get; } = new WorkShift("NonParallelSTA");
// WorkItemQueues
private WorkItemQueue ParallelQueue { get; } = new WorkItemQueue("ParallelQueue", true, ApartmentState.MTA);
private WorkItemQueue ParallelSTAQueue { get; } = new WorkItemQueue("ParallelSTAQueue", true, ApartmentState.STA);
private WorkItemQueue NonParallelQueue { get; } = new WorkItemQueue("NonParallelQueue", false, ApartmentState.MTA);
private WorkItemQueue NonParallelSTAQueue { get; } = new WorkItemQueue("NonParallelSTAQueue", false, ApartmentState.STA);
#else
// WorkItemQueues
private WorkItemQueue ParallelQueue { get; } = new WorkItemQueue("ParallelQueue", true);
private WorkItemQueue NonParallelQueue { get; } = new WorkItemQueue("NonParallelQueue", false);
#endif
#endregion
#region IWorkItemDispatcher Members
/// <summary>
/// Start execution, setting the top level work,
/// enqueuing it and starting a shift to execute it.
/// </summary>
public void Start(WorkItem topLevelWorkItem)
{
_topLevelWorkItem = topLevelWorkItem;
Dispatch(topLevelWorkItem, InitialExecutionStrategy(topLevelWorkItem));
var shift = SelectNextShift();
ShiftStarting?.Invoke(shift);
shift.Start();
}
// Initial strategy for the top level item is solely determined
// by the ParallelScope of that item. While other approaches are
// possible, this one gives the user a predictable result.
private static ParallelExecutionStrategy InitialExecutionStrategy(WorkItem workItem)
{
return workItem.ParallelScope == ParallelScope.Default || workItem.ParallelScope == ParallelScope.None
? ParallelExecutionStrategy.NonParallel
: ParallelExecutionStrategy.Parallel;
}
/// <summary>
/// Dispatch a single work item for execution. The first
/// work item dispatched is saved as the top-level
/// work item and used when stopping the run.
/// </summary>
/// <param name="work">The item to dispatch</param>
public void Dispatch(WorkItem work)
{
Dispatch(work, work.ExecutionStrategy);
}
// Separate method so it can be used by Start
private void Dispatch(WorkItem work, ParallelExecutionStrategy strategy)
{
log.Debug("Using {0} strategy for {1}", strategy, work.Name);
switch (strategy)
{
default:
case ParallelExecutionStrategy.Direct:
work.Execute();
break;
case ParallelExecutionStrategy.Parallel:
#if APARTMENT_STATE
if (work.TargetApartment == ApartmentState.STA)
ParallelSTAQueue.Enqueue(work);
else
#endif
ParallelQueue.Enqueue(work);
break;
case ParallelExecutionStrategy.NonParallel:
#if APARTMENT_STATE
if (work.TargetApartment == ApartmentState.STA)
NonParallelSTAQueue.Enqueue(work);
else
#endif
NonParallelQueue.Enqueue(work);
break;
}
}
/// <summary>
/// Cancel the ongoing run completely.
/// If no run is in process, the call has no effect.
/// </summary>
public void CancelRun(bool force)
{
foreach (var shift in Shifts)
shift.Cancel(force);
}
private readonly object _queueLock = new object();
private int _isolationLevel = 0;
/// <summary>
/// Save the state of the queues and create a new isolated set
/// </summary>
internal void IsolateQueues(WorkItem work)
{
log.Info("Saving Queue State for {0}", work.Name);
lock (_queueLock)
{
foreach (WorkItemQueue queue in Queues)
queue.Save();
_savedWorkItems.Push(_topLevelWorkItem);
_topLevelWorkItem = work;
_isolationLevel++;
}
}
/// <summary>
/// Remove isolated queues and restore old ones
/// </summary>
private void RestoreQueues()
{
Guard.OperationValid(_isolationLevel > 0, $"Called {nameof(RestoreQueues)} with no saved queues.");
// Keep lock until we can remove for both methods
lock (_queueLock)
{
log.Info("Restoring Queue State");
foreach (WorkItemQueue queue in Queues)
queue.Restore();
_topLevelWorkItem = _savedWorkItems.Pop();
_isolationLevel--;
}
}
#endregion
#region Helper Methods
private void OnEndOfShift(WorkShift endingShift)
{
ShiftFinished?.Invoke(endingShift);
WorkShift nextShift = null;
while (true)
{
// Shift has ended but all work may not yet be done
while (_topLevelWorkItem.State != WorkItemState.Complete)
{
// This will return null if all queues are empty.
nextShift = SelectNextShift();
if (nextShift != null)
{
ShiftStarting?.Invoke(nextShift);
nextShift.Start();
return;
}
}
// If the shift has ended for an isolated queue, restore
// the queues and keep trying. Otherwise, we are done.
if (_isolationLevel > 0)
RestoreQueues();
else
break;
}
// All done - shutdown all shifts
foreach (var shift in Shifts)
shift.ShutDown();
}
private WorkShift SelectNextShift()
{
foreach (var shift in Shifts)
if (shift.HasWork)
return shift;
return null;
}
#endregion
}
#region ParallelScopeHelper Class
#if NET35
static class ParallelScopeHelper
{
public static bool HasFlag(this ParallelScope scope, ParallelScope value)
{
return (scope & value) != 0;
}
}
#endif
#endregion
}
#endif
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.10.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* YouTube Reporting API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/youtube/reporting/v1/reports/'>YouTube Reporting API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20160301 (425)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/youtube/reporting/v1/reports/'>
* https://developers.google.com/youtube/reporting/v1/reports/</a>
* <tr><th>Discovery Name<td>youtubereporting
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using YouTube Reporting API can be found at
* <a href='https://developers.google.com/youtube/reporting/v1/reports/'>https://developers.google.com/youtube/reporting/v1/reports/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.YouTubeReporting.v1
{
/// <summary>The YouTubeReporting Service.</summary>
public class YouTubeReportingService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public YouTubeReportingService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public YouTubeReportingService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
jobs = new JobsResource(this);
media = new MediaResource(this);
reportTypes = new ReportTypesResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "youtubereporting"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://youtubereporting.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
/// <summary>Available OAuth 2.0 scopes for use with the YouTube Reporting API.</summary>
public class Scope
{
/// <summary>View monetary and non-monetary YouTube Analytics reports for your YouTube content</summary>
public static string YtAnalyticsMonetaryReadonly = "https://www.googleapis.com/auth/yt-analytics-monetary.readonly";
/// <summary>View YouTube Analytics reports for your YouTube content</summary>
public static string YtAnalyticsReadonly = "https://www.googleapis.com/auth/yt-analytics.readonly";
}
private readonly JobsResource jobs;
/// <summary>Gets the Jobs resource.</summary>
public virtual JobsResource Jobs
{
get { return jobs; }
}
private readonly MediaResource media;
/// <summary>Gets the Media resource.</summary>
public virtual MediaResource Media
{
get { return media; }
}
private readonly ReportTypesResource reportTypes;
/// <summary>Gets the ReportTypes resource.</summary>
public virtual ReportTypesResource ReportTypes
{
get { return reportTypes; }
}
}
///<summary>A base abstract class for YouTubeReporting requests.</summary>
public abstract class YouTubeReportingBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new YouTubeReportingBaseServiceRequest instance.</summary>
protected YouTubeReportingBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Xgafv { get; set; }
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Alt { get; set; }
/// <summary>OAuth bearer token.</summary>
[Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string BearerToken { get; set; }
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Pretty-print response.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Pp { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes YouTubeReporting parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"bearer_token", new Google.Apis.Discovery.Parameter
{
Name = "bearer_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pp", new Google.Apis.Discovery.Parameter
{
Name = "pp",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "jobs" collection of methods.</summary>
public class JobsResource
{
private const string Resource = "jobs";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public JobsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
reports = new ReportsResource(service);
}
private readonly ReportsResource reports;
/// <summary>Gets the Reports resource.</summary>
public virtual ReportsResource Reports
{
get { return reports; }
}
/// <summary>The "reports" collection of methods.</summary>
public class ReportsResource
{
private const string Resource = "reports";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ReportsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Gets the metadata of a specific report.</summary>
/// <param name="jobId">The ID of the job.</param>
/// <param name="reportId">The ID of the report to
/// retrieve.</param>
public virtual GetRequest Get(string jobId, string reportId)
{
return new GetRequest(service, jobId, reportId);
}
/// <summary>Gets the metadata of a specific report.</summary>
public class GetRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.Report>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string jobId, string reportId)
: base(service)
{
JobId = jobId;
ReportId = reportId;
InitParameters();
}
/// <summary>The ID of the job.</summary>
[Google.Apis.Util.RequestParameterAttribute("jobId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string JobId { get; private set; }
/// <summary>The ID of the report to retrieve.</summary>
[Google.Apis.Util.RequestParameterAttribute("reportId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ReportId { get; private set; }
/// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user
/// is acting for himself (his own channel).</summary>
[Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OnBehalfOfContentOwner { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/jobs/{jobId}/reports/{reportId}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"jobId", new Google.Apis.Discovery.Parameter
{
Name = "jobId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"reportId", new Google.Apis.Discovery.Parameter
{
Name = "reportId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter
{
Name = "onBehalfOfContentOwner",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists reports created by a specific job. Returns NOT_FOUND if the job does not exist.</summary>
/// <param name="jobId">The ID of the job.</param>
public virtual ListRequest List(string jobId)
{
return new ListRequest(service, jobId);
}
/// <summary>Lists reports created by a specific job. Returns NOT_FOUND if the job does not exist.</summary>
public class ListRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.ListReportsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string jobId)
: base(service)
{
JobId = jobId;
InitParameters();
}
/// <summary>The ID of the job.</summary>
[Google.Apis.Util.RequestParameterAttribute("jobId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string JobId { get; private set; }
/// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user
/// is acting for himself (his own channel).</summary>
[Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OnBehalfOfContentOwner { get; set; }
/// <summary>Requested page size. Server may return fewer report types than requested. If unspecified,
/// server will pick an appropriate default.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>A token identifying a page of results the server should return. Typically, this is the
/// value of ListReportsResponse.next_page_token returned in response to the previous call to the
/// `ListReports` method.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>If set, only reports created after the specified date/time are returned.</summary>
[Google.Apis.Util.RequestParameterAttribute("createdAfter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CreatedAfter { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/jobs/{jobId}/reports"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"jobId", new Google.Apis.Discovery.Parameter
{
Name = "jobId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter
{
Name = "onBehalfOfContentOwner",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"createdAfter", new Google.Apis.Discovery.Parameter
{
Name = "createdAfter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Creates a job and returns it.</summary>
/// <param name="body">The body of the request.</param>
public virtual CreateRequest Create(Google.Apis.YouTubeReporting.v1.Data.Job body)
{
return new CreateRequest(service, body);
}
/// <summary>Creates a job and returns it.</summary>
public class CreateRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.Job>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.YouTubeReporting.v1.Data.Job body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user is
/// acting for himself (his own channel).</summary>
[Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OnBehalfOfContentOwner { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.YouTubeReporting.v1.Data.Job Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/jobs"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter
{
Name = "onBehalfOfContentOwner",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Deletes a job.</summary>
/// <param name="jobId">The ID of the job to delete.</param>
public virtual DeleteRequest Delete(string jobId)
{
return new DeleteRequest(service, jobId);
}
/// <summary>Deletes a job.</summary>
public class DeleteRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string jobId)
: base(service)
{
JobId = jobId;
InitParameters();
}
/// <summary>The ID of the job to delete.</summary>
[Google.Apis.Util.RequestParameterAttribute("jobId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string JobId { get; private set; }
/// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user is
/// acting for himself (his own channel).</summary>
[Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OnBehalfOfContentOwner { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/jobs/{jobId}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"jobId", new Google.Apis.Discovery.Parameter
{
Name = "jobId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter
{
Name = "onBehalfOfContentOwner",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Gets a job.</summary>
/// <param name="jobId">The ID of the job to retrieve.</param>
public virtual GetRequest Get(string jobId)
{
return new GetRequest(service, jobId);
}
/// <summary>Gets a job.</summary>
public class GetRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.Job>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string jobId)
: base(service)
{
JobId = jobId;
InitParameters();
}
/// <summary>The ID of the job to retrieve.</summary>
[Google.Apis.Util.RequestParameterAttribute("jobId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string JobId { get; private set; }
/// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user is
/// acting for himself (his own channel).</summary>
[Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OnBehalfOfContentOwner { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/jobs/{jobId}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"jobId", new Google.Apis.Discovery.Parameter
{
Name = "jobId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter
{
Name = "onBehalfOfContentOwner",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists jobs.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists jobs.</summary>
public class ListRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.ListJobsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user is
/// acting for himself (his own channel).</summary>
[Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OnBehalfOfContentOwner { get; set; }
/// <summary>Requested page size. Server may return fewer jobs than requested. If unspecified, server will
/// pick an appropriate default.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>A token identifying a page of results the server should return. Typically, this is the value of
/// ListReportTypesResponse.next_page_token returned in response to the previous call to the `ListJobs`
/// method.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/jobs"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter
{
Name = "onBehalfOfContentOwner",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>The "media" collection of methods.</summary>
public class MediaResource
{
private const string Resource = "media";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public MediaResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Method for media download. Download is supported on the URI
/// `/v1/media/{+name}?alt=media`.</summary>
/// <param name="resourceName">Name of the media that is being downloaded. See
/// ByteStream.ReadRequest.resource_name.</param>
public virtual DownloadRequest Download(string resourceName)
{
return new DownloadRequest(service, resourceName);
}
/// <summary>Method for media download. Download is supported on the URI
/// `/v1/media/{+name}?alt=media`.</summary>
public class DownloadRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.Media>
{
/// <summary>Constructs a new Download request.</summary>
public DownloadRequest(Google.Apis.Services.IClientService service, string resourceName)
: base(service)
{
ResourceName = resourceName;
MediaDownloader = new Google.Apis.Download.MediaDownloader(service);
InitParameters();
}
/// <summary>Name of the media that is being downloaded. See ByteStream.ReadRequest.resource_name.</summary>
[Google.Apis.Util.RequestParameterAttribute("resourceName", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ResourceName { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "download"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/media/{+resourceName}"; }
}
/// <summary>Initializes Download parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"resourceName", new Google.Apis.Discovery.Parameter
{
Name = "resourceName",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^.*$",
});
}
/// <summary>Gets the media downloader.</summary>
public Google.Apis.Download.IMediaDownloader MediaDownloader { get; private set; }
/// <summary>Synchronously download the media into the given stream.</summary>
public virtual void Download(System.IO.Stream stream)
{
MediaDownloader.Download(this.GenerateRequestUri(), stream);
}
/// <summary>Asynchronously download the media into the given stream.</summary>
public virtual System.Threading.Tasks.Task<Google.Apis.Download.IDownloadProgress> DownloadAsync(System.IO.Stream stream)
{
return MediaDownloader.DownloadAsync(this.GenerateRequestUri(), stream);
}
/// <summary>Asynchronously download the media into the given stream.</summary>
public virtual System.Threading.Tasks.Task<Google.Apis.Download.IDownloadProgress> DownloadAsync(System.IO.Stream stream,
System.Threading.CancellationToken cancellationToken)
{
return MediaDownloader.DownloadAsync(this.GenerateRequestUri(), stream, cancellationToken);
}
}
}
/// <summary>The "reportTypes" collection of methods.</summary>
public class ReportTypesResource
{
private const string Resource = "reportTypes";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ReportTypesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Lists report types.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists report types.</summary>
public class ListRequest : YouTubeReportingBaseServiceRequest<Google.Apis.YouTubeReporting.v1.Data.ListReportTypesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>The content owner's external ID on which behalf the user is acting on. If not set, the user is
/// acting for himself (his own channel).</summary>
[Google.Apis.Util.RequestParameterAttribute("onBehalfOfContentOwner", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OnBehalfOfContentOwner { get; set; }
/// <summary>Requested page size. Server may return fewer report types than requested. If unspecified,
/// server will pick an appropriate default.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>A token identifying a page of results the server should return. Typically, this is the value of
/// ListReportTypesResponse.next_page_token returned in response to the previous call to the
/// `ListReportTypes` method.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/reportTypes"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"onBehalfOfContentOwner", new Google.Apis.Discovery.Parameter
{
Name = "onBehalfOfContentOwner",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.YouTubeReporting.v1.Data
{
/// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A
/// typical example is to use it as the request or the response type of an API method. For instance: service Foo {
/// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty
/// JSON object `{}`.</summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A job creating reports of a specific type.</summary>
public class Job : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The creation date/time of the job.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual string CreateTime { get; set; }
/// <summary>The server-generated ID of the job (max. 40 characters).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>The name of the job (max. 100 characters).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The type of reports this job creates. Corresponds to the ID of a ReportType.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportTypeId")]
public virtual string ReportTypeId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for ReportingService.ListJobs.</summary>
public class ListJobsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of jobs.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("jobs")]
public virtual System.Collections.Generic.IList<Job> Jobs { get; set; }
/// <summary>A token to retrieve next page of results. Pass this value in the ListJobsRequest.page_token field
/// in the subsequent call to `ListJobs` method to retrieve the next page of results.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for ReportingService.ListReportTypes.</summary>
public class ListReportTypesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A token to retrieve next page of results. Pass this value in the ListReportTypesRequest.page_token
/// field in the subsequent call to `ListReportTypes` method to retrieve the next page of results.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The list of report types.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reportTypes")]
public virtual System.Collections.Generic.IList<ReportType> ReportTypes { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for ReportingService.ListReports.</summary>
public class ListReportsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A token to retrieve next page of results. Pass this value in the ListReportsRequest.page_token
/// field in the subsequent call to `ListReports` method to retrieve the next page of results.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The list of report types.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("reports")]
public virtual System.Collections.Generic.IList<Report> Reports { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Media resource.</summary>
public class Media : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Name of the media resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceName")]
public virtual string ResourceName { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A report's metadata including the URL from which the report itself can be downloaded.</summary>
public class Report : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The date/time when this report was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual string CreateTime { get; set; }
/// <summary>The URL from which the report can be downloaded (max. 1000 characters).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("downloadUrl")]
public virtual string DownloadUrl { get; set; }
/// <summary>The end of the time period that the report instance covers. The value is exclusive.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual string EndTime { get; set; }
/// <summary>The server-generated ID of the report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>The ID of the job that created this report.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("jobId")]
public virtual string JobId { get; set; }
/// <summary>The start of the time period that the report instance covers. The value is inclusive.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startTime")]
public virtual string StartTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A report type.</summary>
public class ReportType : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ID of the report type (max. 100 characters).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>The name of the report type (max. 100 characters).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file=".cs" company="sgmunn">
// (c) sgmunn 2012
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of
// the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
//
using System;
using MonoTouch.UIKit;
using System.Drawing;
namespace MonoKit.ViewControllers
{
public class SlidingViewController : UIViewController
{
public SlidingViewController()
{
}
public bool ShowingMasterViewController
{
get;
private set;
}
public UIViewController MasterViewController
{
get;
set;
}
public UIViewController DetailViewController
{
get;
set;
}
public void SetShowingMasterViewController(bool flag)
{
this.SetShowingMasterViewController(flag, false, null);
}
public void SetShowingMasterViewController(bool flag, bool animate, Action<bool> onCompletion)
{
if (this.ShowingMasterViewController == flag)
{
if (onCompletion != null)
{
onCompletion(false);
}
}
this.ShowingMasterViewController = flag;
double duration = animate ? 0.3 : 0;
// oncompletion doesn't have a parameter
UIView.Animate(
duration,
0,
UIViewAnimationOptions.BeginFromCurrentState | UIViewAnimationOptions.AllowUserInteraction,
() => this.LayoutViews(),
() => {
if (onCompletion != null)
{
onCompletion(true);
}});
}
private void SetMasterViewController(UIViewController master)
{
this.SetMasterViewController(master, false, null);
}
public void SetMasterViewController(UIViewController master, bool animate, Action<bool> onCompletion)
{
if (this.MasterViewController == master)
{
if (onCompletion != null)
{
onCompletion(false);
}
}
if (this.MasterViewController != null)
{
this.MasterViewController.WillMoveToParentViewController(null);
this.MasterViewController.RemoveFromParentViewController();
this.MasterViewController.View.RemoveFromSuperview();
}
this.MasterViewController = master;
if (this.MasterViewController != null)
{
this.AddChildViewController(this.MasterViewController);
this.ConfigureMasterView(this.MasterViewController.View);
this.View.AddSubview(this.MasterViewController.View);
this.MasterViewController.DidMoveToParentViewController(this);
}
this.LayoutViews();
if (onCompletion != null)
{
onCompletion(true);
}
}
public void SetDetailViewController(UIViewController detail, bool animate, Action<bool> onCompletion)
{
if (this.DetailViewController == detail)
{
if (onCompletion != null)
{
onCompletion(false);
}
}
if (this.DetailViewController != null)
{
this.DetailViewController.WillMoveToParentViewController(null);
this.DetailViewController.RemoveFromParentViewController();
this.DetailViewController.View.RemoveFromSuperview();
}
this.DetailViewController = detail;
if (this.DetailViewController != null)
{
this.AddChildViewController(this.DetailViewController);
this.ConfigureMasterView(this.DetailViewController.View);
this.View.AddSubview(this.DetailViewController.View);
this.DetailViewController.DidMoveToParentViewController(this);
}
this.LayoutViews();
if (onCompletion != null)
{
onCompletion(true);
}
}
public RectangleF RectForMasterView
{
get
{
return this.View.Bounds;
}
}
public RectangleF RectForDetailView
{
get
{
if (this.ShowingMasterViewController)
{
return new RectangleF(this.View.Bounds.X + 200, this.View.Bounds.Y, this.View.Bounds.Width, this.View.Bounds.Height);
}
return this.View.Bounds;
}
}
public PointF DetailViewTranslationForGestureTranslation(PointF translation)
{
return new PointF(translation.X, 0);
}
public bool ShouldShowMasterViewControllerWithGestureTranslation(PointF translation)
{
if (this.ShowingMasterViewController && translation.X > 0)
{
return true;
}
if (this.ShowingMasterViewController && translation.X < 0)
{
return false;
}
return this.ShowingMasterViewController;
}
private UIPanGestureRecognizer panGestureRecognizer;
public UIPanGestureRecognizer PanGestureRecognizer
{
get
{
if (this.panGestureRecognizer == null)
{
this.panGestureRecognizer = new UIPanGestureRecognizer(this.HandlePan);
//this.panGestureRecognizer.AddTarget(this, this.HandlePan);
this.panGestureRecognizer.WeakDelegate = this;
this.panGestureRecognizer.CancelsTouchesInView = true;
}
return this.panGestureRecognizer;
}
}
private UITapGestureRecognizer tapGestureRecognizer;
public UITapGestureRecognizer TapGestureRecognizer
{
get
{
if (this.tapGestureRecognizer == null)
{
this.tapGestureRecognizer = new UITapGestureRecognizer(this.HandleTap);
//this.tapGestureRecognizer.AddTarget(this, () => this.HandleTap());
this.tapGestureRecognizer.WeakDelegate = this;
this.tapGestureRecognizer.CancelsTouchesInView = true;
}
return this.tapGestureRecognizer;
}
}
public override bool ShouldAutorotateToInterfaceOrientation(UIInterfaceOrientation toInterfaceOrientation)
{
if (this.MasterViewController == null || this.DetailViewController == null)
{
return true;
}
return this.MasterViewController.ShouldAutorotateToInterfaceOrientation(toInterfaceOrientation)
&& this.DetailViewController.ShouldAutorotateToInterfaceOrientation(toInterfaceOrientation);
}
private void HandlePan()
{
}
private void HandleTap()
{
UIView.Animate(0.25, 0, UIViewAnimationOptions.CurveEaseInOut,
() =>
{
this.SetShowingMasterViewController(false);
this.View.LayoutSubviews();
this.LayoutViews();
}, null
);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
this.View.AddGestureRecognizer(this.PanGestureRecognizer);
this.View.AddGestureRecognizer(this.TapGestureRecognizer);
}
public override void ViewDidUnload()
{
base.ViewDidUnload();
this.panGestureRecognizer = null;
this.tapGestureRecognizer = null;
}
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
this.LayoutViews();
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
this.LayoutViews();
}
private void LayoutViews()
{
var masterView = this.MasterViewController.View;
var detailView = this.DetailViewController.View;
masterView.Frame = this.RectForMasterView;
detailView.Frame = this.RectForDetailView;
detailView.Superview.BringSubviewToFront(detailView);
detailView.UserInteractionEnabled = !this.ShowingMasterViewController;
}
protected virtual void ConfigureMasterView(UIView view)
{
}
protected virtual void ConfigureDetailView(UIView view)
{
}
}
}
| |
// Copyright (c) 2004-2010 Azavea, 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 System.Reflection;
using System.Text;
using Azavea.Open.Common;
using Azavea.Open.DAO.Criteria;
using Azavea.Open.DAO.Criteria.Grouping;
using Azavea.Open.DAO.Exceptions;
using Azavea.Open.DAO.Util;
using log4net;
namespace Azavea.Open.DAO
{
/// <summary>
/// Defines an interface that FastDAO can use to run data access functions that
/// are specific to a particular data source (e.g. sql-based database).
///
/// This class, and all classes that extend it, should be thread-safe.
/// </summary>
public abstract class AbstractDaLayer : IDaLayer
{
/// <summary>
/// log4net logger that any child class may use for logging any appropriate messages.
/// </summary>
protected static ILog _log = LogManager.GetLogger(
new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().DeclaringType.Namespace);
/// <summary>
/// The connection descriptor that is being used by this FastDaoLayer.
/// </summary>
protected readonly IConnectionDescriptor _connDesc;
#region Properties Defining What Is Supported On This Layer
private readonly bool _supportsNumRecords;
/// <summary>
/// If true, methods that return numbers of records affected will be
/// returning accurate numbers. If false, they will return
/// UNKNOWN_NUM_ROWS.
/// </summary>
public virtual bool SupportsNumRecords()
{
return _supportsNumRecords;
}
#endregion
/// <summary>
/// A mapping of additional types that can be handled by this DAO to methods for handling them.
/// It is initially null, but can be created and aded to by a subclass to easily allow for
/// handling arbitrary data types.
///
/// Use must be synchronized!
/// </summary>
protected Dictionary<Type, TypeCoercionDelegate> _coerceableTypes;
#region Constructors
/// <summary>
/// Instantiates the data access layer with the connection descriptor for the DB.
/// </summary>
/// <param name="connDesc">The connection descriptor that is being used by this FastDaoLayer.</param>
/// <param name="supportsNumRecords">If true, methods that return numbers of records affected will be
/// returning accurate numbers. If false, they will probably return
/// FastDAO.UNKNOWN_NUM_ROWS.</param>
protected AbstractDaLayer(IConnectionDescriptor connDesc, bool supportsNumRecords)
{
_connDesc = connDesc;
_supportsNumRecords = supportsNumRecords;
}
#endregion
#region Methods For Modifying Behavior
/// <summary>
/// A method to add a coercion delegate for a type, without exposing the dictionary.
/// </summary>
/// <param name="t">The type to coerce.</param>
/// <param name="coercionDelegate">How to coerce it.</param>
public void AddCoercibleType(Type t, TypeCoercionDelegate coercionDelegate)
{
lock (this)
{
if (_coerceableTypes == null)
{
_coerceableTypes = new Dictionary<Type, TypeCoercionDelegate>();
}
_coerceableTypes.Add(t, coercionDelegate);
}
}
#endregion
#region Delete
/// <summary>
/// Deletes a data object record using the mapping and criteria for what's deleted.
/// </summary>
/// <param name="transaction">The transaction to do this as part of.</param>
/// <param name="mapping">The mapping of the table from which to delete.</param>
/// <param name="crit">Criteria for deletion. NOTE: Only the expressions are observed,
/// other things (like "order" or start / limit) are ignored.
/// WARNING: A null or empty (no expression) criteria will
/// delete ALL records!</param>
/// <returns>The number of records affected.</returns>
public abstract int Delete(ITransaction transaction, ClassMapping mapping, DaoCriteria crit);
/// <summary>
/// Deletes all contents of the table. Faster for large tables than DeleteAll,
/// but requires greater permissions. For layers that do not support this, the
/// behavior should be the same as calling Delete(null, mapping).
/// </summary>
public abstract void Truncate(ClassMapping mapping);
#endregion
#region Insert
/// <summary>
/// Inserts a data object record using the "table" and a list of column/value pairs.
/// </summary>
/// <param name="transaction">The transaction to do this as part of.</param>
/// <param name="mapping">The mapping of the table or other data container we're dealing with.</param>
/// <param name="propValues">A dictionary of "column"/value pairs for the object to insert.</param>
/// <returns>The number of records affected.</returns>
public abstract int Insert(ITransaction transaction, ClassMapping mapping, IDictionary<string, object> propValues);
/// <summary>
/// Inserts a list of data object records of the same type. The default implementation
/// merely calls Insert for each one, however some datasources may have more efficient
/// ways of inserting multiple records that the appropriate DaLayer will take advantage of.
/// </summary>
/// <param name="transaction">The transaction to do this as part of.</param>
/// <param name="mapping">The mapping of the table or other data container we're dealing with.</param>
/// <param name="propValueDictionaries">A list of dictionaries of column/value pairs.
/// Each item in the list should represent the dictionary of column/value pairs for
/// each respective object being inserted.</param>
public virtual void InsertBatch(ITransaction transaction, ClassMapping mapping, List<IDictionary<string, object>> propValueDictionaries)
{
foreach(Dictionary<string, object> propValues in propValueDictionaries)
{
Insert(transaction, mapping, propValues);
}
}
#endregion
#region Update
/// <summary>
/// Updates a data object record using the "table" and a list of column/value pairs.
/// </summary>
/// <param name="transaction">The transaction to do this as part of.</param>
/// <param name="mapping">The mapping of the table or other data container we're dealing with.</param>
/// <param name="crit">All records matching this criteria will be updated per the dictionary of
/// values.</param>
/// <param name="propValues">A dictionary of column/value pairs for all non-ID columns to be updated.</param>
/// <returns>The number of records affected.</returns>
public abstract int Update(ITransaction transaction, ClassMapping mapping, DaoCriteria crit, IDictionary<string, object> propValues);
/// <summary>
/// Updates a list of data object records of the same type. The default implementation
/// merely calls Update for each one, however some datasources may have more efficient
/// ways of inserting multiple records that the appropriate DaLayer will take advantage of.
/// </summary>
/// <param name="transaction">The transaction to do this as part of.</param>
/// <param name="mapping">The mapping of the table or other data container we're dealing with.</param>
/// <param name="criteriaList">A list of DaoCriteria.
/// Each item in the list should represent the criteria for
/// rows that will be updated per the accompanying dictionary.</param>
/// <param name="propValueDictionaries">A list of dictionaries of column/value pairs.
/// Each item in the list should represent the dictionary of non-ID column/value pairs for
/// each respective object being updated.</param>
public virtual void UpdateBatch(ITransaction transaction, ClassMapping mapping, List<DaoCriteria> criteriaList,
List<IDictionary<string, object>> propValueDictionaries)
{
for (int i = 0; i < criteriaList.Count; i++)
{
Update(transaction, mapping, criteriaList[i], propValueDictionaries[i]);
}
}
#endregion
#region Querying
/// <summary>
/// Builds the query based on a serializable criteria. The Query object is particular to
/// the implementation, but may contain things like the parameters parsed out, or whatever
/// makes sense to this FastDaoLayer. You can think of this method as a method to convert
/// from the generic DaoCriteria into the specific details necessary for querying.
/// </summary>
/// <param name="mapping">The mapping of the table for which to build the query string.</param>
/// <param name="crit">The criteria to use to find the desired objects.</param>
/// <returns>A query that can be run by ExecureQuery.</returns>
public abstract IDaQuery CreateQuery(ClassMapping mapping, DaoCriteria crit);
/// <summary>
/// Executes a query and invokes a method with a DataReader of results.
/// </summary>
/// <param name="transaction">The transaction to do this as part of.</param>
/// <param name="mapping">Class mapping for the table we're querying against. Optional,
/// but not all columns may be properly typed if it is null.</param>
/// <param name="query">The query to execute, should have come from CreateQuery.</param>
/// <param name="invokeMe">The method to invoke with the IDataReader results.</param>
/// <param name="parameters">A hashtable containing any values that need to be persisted through invoked method.
/// The list of objects from the query will be placed here.</param>
public abstract void ExecuteQuery(ITransaction transaction, ClassMapping mapping, IDaQuery query, DataReaderDelegate invokeMe, Hashtable parameters);
/// <summary>
/// Should be called when you're done with the query. Allows us to cache the
/// objects for reuse.
/// </summary>
/// <param name="query">Query you're done using.</param>
public abstract void DisposeOfQuery(IDaQuery query);
/// <summary>
/// Gets a count of records for the given criteria.
/// </summary>
/// <param name="transaction">The transaction to do this as part of.</param>
/// <param name="mapping">The mapping of the table for which to build the query string.</param>
/// <param name="crit">The criteria to use for "where" comparisons.</param>
/// <returns>The number of results found that matched the criteria.</returns>
public abstract int GetCount(ITransaction transaction, ClassMapping mapping, DaoCriteria crit);
/// <summary>
/// Gets a count of records for the given criteria,
/// aggregated by the given grouping expressions. This matches "GROUP BY" behavior
/// in SQL.
/// </summary>
/// <param name="transaction">The transaction to do this as part of.</param>
/// <param name="mapping">The mapping of the table for which to build the query string.</param>
/// <param name="crit">The criteria to use for "where" comparisons.</param>
/// <param name="groupExpressions">The fields/expressions to aggregate on when counting.</param>
/// <returns>The number of objects that match the criteria, plus the values of those objects
/// for the fields that were aggregated on.</returns>
public abstract List<GroupCountResult> GetCount(ITransaction transaction, ClassMapping mapping, DaoCriteria crit,
ICollection<AbstractGroupExpression> groupExpressions);
#endregion
#region Utility Methods
/// <summary>
/// Attempts to convert the value into the given type. While broadly
/// similar to Convert.ChangeType, that method doesn't support enums and this one does.
/// Calling that from within this method makes it take nearly twice as long, so this method
/// does its own type checking.
/// </summary>
/// <param name="desiredType">Type we need the value to be.</param>
/// <param name="input">Input value, may or may not already be the right type.</param>
/// <returns>An object of type desiredType whose value is equal to the input.</returns>
public virtual object CoerceType(Type desiredType, object input)
{
try
{
// For speed, put the most common checks at the top.
if (desiredType.IsInstanceOfType(input))
{
return input;
}
if (desiredType.Equals(typeof (string)))
{
return Convert.ToString(input);
}
if (desiredType.Equals(typeof (int)))
{
return input is string ? (int)Decimal.Parse((string)input) : Convert.ToInt32(input);
}
if (desiredType.Equals(typeof (long)))
{
return input is string ? (long)Decimal.Parse((string)input) : Convert.ToInt32(input);
}
if (desiredType.Equals(typeof (double)))
{
return Convert.ToDouble(input);
}
if (desiredType.Equals(typeof (DateTime)))
{
return Convert.ToDateTime(input);
}
if (desiredType.IsEnum)
{
return (input is int) ? input : Enum.Parse(desiredType, input.ToString());
}
if (desiredType.Equals(typeof (bool)))
{
return Convert.ToBoolean(input);
}
if (desiredType.Equals(typeof (short)))
{
return Convert.ToInt16(input);
}
if (desiredType.Equals(typeof (byte)))
{
return Convert.ToByte(input);
}
if (desiredType.Equals(typeof (char)))
{
return Convert.ToChar(input);
}
if (desiredType.Equals(typeof (float)))
{
return (float) Convert.ToDouble(input);
}
if (desiredType.Equals(typeof (DateTime?)))
{
if (input == null)
{
return null;
}
return Convert.ToDateTime(input);
}
if (desiredType.Equals(typeof(int?)))
{
if (input == null)
{
return null;
}
return Convert.ToInt32(input);
}
if (desiredType.Equals(typeof(long?)))
{
if (input == null)
{
return null;
}
return Convert.ToInt64(input);
}
if (desiredType.Equals(typeof(double?)))
{
if (input == null)
{
return null;
}
return Convert.ToDouble(input);
}
if (desiredType.Equals(typeof (float?)))
{
if (input == null)
{
return null;
}
return (float) Convert.ToDouble(input);
}
if (desiredType.Equals(typeof (bool?)))
{
if (input == null)
{
return null;
}
return Convert.ToBoolean(input);
}
if (desiredType.Equals(typeof (byte[])))
{
// Cast to byte array here so we'll throw if the type is incompatible.
// Technically we don't have to, since this returns object, but we want
// this to be the method that throws the type cast exception.
byte[] retVal = (byte[]) input;
return retVal;
}
// Nullables are generics, so nullable enums are more work to check for.
if (desiredType.IsGenericType &&
desiredType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
// Technically this first check will work for any nullable type, not just enums.
if (input == null)
{
return null;
}
// Note that we're only handling nullables, which have 1 generic param
// which is why the [0] is correct.
Type genericType = desiredType.GetGenericArguments()[0];
if (genericType.IsEnum)
{
return (input is int)
// Unlike normal enums, integers cannot simply be set on a nullable enum.
// So we have to call ToObject to convert it to an enum value first.
? Enum.ToObject(genericType, input)
// Since it is a nullable enum, we're allowing blank or all-whitespace
// strings to count as nulls.
: (StringHelper.IsNonBlank(input.ToString())
? Enum.Parse(genericType, input.ToString())
: null);
}
}
// For misc object types, we'll just check if it is already the correct type.
if (desiredType.IsInstanceOfType(input))
{
return input;
}
// If it's mapped as an AsciiString, put the value in as a byte array of
// ascii characters. This supports old-style (non-unicode) varchars.
if (desiredType.Equals(typeof (AsciiString)))
{
return Encoding.ASCII.GetBytes(input.ToString());
}
// Have subclasses be able to add their own coerced types.
lock (this)
{
if (_coerceableTypes != null)
{
foreach (Type t in _coerceableTypes.Keys)
{
if (t.IsAssignableFrom(desiredType))
{
return _coerceableTypes[t].DynamicInvoke(input);
}
}
}
}
}
catch (Exception e)
{
throw new DaoTypeCoercionException(desiredType, input, e);
}
// To add support for lists, you'd need to add:
//if (desiredType.IsSubclassOf(typeof(IList)))
//{
// // input is some sort of list ID, so go run a subquery or something...
//}
// You'd also need to check if the input was a list, and do something special rather
// than just try to convert it to an int or whatever.
// Custom class types would be similar... Hmm, and you'd have to add support to the
// class mapping to handle nested classes. OK it's a tad more complicated, but it
// is doable if necessary.
// Oh yeah and then you have to handle transactions correctly, so if a second query fails
// you remember to roll back the first one... And there are probably a billion other details...
throw new DaoUnsupportedTypeCoercionException(desiredType, input);
}
/// <summary>
/// Given the class mapping and the column name, determines the appropriate
/// c# data type.
/// </summary>
/// <param name="col">Column to look up.</param>
/// <param name="mapping">Mapping for the class we're creating a table for.</param>
/// <returns>A C# type that will be stored in the column.</returns>
protected Type GetDataType(string col, ClassMapping mapping)
{
Type colType = null;
// Use the explicit type if there is one.
if (mapping.DataColTypesByDataCol.ContainsKey(col))
{
colType = mapping.DataColTypesByDataCol[col];
}
// Otherwise use the type of the member on the mapped object.
if ((colType == null) && (mapping.AllObjMemberInfosByDataCol.ContainsKey(col)))
{
MemberInfo info = mapping.AllObjMemberInfosByDataCol[col];
if (info is FieldInfo)
{
colType = ((FieldInfo)info).FieldType;
}
else if (info is PropertyInfo)
{
colType = ((PropertyInfo)info).PropertyType;
}
}
// Default behavior is assume string since pretty much everything can be stored
// as a string. This should generally only happen for DictionaryDAOs.
if (colType == null)
{
colType = typeof(string);
}
return colType;
}
/// <summary>
/// Finds the last generated id number for a column.
/// </summary>
/// <param name="transaction">The transaction to do this as part of.</param>
/// <param name="mapping">The class mapping for the table being queried.</param>
/// <param name="idCol">The ID column for which to find the last-generated ID.</param>
public abstract object GetLastAutoGeneratedId(ITransaction transaction, ClassMapping mapping, string idCol);
/// <summary>
/// Gets the next id number from a sequence in the data source.
/// </summary>
/// <param name="transaction">The transaction to do this as part of.</param>
/// <param name="sequenceName">The name of the sequence.</param>
/// <returns>The next number from the sequence.</returns>
public abstract int GetNextSequenceValue(ITransaction transaction, string sequenceName);
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Bindables;
using osuTK;
using osuTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Overlays.SearchableList;
using osu.Game.Overlays.Social;
using osu.Game.Users;
using System.Threading;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Threading;
namespace osu.Game.Overlays
{
public class SocialOverlay : SearchableListOverlay<SocialTab, SocialSortCriteria, SortDirection>
{
private readonly LoadingSpinner loading;
private FillFlowContainer<SocialPanel> panels;
protected override Color4 BackgroundColour => Color4Extensions.FromHex(@"60284b");
protected override Color4 TrianglesColourLight => Color4Extensions.FromHex(@"672b51");
protected override Color4 TrianglesColourDark => Color4Extensions.FromHex(@"5c2648");
protected override SearchableListHeader<SocialTab> CreateHeader() => new Header();
protected override SearchableListFilterControl<SocialSortCriteria, SortDirection> CreateFilterControl() => new FilterControl();
private User[] users = Array.Empty<User>();
public User[] Users
{
get => users;
set
{
if (users == value)
return;
users = value ?? Array.Empty<User>();
if (LoadState >= LoadState.Ready)
recreatePanels();
}
}
public SocialOverlay()
: base(OverlayColourScheme.Pink)
{
Add(loading = new LoadingSpinner());
Filter.Search.Current.ValueChanged += text =>
{
if (!string.IsNullOrEmpty(text.NewValue))
{
// force searching in players until searching for friends is supported
Header.Tabs.Current.Value = SocialTab.AllPlayers;
if (Filter.Tabs.Current.Value != SocialSortCriteria.Rank)
Filter.Tabs.Current.Value = SocialSortCriteria.Rank;
}
};
Header.Tabs.Current.ValueChanged += _ => queueUpdate();
Filter.Tabs.Current.ValueChanged += _ => onFilterUpdate();
Filter.DisplayStyleControl.DisplayStyle.ValueChanged += _ => recreatePanels();
Filter.DisplayStyleControl.Dropdown.Current.ValueChanged += _ => recreatePanels();
currentQuery.BindTo(Filter.Search.Current);
currentQuery.ValueChanged += query =>
{
queryChangedDebounce?.Cancel();
if (string.IsNullOrEmpty(query.NewValue))
queueUpdate();
else
queryChangedDebounce = Scheduler.AddDelayed(updateSearch, 500);
};
}
[BackgroundDependencyLoader]
private void load()
{
recreatePanels();
}
private APIRequest getUsersRequest;
private readonly Bindable<string> currentQuery = new Bindable<string>();
private ScheduledDelegate queryChangedDebounce;
private void queueUpdate() => Scheduler.AddOnce(updateSearch);
private CancellationTokenSource loadCancellation;
private void updateSearch()
{
queryChangedDebounce?.Cancel();
if (!IsLoaded)
return;
Users = null;
clearPanels();
getUsersRequest?.Cancel();
if (API?.IsLoggedIn != true)
return;
switch (Header.Tabs.Current.Value)
{
case SocialTab.Friends:
var friendRequest = new GetFriendsRequest(); // TODO filter arguments?
friendRequest.Success += users => Users = users.ToArray();
API.Queue(getUsersRequest = friendRequest);
break;
default:
var userRequest = new GetUsersRequest(); // TODO filter arguments!
userRequest.Success += res => Users = res.Users.Select(r => r.User).ToArray();
API.Queue(getUsersRequest = userRequest);
break;
}
}
private void recreatePanels()
{
clearPanels();
if (Users == null)
{
loading.Hide();
return;
}
IEnumerable<User> sortedUsers = Users;
switch (Filter.Tabs.Current.Value)
{
case SocialSortCriteria.Location:
sortedUsers = sortedUsers.OrderBy(u => u.Country.FullName);
break;
case SocialSortCriteria.Name:
sortedUsers = sortedUsers.OrderBy(u => u.Username);
break;
}
if (Filter.DisplayStyleControl.Dropdown.Current.Value == SortDirection.Descending)
sortedUsers = sortedUsers.Reverse();
var newPanels = new FillFlowContainer<SocialPanel>
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Spacing = new Vector2(10f),
Margin = new MarginPadding { Top = 10 },
ChildrenEnumerable = sortedUsers.Select(u =>
{
SocialPanel panel;
switch (Filter.DisplayStyleControl.DisplayStyle.Value)
{
case PanelDisplayStyle.Grid:
panel = new SocialGridPanel(u)
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre
};
break;
default:
panel = new SocialListPanel(u);
break;
}
panel.Status.BindTo(u.Status);
panel.Activity.BindTo(u.Activity);
return panel;
})
};
LoadComponentAsync(newPanels, f =>
{
if (panels != null)
ScrollFlow.Remove(panels);
loading.Hide();
ScrollFlow.Add(panels = newPanels);
}, (loadCancellation = new CancellationTokenSource()).Token);
}
private void onFilterUpdate()
{
if (Filter.Tabs.Current.Value == SocialSortCriteria.Rank)
{
queueUpdate();
return;
}
recreatePanels();
}
private void clearPanels()
{
loading.Show();
loadCancellation?.Cancel();
if (panels != null)
{
panels.Expire();
panels = null;
}
}
public override void APIStateChanged(IAPIProvider api, APIState state)
{
switch (state)
{
case APIState.Online:
queueUpdate();
break;
default:
Users = null;
clearPanels();
break;
}
}
}
public enum SortDirection
{
Ascending,
Descending
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
// The SortedDictionary class implements a generic sorted list of keys
// and values. Entries in a sorted list are sorted by their keys and
// are accessible both by key and by index. The keys of a sorted dictionary
// can be ordered either according to a specific IComparer
// implementation given when the sorted dictionary is instantiated, or
// according to the IComparable implementation provided by the keys
// themselves. In either case, a sorted dictionary does not allow entries
// with duplicate or null keys.
//
// A sorted list internally maintains two arrays that store the keys and
// values of the entries. The capacity of a sorted list is the allocated
// length of these internal arrays. As elements are added to a sorted list, the
// capacity of the sorted list is automatically increased as required by
// reallocating the internal arrays. The capacity is never automatically
// decreased, but users can call either TrimExcess or
// Capacity explicitly.
//
// The GetKeyList and GetValueList methods of a sorted list
// provides access to the keys and values of the sorted list in the form of
// List implementations. The List objects returned by these
// methods are aliases for the underlying sorted list, so modifications
// made to those lists are directly reflected in the sorted list, and vice
// versa.
//
// The SortedList class provides a convenient way to create a sorted
// copy of another dictionary, such as a Hashtable. For example:
//
// Hashtable h = new Hashtable();
// h.Add(...);
// h.Add(...);
// ...
// SortedList s = new SortedList(h);
//
// The last line above creates a sorted list that contains a copy of the keys
// and values stored in the hashtable. In this particular example, the keys
// will be ordered according to the IComparable interface, which they
// all must implement. To impose a different ordering, SortedList also
// has a constructor that allows a specific IComparer implementation to
// be specified.
//
[DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class SortedList<TKey, TValue> :
IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> where TKey : notnull
{
private TKey[] keys; // Do not rename (binary serialization)
private TValue[] values; // Do not rename (binary serialization)
private int _size; // Do not rename (binary serialization)
private int version; // Do not rename (binary serialization)
private readonly IComparer<TKey> comparer; // Do not rename (binary serialization)
private KeyList? keyList; // Do not rename (binary serialization)
private ValueList? valueList; // Do not rename (binary serialization)
private const int DefaultCapacity = 4;
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to DefaultCapacity, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
public SortedList()
{
keys = Array.Empty<TKey>();
values = Array.Empty<TValue>();
_size = 0;
comparer = Comparer<TKey>.Default;
}
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
//
public SortedList(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
keys = new TKey[capacity];
values = new TValue[capacity];
comparer = Comparer<TKey>.Default;
}
// Constructs a new sorted list with a given IComparer
// implementation. The sorted list is initially empty and has a capacity of
// zero. Upon adding the first element to the sorted list the capacity is
// increased to 16, and then increased in multiples of two as required. The
// elements of the sorted list are ordered according to the given
// IComparer implementation. If comparer is null, the
// elements are compared to each other using the IComparable
// interface, which in that case must be implemented by the keys of all
// entries added to the sorted list.
//
public SortedList(IComparer<TKey>? comparer)
: this()
{
if (comparer != null)
{
this.comparer = comparer;
}
}
// Constructs a new sorted dictionary with a given IComparer
// implementation and a given initial capacity. The sorted list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required. The elements of the sorted list
// are ordered according to the given IComparer implementation. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented
// by the keys of all entries added to the sorted list.
//
public SortedList(int capacity, IComparer<TKey>? comparer)
: this(comparer)
{
Capacity = capacity;
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the IComparable interface, which must be implemented by the
// keys of all entries in the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary<TKey, TValue> dictionary)
: this(dictionary, null)
{
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the given IComparer implementation. If comparer is
// null, the elements are compared to each other using the
// IComparable interface, which in that case must be implemented
// by the keys of all entries in the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey>? comparer)
: this((dictionary != null ? dictionary.Count : 0), comparer)
{
if (dictionary == null)
throw new ArgumentNullException(nameof(dictionary));
int count = dictionary.Count;
if (count != 0)
{
TKey[] keys = this.keys;
dictionary.Keys.CopyTo(keys, 0);
dictionary.Values.CopyTo(values, 0);
Debug.Assert(count == this.keys.Length);
if (count > 1)
{
comparer = Comparer; // obtain default if this is null.
Array.Sort<TKey, TValue>(keys, values, comparer);
for (int i = 1; i != keys.Length; ++i)
{
if (comparer.Compare(keys[i - 1], keys[i]) == 0)
{
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, keys[i]));
}
}
}
}
_size = count;
}
// Adds an entry with the given key and value to this sorted list. An
// ArgumentException is thrown if the key is already present in the sorted list.
//
public void Add(TKey key, TValue value)
{
if (key == null) throw new ArgumentNullException(nameof(key));
int i = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer);
if (i >= 0)
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key), nameof(key));
Insert(~i, key, value);
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
{
Add(keyValuePair.Key, keyValuePair.Value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
int index = IndexOfKey(keyValuePair.Key);
if (index >= 0 && EqualityComparer<TValue>.Default.Equals(values[index], keyValuePair.Value))
{
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
int index = IndexOfKey(keyValuePair.Key);
if (index >= 0 && EqualityComparer<TValue>.Default.Equals(values[index], keyValuePair.Value))
{
RemoveAt(index);
return true;
}
return false;
}
// Returns the capacity of this sorted list. The capacity of a sorted list
// represents the allocated length of the internal arrays used to store the
// keys and values of the list, and thus also indicates the maximum number
// of entries the list can contain before a reallocation of the internal
// arrays is required.
//
public int Capacity
{
get
{
return keys.Length;
}
set
{
if (value != keys.Length)
{
if (value < _size)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_SmallCapacity);
}
if (value > 0)
{
TKey[] newKeys = new TKey[value];
TValue[] newValues = new TValue[value];
if (_size > 0)
{
Array.Copy(keys, 0, newKeys, 0, _size);
Array.Copy(values, 0, newValues, 0, _size);
}
keys = newKeys;
values = newValues;
}
else
{
keys = Array.Empty<TKey>();
values = Array.Empty<TValue>();
}
}
}
}
public IComparer<TKey> Comparer
{
get
{
return comparer;
}
}
void IDictionary.Add(object key, object? value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null && !(default(TValue)! == null)) // null is an invalid value for Value types // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
throw new ArgumentNullException(nameof(value));
if (!(key is TKey))
throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key));
if (!(value is TValue) && value != null) // null is a valid value for Reference Types
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value));
Add((TKey)key, (TValue)value!);
}
// Returns the number of entries in this sorted list.
public int Count
{
get
{
return _size;
}
}
// Returns a collection representing the keys of this sorted list. This
// method returns the same object as GetKeyList, but typed as an
// ICollection instead of an IList.
public IList<TKey> Keys
{
get
{
return GetKeyListHelper();
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
return GetKeyListHelper();
}
}
ICollection IDictionary.Keys
{
get
{
return GetKeyListHelper();
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
return GetKeyListHelper();
}
}
// Returns a collection representing the values of this sorted list. This
// method returns the same object as GetValueList, but typed as an
// ICollection instead of an IList.
//
public IList<TValue> Values
{
get
{
return GetValueListHelper();
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
return GetValueListHelper();
}
}
ICollection IDictionary.Values
{
get
{
return GetValueListHelper();
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
return GetValueListHelper();
}
}
private KeyList GetKeyListHelper()
{
if (keyList == null)
keyList = new KeyList(this);
return keyList;
}
private ValueList GetValueListHelper()
{
if (valueList == null)
valueList = new ValueList(this);
return valueList;
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
bool IDictionary.IsReadOnly
{
get { return false; }
}
bool IDictionary.IsFixedSize
{
get { return false; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
// Synchronization root for this object.
object ICollection.SyncRoot => this;
// Removes all entries from this sorted list.
public void Clear()
{
// clear does not change the capacity
version++;
// Don't need to doc this but we clear the elements so that the gc can reclaim the references.
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
Array.Clear(keys, 0, _size);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
Array.Clear(values, 0, _size);
}
_size = 0;
}
bool IDictionary.Contains(object key)
{
if (IsCompatibleKey(key))
{
return ContainsKey((TKey)key);
}
return false;
}
// Checks if this sorted list contains an entry with the given key.
public bool ContainsKey(TKey key)
{
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given value. The
// values of the entries of the sorted list are compared to the given value
// using the Object.Equals method. This method performs a linear
// search and is substantially slower than the Contains
// method.
public bool ContainsValue(TValue value)
{
return IndexOfValue(value) >= 0;
}
// Copies the values in this SortedList to an array.
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
if (array.Length - arrayIndex < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
for (int i = 0; i < Count; i++)
{
KeyValuePair<TKey, TValue> entry = new KeyValuePair<TKey, TValue>(keys[i], values[i]);
array[arrayIndex + i] = entry;
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (index < 0 || index > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey, TValue>[]? keyValuePairArray = array as KeyValuePair<TKey, TValue>[];
if (keyValuePairArray != null)
{
for (int i = 0; i < Count; i++)
{
keyValuePairArray[i + index] = new KeyValuePair<TKey, TValue>(keys[i], values[i]);
}
}
else
{
object[]? objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
try
{
for (int i = 0; i < Count; i++)
{
objects[i + index] = new KeyValuePair<TKey, TValue>(keys[i], values[i]);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
}
private const int MaxArrayLength = 0X7FEFFFFF;
// Ensures that the capacity of this sorted list is at least the given
// minimum value. If the current capacity of the list is less than
// min, the capacity is increased to twice the current capacity or
// to min, whichever is larger.
private void EnsureCapacity(int min)
{
int newCapacity = keys.Length == 0 ? DefaultCapacity : keys.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > MaxArrayLength) newCapacity = MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
// Returns the value of the entry at the given index.
private TValue GetByIndex(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
return values[index];
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new Enumerator(this, Enumerator.DictEntry);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
// Returns the key of the entry at the given index.
private TKey GetKey(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
return keys[index];
}
// Returns the value associated with the given key. If an entry with the
// given key is not found, the returned value is null.
public TValue this[TKey key]
{
get
{
int i = IndexOfKey(key);
if (i >= 0)
return values[i];
throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
}
set
{
if (((object)key) == null) throw new ArgumentNullException(nameof(key));
int i = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer);
if (i >= 0)
{
values[i] = value;
version++;
return;
}
Insert(~i, key, value);
}
}
object? IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
int i = IndexOfKey((TKey)key);
if (i >= 0)
{
return values[i];
}
}
return null;
}
set
{
if (!IsCompatibleKey(key))
{
throw new ArgumentNullException(nameof(key));
}
if (value == null && !(default(TValue)! == null)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
throw new ArgumentNullException(nameof(value));
TKey tempKey = (TKey)key;
try
{
this[tempKey] = (TValue)value!;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value));
}
}
}
// Returns the index of the entry with a given key in this sorted list. The
// key is located through a binary search, and thus the average execution
// time of this method is proportional to Log2(size), where
// size is the size of this sorted list. The returned value is -1 if
// the given key does not occur in this sorted list. Null is an invalid
// key value.
public int IndexOfKey(TKey key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
int ret = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer);
return ret >= 0 ? ret : -1;
}
// Returns the index of the first occurrence of an entry with a given value
// in this sorted list. The entry is located through a linear search, and
// thus the average execution time of this method is proportional to the
// size of this sorted list. The elements of the list are compared to the
// given value using the Object.Equals method.
public int IndexOfValue(TValue value)
{
return Array.IndexOf(values, value, 0, _size);
}
// Inserts an entry with a given key and value at a given index.
private void Insert(int index, TKey key, TValue value)
{
if (_size == keys.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(keys, index, keys, index + 1, _size - index);
Array.Copy(values, index, values, index + 1, _size - index);
}
keys[index] = key;
values[index] = value;
_size++;
version++;
}
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
{
int i = IndexOfKey(key);
if (i >= 0)
{
value = values[i];
return true;
}
value = default(TValue)!;
return false;
}
// Removes the entry at the given index. The size of the sorted list is
// decreased by one.
public void RemoveAt(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
_size--;
if (index < _size)
{
Array.Copy(keys, index + 1, keys, index, _size - index);
Array.Copy(values, index + 1, values, index, _size - index);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
keys[_size] = default(TKey)!;
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
values[_size] = default(TValue)!;
}
version++;
}
// Removes an entry from this sorted list. If an entry with the specified
// key exists in the sorted list, it is removed. An ArgumentException is
// thrown if the key is null.
public bool Remove(TKey key)
{
int i = IndexOfKey(key);
if (i >= 0)
RemoveAt(i);
return i >= 0;
}
void IDictionary.Remove(object key)
{
if (IsCompatibleKey(key))
{
Remove((TKey)key);
}
}
// Sets the capacity of this sorted list to the size of the sorted list.
// This method can be used to minimize a sorted list's memory overhead once
// it is known that no new elements will be added to the sorted list. To
// completely clear a sorted list and release all memory referenced by the
// sorted list, execute the following statements:
//
// SortedList.Clear();
// SortedList.TrimExcess();
public void TrimExcess()
{
int threshold = (int)(((double)keys.Length) * 0.9);
if (_size < threshold)
{
Capacity = _size;
}
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return (key is TKey);
}
private struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator
{
private readonly SortedList<TKey, TValue> _sortedList;
[AllowNull] private TKey _key;
[AllowNull] private TValue _value;
private int _index;
private readonly int _version;
private readonly int _getEnumeratorRetType; // What should Enumerator.Current return?
internal const int KeyValuePair = 1;
internal const int DictEntry = 2;
internal Enumerator(SortedList<TKey, TValue> sortedList, int getEnumeratorRetType)
{
_sortedList = sortedList;
_index = 0;
_version = _sortedList.version;
_getEnumeratorRetType = getEnumeratorRetType;
_key = default;
_value = default;
}
public void Dispose()
{
_index = 0;
_key = default;
_value = default;
}
object IDictionaryEnumerator.Key
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _key;
}
}
public bool MoveNext()
{
if (_version != _sortedList.version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if ((uint)_index < (uint)_sortedList.Count)
{
_key = _sortedList.keys[_index];
_value = _sortedList.values[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_key = default;
_value = default;
return false;
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return new DictionaryEntry(_key, _value);
}
}
public KeyValuePair<TKey, TValue> Current
{
get
{
return new KeyValuePair<TKey, TValue>(_key, _value);
}
}
object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
if (_getEnumeratorRetType == DictEntry)
{
return new DictionaryEntry(_key, _value);
}
else
{
return new KeyValuePair<TKey, TValue>(_key, _value);
}
}
}
object? IDictionaryEnumerator.Value
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _value;
}
}
void IEnumerator.Reset()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_key = default;
_value = default;
}
}
private sealed class SortedListKeyEnumerator : IEnumerator<TKey>, IEnumerator
{
private readonly SortedList<TKey, TValue> _sortedList;
private int _index;
private readonly int _version;
[AllowNull] private TKey _currentKey = default!;
internal SortedListKeyEnumerator(SortedList<TKey, TValue> sortedList)
{
_sortedList = sortedList;
_version = sortedList.version;
}
public void Dispose()
{
_index = 0;
_currentKey = default;
}
public bool MoveNext()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if ((uint)_index < (uint)_sortedList.Count)
{
_currentKey = _sortedList.keys[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_currentKey = default;
return false;
}
public TKey Current
{
get
{
return _currentKey;
}
}
object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _currentKey;
}
}
void IEnumerator.Reset()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_currentKey = default;
}
}
private sealed class SortedListValueEnumerator : IEnumerator<TValue>, IEnumerator
{
private readonly SortedList<TKey, TValue> _sortedList;
private int _index;
private readonly int _version;
[AllowNull] private TValue _currentValue = default!;
internal SortedListValueEnumerator(SortedList<TKey, TValue> sortedList)
{
_sortedList = sortedList;
_version = sortedList.version;
}
public void Dispose()
{
_index = 0;
_currentValue = default;
}
public bool MoveNext()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if ((uint)_index < (uint)_sortedList.Count)
{
_currentValue = _sortedList.values[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_currentValue = default;
return false;
}
public TValue Current
{
get
{
return _currentValue;
}
}
object? IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _currentValue;
}
}
void IEnumerator.Reset()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_currentValue = default;
}
}
[DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class KeyList : IList<TKey>, ICollection
{
private readonly SortedList<TKey, TValue> _dict; // Do not rename (binary serialization)
internal KeyList(SortedList<TKey, TValue> dictionary)
{
_dict = dictionary;
}
public int Count
{
get { return _dict._size; }
}
public bool IsReadOnly
{
get { return true; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_dict).SyncRoot; }
}
public void Add(TKey key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public void Clear()
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public bool Contains(TKey key)
{
return _dict.ContainsKey(key);
}
public void CopyTo(TKey[] array, int arrayIndex)
{
// defer error checking to Array.Copy
Array.Copy(_dict.keys, 0, array, arrayIndex, _dict.Count);
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
if (array != null && array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
try
{
// defer error checking to Array.Copy
Array.Copy(_dict.keys, 0, array!, arrayIndex, _dict.Count);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
public void Insert(int index, TKey value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public TKey this[int index]
{
get
{
return _dict.GetKey(index);
}
set
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
}
public IEnumerator<TKey> GetEnumerator()
{
return new SortedListKeyEnumerator(_dict);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new SortedListKeyEnumerator(_dict);
}
public int IndexOf(TKey key)
{
if (((object)key) == null)
throw new ArgumentNullException(nameof(key));
int i = Array.BinarySearch<TKey>(_dict.keys, 0,
_dict.Count, key, _dict.comparer);
if (i >= 0) return i;
return -1;
}
public bool Remove(TKey key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
// return false;
}
public void RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
[DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class ValueList : IList<TValue>, ICollection
{
private readonly SortedList<TKey, TValue> _dict; // Do not rename (binary serialization)
internal ValueList(SortedList<TKey, TValue> dictionary)
{
_dict = dictionary;
}
public int Count
{
get { return _dict._size; }
}
public bool IsReadOnly
{
get { return true; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_dict).SyncRoot; }
}
public void Add(TValue key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public void Clear()
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public bool Contains(TValue value)
{
return _dict.ContainsValue(value);
}
public void CopyTo(TValue[] array, int arrayIndex)
{
// defer error checking to Array.Copy
Array.Copy(_dict.values, 0, array, arrayIndex, _dict.Count);
}
void ICollection.CopyTo(Array array, int index)
{
if (array != null && array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
try
{
// defer error checking to Array.Copy
Array.Copy(_dict.values, 0, array!, index, _dict.Count);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
public void Insert(int index, TValue value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public TValue this[int index]
{
get
{
return _dict.GetByIndex(index);
}
set
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
public IEnumerator<TValue> GetEnumerator()
{
return new SortedListValueEnumerator(_dict);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new SortedListValueEnumerator(_dict);
}
public int IndexOf(TValue value)
{
return Array.IndexOf(_dict.values, value, 0, _dict.Count);
}
public bool Remove(TValue value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
// return false;
}
public void RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.