context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Diagnostics;
namespace RCube
{
public class Cube : ICloneable
{
public int[,] Sides;
public int this[int i, int j]
{
get { return Sides[i, j]; }
}
public Cube(bool populate)
{
Sides = new int[6,8];
if(populate)
{
Populate();
}
}
private Cube(int[,] sides)
{
Sides = sides;
}
private void Populate()
{
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 8; j++)
{
Sides[i, j] = i;
}
}
}
public void RotateSide(int side, bool reverse)
{
int[][,] rotations = GetRotations(side);
for (int j = 0; j < 5; j++)
{
if (!reverse)
{
int t = Sides[rotations[j][0, 3], rotations[j][1, 3]];
for (int q = 3; q > 0; q--)
{
Sides[rotations[j][0, q], rotations[j][1, q]] =
Sides[rotations[j][0, q - 1], rotations[j][1, q - 1]];
}
Sides[rotations[j][0, 0], rotations[j][1, 0]] = t;
}
else
{
int t = Sides[rotations[j][0, 0], rotations[j][1, 0]];
for (int q = 1; q < 4; q++)
{
Sides[rotations[j][0, q - 1], rotations[j][1, q - 1]] =
Sides[rotations[j][0, q], rotations[j][1, q]];
}
Sides[rotations[j][0, 3], rotations[j][1, 3]] = t;
}
}
}
public int[] GetNeighbors(int side)
{
int[] sides = new int[4];
for (int i = 0; i < 4; i++)
{
sides[i] = ROTATION_NEIGHBORS[side, i];
}
return sides;
}
public static void GetEdgeNeighbor0(int side, int piece, out int side1, out int piece1)
{
side1 = ROTATION_NEIGHBORS[side, piece / 2];
if (piece == 1 || piece == 7)
piece1 = 8 - piece;
else
piece1 = piece;
}
public static void GetCornerNeighbor0(int side, int piece, out int side1, out int piece1, out int side2, out int piece2)
{
side1 = ROTATION_NEIGHBORS[side, (piece / 2 + 3) % 4];
side2 = ROTATION_NEIGHBORS[side, piece / 2];
if (piece == 0)
piece1 = piece2 = 0;
else
piece1 = (piece2 = piece % 6 + 2) % 6 + 2;
}
public static int[,] RotationNeighbors
{
get { return ROTATION_NEIGHBORS; }
}
public static int[,] RightSideForUpAndFront
{
get { return RIGHT_SIDE_FOR_UP_FRONT; }
}
private static int[,] ROTATION_NEIGHBORS =
{ { 2, 4, 5, 1 }, { 0, 5, 3, 2 }, { 1, 3, 4, 0 }, { 4, 2, 1, 5 }, { 5, 0, 2, 3 }, { 3, 1, 0, 4} };
private static int[,] ROTATION_SERIES =
{ { 0, 2, 4, 6 }, { 1, 3, 5, 7 }, { 0, 4, 6, 2 }, { 7, 3, 5, 1 }, { 6, 2, 4, 0 } };
private static int[,] RIGHT_SIDE_FOR_UP_FRONT = {
{-1,5,1,-1,2,4},
{2,-1,3,5,-1,0},
{4,0,-1,1,3,-1},
{-1,2,4,-1,5,1},
{5,-1,0,2,-1,3},
{1,3,-1,4,0,-1}};
public static int[][,] GetRotations(int side)
{
int[][,] results = new int[5][,];
for (int i = 0; i < 2; i++)
{
int[,] r = new int[2, 4];
for (int j = 0; j < 4; j++)
{
r[0, j] = side;
r[1, j] = ROTATION_SERIES[i, j];
}
results[i] = r;
}
for (int i = 0; i < 3; i++)
{
int[,] r = new int[2, 4];
for (int j = 0; j < 4; j++)
{
r[0, j] = ROTATION_NEIGHBORS[side, j];
r[1, j] = ROTATION_SERIES[i + 2, j];
}
results[i + 2] = r;
}
return results;
}
#region ICloneable Members
public object Clone()
{
return new Cube((int[,])Sides.Clone());
}
#endregion
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public string[] FieldDisplay
{
get
{
StringBuilder sb = new StringBuilder();
sb.Append(" ").Append(Sides[5, 6]).Append(Sides[5, 7]).Append(Sides[5, 0]).Append("\r");
sb.Append(" ").Append(Sides[5, 5]).Append('5').Append(Sides[5, 1]).Append("\r");
sb.Append(" ").Append(Sides[5, 4]).Append(Sides[5, 3]).Append(Sides[5, 2]).Append("\r");
sb.Append(Sides[0, 4]).Append(Sides[0, 5]).Append(Sides[0, 6]).Append(Sides[1, 2]).Append(Sides[1, 3]).Append(Sides[1, 4]).Append(Sides[3, 6]).Append(Sides[3, 7]).Append(Sides[3, 0]).Append(Sides[4, 0]).Append(Sides[4, 1]).Append(Sides[4, 2]).Append("\r");
sb.Append(Sides[0, 3]).Append('0').Append(Sides[0, 7]).Append(Sides[1, 1]).Append('1').Append(Sides[1, 5]).Append(Sides[3, 5]).Append('3').Append(Sides[3, 1]).Append(Sides[4, 7]).Append('4').Append(Sides[4, 3]).Append("\r");
sb.Append(Sides[0, 2]).Append(Sides[0, 1]).Append(Sides[0, 0]).Append(Sides[1, 0]).Append(Sides[1, 7]).Append(Sides[1, 6]).Append(Sides[3, 4]).Append(Sides[3, 3]).Append(Sides[3, 2]).Append(Sides[4, 6]).Append(Sides[4, 5]).Append(Sides[4, 4]).Append("\r");
sb.Append(" ").Append(Sides[2, 0]).Append(Sides[2, 1]).Append(Sides[2, 2]).Append("\r");
sb.Append(" ").Append(Sides[2, 7]).Append('2').Append(Sides[2, 3]).Append("\r");
sb.Append(" ").Append(Sides[2, 6]).Append(Sides[2, 5]).Append(Sides[2, 4]);
return sb.ToString().Split('\r');
}
}
}
public struct CubeNavigator
{
public Cube Cube;
public int Side;
public int Piece;
public CubeNavigator(Cube cube, int side, int piece)
{
this.Cube = cube;
this.Side = side;
this.Piece = piece;
}
public CubePieceType Type
{
get
{
switch (Piece)
{
case 1: case 3: case 5: case 7:
return CubePieceType.Edge;
case 0: case 2: case 4: case 6:
return CubePieceType.Corner;
default:
return CubePieceType.Middle;
}
}
}
public int Value
{
get { return this.Cube[Side, Piece]; }
}
public void MoveNextSide()
{
if (Piece >= 8)
throw new InvalidOperationException("Not next side for middle piece");
else if ((Piece & 1) == 0)
{
// corner
Side = Cube.RotationNeighbors[Side, (Piece / 2 + 3) % 4];
if (Piece != 0) Piece = (Piece % 6 + 2) % 6 + 2;
}
else
{
Side = Cube.RotationNeighbors[Side, Piece / 2];
if (Piece == 1 || Piece == 7) Piece = 8 - Piece;
}
}
public void MovePrevSide()
{
if (Piece >= 8)
throw new InvalidOperationException("Not next side for middle piece");
else if ((Piece & 1) == 0)
{
// corner
Side = Cube.RotationNeighbors[Side, Piece / 2];
if (Piece != 0) Piece = Piece % 6 + 2;
}
else
{
Side = Cube.RotationNeighbors[Side, Piece / 2];
if (Piece == 1 || Piece == 7) Piece = 8 - Piece;
}
}
public void MoveBy(int step)
{
Piece = (Piece + step) & 7;
}
public void MoveNext()
{
MoveBy(1);
}
public void MovePrev()
{
MoveBy(-1);
}
public void Move(bool nextSide, int step)
{
if (nextSide) MoveNextSide(); else MovePrevSide();
MoveBy(step);
}
public void Move(int step, bool nextSide)
{
MoveBy(step);
if (nextSide) MoveNextSide(); else MovePrevSide();
}
public void Move(bool nextSide, int step, bool nextSide2)
{
Move(nextSide, step);
if (nextSide2) MoveNextSide(); else MovePrevSide();
}
public void Move(int step, bool nextSide, int step2)
{
Move(step, nextSide);
MoveBy(step2);
}
}
public enum CubePieceType
{
Edge,
Corner,
Middle
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// HeaderOperations operations.
/// </summary>
internal partial class HeaderOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IHeaderOperations
{
/// <summary>
/// Initializes a new instance of the HeaderOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal HeaderOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the
/// header of the request
/// </summary>
/// <param name='fooClientRequestId'>
/// The fooRequestId
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationHeaderResponse<HeaderCustomNamedRequestIdHeaders>> CustomNamedRequestIdWithHttpMessagesAsync(string fooClientRequestId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (fooClientRequestId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fooClientRequestId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fooClientRequestId", fooClientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CustomNamedRequestId", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/customNamedRequestId").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", Guid.NewGuid().ToString());
}
if (fooClientRequestId != null)
{
if (_httpRequest.Headers.Contains("foo-client-request-id"))
{
_httpRequest.Headers.Remove("foo-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", fooClientRequestId);
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationHeaderResponse<HeaderCustomNamedRequestIdHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("foo-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("foo-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HeaderCustomNamedRequestIdHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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;
using System.Xml.Schema;
using System.Xml;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Diagnostics;
using System.CodeDom.Compiler;
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class SoapSchemaImporter : SchemaImporter
{
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.SoapSchemaImporter"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SoapSchemaImporter(XmlSchemas schemas) : base(schemas, CodeGenerationOptions.GenerateProperties, null, new ImportContext()) { }
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.SoapSchemaImporter1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SoapSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers) : base(schemas, CodeGenerationOptions.GenerateProperties, null, new ImportContext(typeIdentifiers, false)) { }
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.SoapSchemaImporter2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SoapSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers, CodeGenerationOptions options) : base(schemas, options, null, new ImportContext(typeIdentifiers, false)) { }
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.SoapSchemaImporter3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SoapSchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, ImportContext context) : base(schemas, options, null, context) { }
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.SoapSchemaImporter4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
internal SoapSchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, CodeDomProvider codeProvider, ImportContext context) : base(schemas, options, codeProvider, context) { }
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.ImportDerivedTypeMapping"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type baseType, bool baseTypeCanBeIndirect)
{
TypeMapping mapping = ImportType(name, false);
if (mapping is StructMapping)
{
MakeDerived((StructMapping)mapping, baseType, baseTypeCanBeIndirect);
}
else if (baseType != null)
throw new InvalidOperationException(SR.Format(SR.XmlPrimitiveBaseType, name.Name, name.Namespace, baseType.FullName));
ElementAccessor accessor = new ElementAccessor();
accessor.IsSoap = true;
accessor.Name = name.Name;
accessor.Namespace = name.Namespace;
accessor.Mapping = mapping;
accessor.IsNullable = true;
accessor.Form = XmlSchemaForm.Qualified;
return new XmlTypeMapping(Scope, accessor);
}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.ImportMembersMapping"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchemaMember member)
{
TypeMapping typeMapping = ImportType(member.MemberType, true);
if (!(typeMapping is StructMapping)) return ImportMembersMapping(name, ns, new SoapSchemaMember[] { member });
MembersMapping mapping = new MembersMapping();
mapping.TypeDesc = Scope.GetTypeDesc(typeof(object[]));
mapping.Members = ((StructMapping)typeMapping).Members;
mapping.HasWrapperElement = true;
ElementAccessor accessor = new ElementAccessor();
accessor.IsSoap = true;
accessor.Name = name;
accessor.Namespace = typeMapping.Namespace != null ? typeMapping.Namespace : ns;
accessor.Mapping = mapping;
accessor.IsNullable = false;
accessor.Form = XmlSchemaForm.Qualified;
return new XmlMembersMapping(Scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write);
}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.ImportMembersMapping1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchemaMember[] members)
{
return ImportMembersMapping(name, ns, members, true);
}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.ImportMembersMapping2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchemaMember[] members, bool hasWrapperElement)
{
return ImportMembersMapping(name, ns, members, hasWrapperElement, null, false);
}
/// <include file='doc\SoapSchemaImporter.uex' path='docs/doc[@for="SoapSchemaImporter.ImportMembersMapping3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchemaMember[] members, bool hasWrapperElement, Type baseType, bool baseTypeCanBeIndirect)
{
XmlSchemaComplexType type = new XmlSchemaComplexType();
XmlSchemaSequence seq = new XmlSchemaSequence();
type.Particle = seq;
foreach (SoapSchemaMember member in members)
{
XmlSchemaElement element = new XmlSchemaElement();
element.Name = member.MemberName;
element.SchemaTypeName = member.MemberType;
seq.Items.Add(element);
}
CodeIdentifiers identifiers = new CodeIdentifiers();
identifiers.UseCamelCasing = true;
MembersMapping mapping = new MembersMapping();
mapping.TypeDesc = Scope.GetTypeDesc(typeof(object[]));
mapping.Members = ImportTypeMembers(type, ns, identifiers);
mapping.HasWrapperElement = hasWrapperElement;
if (baseType != null)
{
for (int i = 0; i < mapping.Members.Length; i++)
{
MemberMapping member = mapping.Members[i];
if (member.Accessor.Mapping is StructMapping)
MakeDerived((StructMapping)member.Accessor.Mapping, baseType, baseTypeCanBeIndirect);
}
}
ElementAccessor accessor = new ElementAccessor();
accessor.IsSoap = true;
accessor.Name = name;
accessor.Namespace = ns;
accessor.Mapping = mapping;
accessor.IsNullable = false;
accessor.Form = XmlSchemaForm.Qualified;
return new XmlMembersMapping(Scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write);
}
private ElementAccessor ImportElement(XmlSchemaElement element, string ns)
{
if (!element.RefName.IsEmpty)
{
throw new InvalidOperationException(SR.Format(SR.RefSyntaxNotSupportedForElements0, element.RefName.Name, element.RefName.Namespace));
}
if (element.Name.Length == 0)
{
XmlQualifiedName parentType = XmlSchemas.GetParentName(element);
throw new InvalidOperationException(SR.Format(SR.XmlElementHasNoName, parentType.Name, parentType.Namespace));
}
TypeMapping mapping = ImportElementType(element, ns);
ElementAccessor accessor = new ElementAccessor();
accessor.IsSoap = true;
accessor.Name = element.Name;
accessor.Namespace = ns;
accessor.Mapping = mapping;
accessor.IsNullable = element.IsNillable;
accessor.Form = XmlSchemaForm.None;
return accessor;
}
private TypeMapping ImportElementType(XmlSchemaElement element, string ns)
{
TypeMapping mapping;
if (!element.SchemaTypeName.IsEmpty)
mapping = ImportType(element.SchemaTypeName, false);
else if (element.SchemaType != null)
{
XmlQualifiedName parentType = XmlSchemas.GetParentName(element);
if (element.SchemaType is XmlSchemaComplexType)
{
mapping = ImportType((XmlSchemaComplexType)element.SchemaType, ns, false);
if (!(mapping is ArrayMapping))
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidSchemaElementType, parentType.Name, parentType.Namespace, element.Name));
}
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidSchemaElementType, parentType.Name, parentType.Namespace, element.Name));
}
}
else if (!element.SubstitutionGroup.IsEmpty)
{
XmlQualifiedName parentType = XmlSchemas.GetParentName(element);
throw new InvalidOperationException(SR.Format(SR.XmlInvalidSubstitutionGroupUse, parentType.Name, parentType.Namespace));
}
else
{
XmlQualifiedName parentType = XmlSchemas.GetParentName(element);
throw new InvalidOperationException(SR.Format(SR.XmlElementMissingType, parentType.Name, parentType.Namespace, element.Name));
}
mapping.ReferencedByElement = true;
return mapping;
}
internal override void ImportDerivedTypes(XmlQualifiedName baseName)
{
foreach (XmlSchema schema in Schemas)
{
if (Schemas.IsReference(schema)) continue;
if (XmlSchemas.IsDataSet(schema)) continue;
XmlSchemas.Preprocess(schema);
foreach (object item in schema.SchemaTypes.Values)
{
if (item is XmlSchemaType)
{
XmlSchemaType type = (XmlSchemaType)item;
if (type.DerivedFrom == baseName)
{
ImportType(type.QualifiedName, false);
}
}
}
}
}
private TypeMapping ImportType(XmlQualifiedName name, bool excludeFromImport)
{
if (name.Name == Soap.UrType && name.Namespace == XmlSchema.Namespace)
return ImportRootMapping();
object type = FindType(name);
TypeMapping mapping = (TypeMapping)ImportedMappings[type];
if (mapping == null)
{
if (type is XmlSchemaComplexType)
mapping = ImportType((XmlSchemaComplexType)type, name.Namespace, excludeFromImport);
else if (type is XmlSchemaSimpleType)
mapping = ImportDataType((XmlSchemaSimpleType)type, name.Namespace, name.Name, false);
else
throw new InvalidOperationException(SR.XmlInternalError);
}
if (excludeFromImport)
mapping.IncludeInSchema = false;
return mapping;
}
private TypeMapping ImportType(XmlSchemaComplexType type, string typeNs, bool excludeFromImport)
{
if (type.Redefined != null)
{
// we do not support redefine in the current version
throw new NotSupportedException(SR.Format(SR.XmlUnsupportedRedefine, type.Name, typeNs));
}
TypeMapping mapping = ImportAnyType(type, typeNs);
if (mapping == null)
mapping = ImportArrayMapping(type, typeNs);
if (mapping == null)
mapping = ImportStructType(type, typeNs, excludeFromImport);
return mapping;
}
private TypeMapping ImportAnyType(XmlSchemaComplexType type, string typeNs)
{
if (type.Particle == null)
return null;
if (!(type.Particle is XmlSchemaAll || type.Particle is XmlSchemaSequence))
return null;
XmlSchemaGroupBase group = (XmlSchemaGroupBase)type.Particle;
if (group.Items.Count != 1 || !(group.Items[0] is XmlSchemaAny))
return null;
return ImportRootMapping();
}
private StructMapping ImportStructType(XmlSchemaComplexType type, string typeNs, bool excludeFromImport)
{
if (type.Name == null)
{
XmlSchemaElement element = (XmlSchemaElement)type.Parent;
XmlQualifiedName parentType = XmlSchemas.GetParentName(element);
throw new InvalidOperationException(SR.Format(SR.XmlInvalidSchemaElementType, parentType.Name, parentType.Namespace, element.Name));
}
TypeDesc baseTypeDesc = null;
Mapping baseMapping = null;
if (!type.DerivedFrom.IsEmpty)
{
baseMapping = ImportType(type.DerivedFrom, excludeFromImport);
if (baseMapping is StructMapping)
baseTypeDesc = ((StructMapping)baseMapping).TypeDesc;
else
baseMapping = null;
}
if (baseMapping == null) baseMapping = GetRootMapping();
Mapping previousMapping = (Mapping)ImportedMappings[type];
if (previousMapping != null)
{
return (StructMapping)previousMapping;
}
string typeName = GenerateUniqueTypeName(Accessor.UnescapeName(type.Name));
StructMapping structMapping = new StructMapping();
structMapping.IsReference = Schemas.IsReference(type);
TypeFlags flags = TypeFlags.Reference;
if (type.IsAbstract) flags |= TypeFlags.Abstract;
structMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Struct, baseTypeDesc, flags);
structMapping.Namespace = typeNs;
structMapping.TypeName = type.Name;
structMapping.BaseMapping = (StructMapping)baseMapping;
ImportedMappings.Add(type, structMapping);
if (excludeFromImport)
structMapping.IncludeInSchema = false;
CodeIdentifiers members = new CodeIdentifiers();
members.AddReserved(typeName);
AddReservedIdentifiersForDataBinding(members);
structMapping.Members = ImportTypeMembers(type, typeNs, members);
Scope.AddTypeMapping(structMapping);
ImportDerivedTypes(new XmlQualifiedName(type.Name, typeNs));
return structMapping;
}
private MemberMapping[] ImportTypeMembers(XmlSchemaComplexType type, string typeNs, CodeIdentifiers members)
{
if (type.AnyAttribute != null)
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidAnyAttributeUse, type.Name, type.QualifiedName.Namespace));
}
XmlSchemaObjectCollection items = type.Attributes;
for (int i = 0; i < items.Count; i++)
{
object item = items[i];
if (item is XmlSchemaAttributeGroup)
{
throw new InvalidOperationException(SR.Format(SR.XmlSoapInvalidAttributeUse, type.Name, type.QualifiedName.Namespace));
}
if (item is XmlSchemaAttribute)
{
XmlSchemaAttribute attr = (XmlSchemaAttribute)item;
if (attr.Use != XmlSchemaUse.Prohibited) throw new InvalidOperationException(SR.Format(SR.XmlSoapInvalidAttributeUse, type.Name, type.QualifiedName.Namespace));
}
}
if (type.Particle != null)
{
ImportGroup(type.Particle, members, typeNs);
}
else if (type.ContentModel != null && type.ContentModel is XmlSchemaComplexContent)
{
XmlSchemaComplexContent model = (XmlSchemaComplexContent)type.ContentModel;
if (model.Content is XmlSchemaComplexContentExtension)
{
if (((XmlSchemaComplexContentExtension)model.Content).Particle != null)
{
ImportGroup(((XmlSchemaComplexContentExtension)model.Content).Particle, members, typeNs);
}
}
else if (model.Content is XmlSchemaComplexContentRestriction)
{
if (((XmlSchemaComplexContentRestriction)model.Content).Particle != null)
{
ImportGroup(((XmlSchemaComplexContentRestriction)model.Content).Particle, members, typeNs);
}
}
}
return (MemberMapping[])members.ToArray(typeof(MemberMapping));
}
private void ImportGroup(XmlSchemaParticle group, CodeIdentifiers members, string ns)
{
if (group is XmlSchemaChoice)
{
XmlQualifiedName parentType = XmlSchemas.GetParentName(group);
throw new InvalidOperationException(SR.Format(SR.XmlSoapInvalidChoice, parentType.Name, parentType.Namespace));
}
else
ImportGroupMembers(group, members, ns);
}
private void ImportGroupMembers(XmlSchemaParticle particle, CodeIdentifiers members, string ns)
{
XmlQualifiedName parentType = XmlSchemas.GetParentName(particle);
if (particle is XmlSchemaGroupRef)
{
throw new InvalidOperationException(SR.Format(SR.XmlSoapUnsupportedGroupRef, parentType.Name, parentType.Namespace));
}
else if (particle is XmlSchemaGroupBase)
{
XmlSchemaGroupBase group = (XmlSchemaGroupBase)particle;
if (group.IsMultipleOccurrence)
throw new InvalidOperationException(SR.Format(SR.XmlSoapUnsupportedGroupRepeat, parentType.Name, parentType.Namespace));
for (int i = 0; i < group.Items.Count; i++)
{
object item = group.Items[i];
if (item is XmlSchemaGroupBase || item is XmlSchemaGroupRef)
throw new InvalidOperationException(SR.Format(SR.XmlSoapUnsupportedGroupNested, parentType.Name, parentType.Namespace));
else if (item is XmlSchemaElement)
ImportElementMember((XmlSchemaElement)item, members, ns);
else if (item is XmlSchemaAny)
throw new InvalidOperationException(SR.Format(SR.XmlSoapUnsupportedGroupAny, parentType.Name, parentType.Namespace));
}
}
}
private ElementAccessor ImportArray(XmlSchemaElement element, string ns)
{
if (element.SchemaType == null) return null;
if (!element.IsMultipleOccurrence) return null;
XmlSchemaType type = element.SchemaType;
ArrayMapping arrayMapping = ImportArrayMapping(type, ns);
if (arrayMapping == null) return null;
ElementAccessor arrayAccessor = new ElementAccessor();
arrayAccessor.IsSoap = true;
arrayAccessor.Name = element.Name;
arrayAccessor.Namespace = ns;
arrayAccessor.Mapping = arrayMapping;
arrayAccessor.IsNullable = false;
arrayAccessor.Form = XmlSchemaForm.None;
return arrayAccessor;
}
private ArrayMapping ImportArrayMapping(XmlSchemaType type, string ns)
{
ArrayMapping arrayMapping;
if (type.Name == Soap.Array && ns == Soap.Encoding)
{
arrayMapping = new ArrayMapping();
TypeMapping mapping = GetRootMapping();
ElementAccessor itemAccessor = new ElementAccessor();
itemAccessor.IsSoap = true;
itemAccessor.Name = Soap.UrType;
itemAccessor.Namespace = ns;
itemAccessor.Mapping = mapping;
itemAccessor.IsNullable = true;
itemAccessor.Form = XmlSchemaForm.None;
arrayMapping.Elements = new ElementAccessor[] { itemAccessor };
arrayMapping.TypeDesc = itemAccessor.Mapping.TypeDesc.CreateArrayTypeDesc();
arrayMapping.TypeName = "ArrayOf" + CodeIdentifier.MakePascal(itemAccessor.Mapping.TypeName);
return arrayMapping;
}
if (!(type.DerivedFrom.Name == Soap.Array && type.DerivedFrom.Namespace == Soap.Encoding)) return null;
// the type should be a XmlSchemaComplexType
XmlSchemaContentModel model = ((XmlSchemaComplexType)type).ContentModel;
// the Content should be an restriction
if (!(model.Content is XmlSchemaComplexContentRestriction)) return null;
arrayMapping = new ArrayMapping();
XmlSchemaComplexContentRestriction restriction = (XmlSchemaComplexContentRestriction)model.Content;
for (int i = 0; i < restriction.Attributes.Count; i++)
{
XmlSchemaAttribute attribute = restriction.Attributes[i] as XmlSchemaAttribute;
if (attribute != null && attribute.RefName.Name == Soap.ArrayType && attribute.RefName.Namespace == Soap.Encoding)
{
// read the value of the wsdl:arrayType attribute
string arrayType = null;
if (attribute.UnhandledAttributes != null)
{
foreach (XmlAttribute a in attribute.UnhandledAttributes)
{
if (a.LocalName == Wsdl.ArrayType && a.NamespaceURI == Wsdl.Namespace)
{
arrayType = a.Value;
break;
}
}
}
if (arrayType != null)
{
string dims;
XmlQualifiedName typeName = TypeScope.ParseWsdlArrayType(arrayType, out dims, attribute);
TypeMapping mapping;
TypeDesc td = Scope.GetTypeDesc(typeName.Name, typeName.Namespace);
if (td != null && td.IsPrimitive)
{
mapping = new PrimitiveMapping();
mapping.TypeDesc = td;
mapping.TypeName = td.DataType.Name;
}
else
{
mapping = ImportType(typeName, false);
}
ElementAccessor itemAccessor = new ElementAccessor();
itemAccessor.IsSoap = true;
itemAccessor.Name = typeName.Name;
itemAccessor.Namespace = ns;
itemAccessor.Mapping = mapping;
itemAccessor.IsNullable = true;
itemAccessor.Form = XmlSchemaForm.None;
arrayMapping.Elements = new ElementAccessor[] { itemAccessor };
arrayMapping.TypeDesc = itemAccessor.Mapping.TypeDesc.CreateArrayTypeDesc();
arrayMapping.TypeName = "ArrayOf" + CodeIdentifier.MakePascal(itemAccessor.Mapping.TypeName);
return arrayMapping;
}
}
}
XmlSchemaParticle particle = restriction.Particle;
if (particle is XmlSchemaAll || particle is XmlSchemaSequence)
{
XmlSchemaGroupBase group = (XmlSchemaGroupBase)particle;
if (group.Items.Count != 1 || !(group.Items[0] is XmlSchemaElement))
return null;
XmlSchemaElement itemElement = (XmlSchemaElement)group.Items[0];
if (!itemElement.IsMultipleOccurrence) return null;
ElementAccessor itemAccessor = ImportElement(itemElement, ns);
arrayMapping.Elements = new ElementAccessor[] { itemAccessor };
arrayMapping.TypeDesc = ((TypeMapping)itemAccessor.Mapping).TypeDesc.CreateArrayTypeDesc();
}
else
{
return null;
}
return arrayMapping;
}
private void ImportElementMember(XmlSchemaElement element, CodeIdentifiers members, string ns)
{
ElementAccessor accessor;
if ((accessor = ImportArray(element, ns)) == null)
{
accessor = ImportElement(element, ns);
}
MemberMapping member = new MemberMapping();
member.Name = CodeIdentifier.MakeValid(Accessor.UnescapeName(accessor.Name));
member.Name = members.AddUnique(member.Name, member);
if (member.Name.EndsWith("Specified", StringComparison.Ordinal))
{
string name = member.Name;
member.Name = members.AddUnique(member.Name, member);
members.Remove(name);
}
member.TypeDesc = ((TypeMapping)accessor.Mapping).TypeDesc;
member.Elements = new ElementAccessor[] { accessor };
if (element.IsMultipleOccurrence)
member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc();
if (element.MinOccurs == 0 && member.TypeDesc.IsValueType && !member.TypeDesc.HasIsEmpty)
{
member.CheckSpecified = SpecifiedAccessor.ReadWrite;
}
}
private TypeMapping ImportDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, bool isList)
{
TypeMapping mapping = ImportNonXsdPrimitiveDataType(dataType, typeNs);
if (mapping != null)
return mapping;
if (dataType.Content is XmlSchemaSimpleTypeRestriction)
{
XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)dataType.Content;
foreach (object o in restriction.Facets)
{
if (o is XmlSchemaEnumerationFacet)
{
return ImportEnumeratedDataType(dataType, typeNs, identifier, isList);
}
}
}
else if (dataType.Content is XmlSchemaSimpleTypeList || dataType.Content is XmlSchemaSimpleTypeUnion)
{
if (dataType.Content is XmlSchemaSimpleTypeList)
{
// check if we have enumeration list
XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)dataType.Content;
if (list.ItemType != null)
{
mapping = ImportDataType(list.ItemType, typeNs, identifier, true);
if (mapping != null)
{
return mapping;
}
}
}
mapping = new PrimitiveMapping();
mapping.TypeDesc = Scope.GetTypeDesc(typeof(string));
mapping.TypeName = mapping.TypeDesc.DataType.Name;
return mapping;
}
return ImportPrimitiveDataType(dataType);
}
private TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, bool isList)
{
TypeMapping mapping = (TypeMapping)ImportedMappings[dataType];
if (mapping != null)
return mapping;
XmlSchemaSimpleType sourceDataType = FindDataType(dataType.DerivedFrom);
TypeDesc sourceTypeDesc = Scope.GetTypeDesc(sourceDataType);
if (sourceTypeDesc != null && sourceTypeDesc != Scope.GetTypeDesc(typeof(string)))
return ImportPrimitiveDataType(dataType);
identifier = Accessor.UnescapeName(identifier);
string typeName = GenerateUniqueTypeName(identifier);
EnumMapping enumMapping = new EnumMapping();
enumMapping.IsReference = Schemas.IsReference(dataType);
enumMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0);
enumMapping.TypeName = identifier;
enumMapping.Namespace = typeNs;
enumMapping.IsFlags = isList;
CodeIdentifiers constants = new CodeIdentifiers();
if (!(dataType.Content is XmlSchemaSimpleTypeRestriction))
throw new InvalidOperationException(SR.Format(SR.XmlInvalidEnumContent, dataType.Content.GetType().Name, identifier));
XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)dataType.Content;
for (int i = 0; i < restriction.Facets.Count; i++)
{
object facet = restriction.Facets[i];
if (!(facet is XmlSchemaEnumerationFacet)) continue;
XmlSchemaEnumerationFacet enumeration = (XmlSchemaEnumerationFacet)facet;
ConstantMapping constant = new ConstantMapping();
string constantName = CodeIdentifier.MakeValid(enumeration.Value);
constant.Name = constants.AddUnique(constantName, constant);
constant.XmlName = enumeration.Value;
constant.Value = i;
}
enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
if (isList && enumMapping.Constants.Length > 63)
{
// if we have 64+ flag constants we cannot map the type to long enum, we will use string mapping instead.
mapping = new PrimitiveMapping();
mapping.TypeDesc = Scope.GetTypeDesc(typeof(string));
mapping.TypeName = mapping.TypeDesc.DataType.Name;
ImportedMappings.Add(dataType, mapping);
return mapping;
}
ImportedMappings.Add(dataType, enumMapping);
Scope.AddTypeMapping(enumMapping);
return enumMapping;
}
private PrimitiveMapping ImportPrimitiveDataType(XmlSchemaSimpleType dataType)
{
TypeDesc sourceTypeDesc = GetDataTypeSource(dataType);
PrimitiveMapping mapping = new PrimitiveMapping();
mapping.TypeDesc = sourceTypeDesc;
mapping.TypeName = sourceTypeDesc.DataType.Name;
return mapping;
}
private PrimitiveMapping ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataType, string ns)
{
PrimitiveMapping mapping = null;
TypeDesc typeDesc = null;
if (dataType.Name != null && dataType.Name.Length != 0)
{
typeDesc = Scope.GetTypeDesc(dataType.Name, ns);
if (typeDesc != null)
{
mapping = new PrimitiveMapping();
mapping.TypeDesc = typeDesc;
mapping.TypeName = typeDesc.DataType.Name;
}
}
return mapping;
}
private TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType)
{
if (dataType.Name != null && dataType.Name.Length != 0)
{
TypeDesc typeDesc = Scope.GetTypeDesc(dataType);
if (typeDesc != null) return typeDesc;
}
if (!dataType.DerivedFrom.IsEmpty)
{
return GetDataTypeSource(FindDataType(dataType.DerivedFrom));
}
return Scope.GetTypeDesc(typeof(string));
}
private XmlSchemaSimpleType FindDataType(XmlQualifiedName name)
{
TypeDesc typeDesc = Scope.GetTypeDesc(name.Name, name.Namespace);
if (typeDesc != null && typeDesc.DataType is XmlSchemaSimpleType)
return (XmlSchemaSimpleType)typeDesc.DataType;
XmlSchemaSimpleType dataType = (XmlSchemaSimpleType)Schemas.Find(name, typeof(XmlSchemaSimpleType));
if (dataType != null)
{
return dataType;
}
if (name.Namespace == XmlSchema.Namespace)
return (XmlSchemaSimpleType)Scope.GetTypeDesc(typeof(string)).DataType;
else
throw new InvalidOperationException(SR.Format(SR.XmlMissingDataType, name.ToString()));
}
private object FindType(XmlQualifiedName name)
{
if (name != null && name.Namespace == Soap.Encoding)
{
// we have a build-in support fo the encoded types, we need to make sure that we generate the same
// object model whether http://www.w3.org/2003/05/soap-encoding schema was specified or not.
object type = Schemas.Find(name, typeof(XmlSchemaComplexType));
if (type != null)
{
XmlSchemaType encType = (XmlSchemaType)type;
XmlQualifiedName baseType = encType.DerivedFrom;
if (!baseType.IsEmpty)
{
return FindType(baseType);
}
return encType;
}
return FindDataType(name);
}
else
{
object type = Schemas.Find(name, typeof(XmlSchemaComplexType));
if (type != null)
{
return type;
}
return FindDataType(name);
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web.Script.Serialization;
using System.Xml;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Management.RecoveryServices.Models;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery;
using Microsoft.Azure.Portal.RecoveryServices.Models.Common;
namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
/// <summary>
/// Recovery services convenience client.
/// </summary>
public partial class PSRecoveryServicesClient
{
/// <summary>
/// Amount of time to sleep before fetching job details again.
/// </summary>
public const int TimeToSleepBeforeFetchingJobDetailsAgain = 30000;
/// <summary>
/// Resource credentials holds vault, cloud service name, vault key and other details.
/// </summary>
[SuppressMessage(
"Microsoft.StyleCop.CSharp.MaintainabilityRules",
"SA1401:FieldsMustBePrivate",
Justification = "For Resource Credentials.")]
public static ASRVaultCreds asrVaultCreds = new ASRVaultCreds();
private static AzureContext AzureContext;
/// <summary>
/// Subscription Cloud credentials
/// </summary>
private static SubscriptionCloudCredentials cloudCredentials;
/// <summary>
/// End point Uri
/// </summary>
private static Uri endPointUri;
public static string idPrefixtillvaultName = string.Empty;
/// <summary>
/// Recovery services vault management client.
/// </summary>
private readonly RecoveryServicesClient recoveryServicesVaultClient;
/// <summary>
/// Initializes a new instance of the <see cref="PSRecoveryServicesClient" /> class with
/// required current subscription.
/// </summary>
/// <param name="azureSubscription">Azure Subscription</param>
public PSRecoveryServicesClient(
IAzureContextContainer azureProfile)
{
AzureContext = (AzureContext)azureProfile.DefaultContext;
var resourceNamespace = ARMResourceTypeConstants
.RecoveryServicesResourceProviderNameSpace;
var resourceType = ARMResourceTypeConstants.RecoveryServicesVault;
// Get Resource provider namespace and type from config only if Vault context is not set
// (hopefully it is required only for Vault related cmdlets)
if (string.IsNullOrEmpty(asrVaultCreds.ResourceNamespace) ||
string.IsNullOrEmpty(asrVaultCreds.ARMResourceType))
{
Utilities.UpdateCurrentVaultContext(
new ASRVaultCreds
{
ResourceNamespace = resourceNamespace,
ARMResourceType = resourceType
});
}
if (null == endPointUri)
{
endPointUri =
azureProfile.DefaultContext.Environment.GetEndpointAsUri(
AzureEnvironment.Endpoint.ResourceManager);
}
cloudCredentials = AzureSession.Instance.AuthenticationFactory
.GetSubscriptionCloudCredentials(azureProfile.DefaultContext);
this.recoveryServicesVaultClient = AzureSession.Instance.ClientFactory
.CreateArmClient<RecoveryServicesClient>(
AzureContext,
AzureEnvironment.Endpoint.ResourceManager);
}
/// <summary>
/// client request id.
/// </summary>
public string ClientRequestId { get; set; }
/// <summary>
/// Gets the value of recovery services vault management client.
/// </summary>
public RecoveryServicesClient GetRecoveryServicesVaultClient => this
.recoveryServicesVaultClient;
/// <summary>
/// Site Recovery requests that go to on-premise components (like the Provider installed
/// in VMM) require an authentication token that is signed with the vault key to indicate
/// that the request indeed originated from the end-user client.
/// Generating that authentication token here and sending it via http headers.
/// </summary>
/// <param name="clientRequestId">Unique identifier for the client's request</param>
/// <returns>The authentication token for the provider</returns>
public string GenerateAgentAuthenticationHeader(
string clientRequestId)
{
var cikTokenDetails = new CikTokenDetails();
var currentDateTime = DateTime.Now;
currentDateTime = currentDateTime.AddHours(-1);
cikTokenDetails.NotBeforeTimestamp = TimeZoneInfo.ConvertTimeToUtc(currentDateTime);
cikTokenDetails.NotAfterTimestamp = cikTokenDetails.NotBeforeTimestamp.AddDays(7);
cikTokenDetails.ClientRequestId = clientRequestId;
cikTokenDetails.Version = new Version(
1,
2);
cikTokenDetails.PropertyBag = new Dictionary<string, object>();
var shaInput = new JavaScriptSerializer().Serialize(cikTokenDetails);
if (null == asrVaultCreds.ChannelIntegrityKey)
{
throw new ArgumentException(Resources.MissingChannelIntergrityKey);
}
var sha = new HMACSHA256(Encoding.UTF8.GetBytes(asrVaultCreds.ChannelIntegrityKey));
cikTokenDetails.Hmac =
Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(shaInput)));
cikTokenDetails.HashFunction = CikSupportedHashFunctions.HMACSHA256.ToString();
return new JavaScriptSerializer().Serialize(cikTokenDetails);
}
/// <summary>
/// Get extendVault Info.
/// </summary>
/// <param name="vaultResourceGroupName">Vault ResourceGroup Name</param>
/// <param name="vaultName">Vault Name</param>
/// <returns>VaultExtendedInfo Resource Object</returns>
public VaultExtendedInfoResource GetVaultExtendedInfo(String vaultResourceGroupName, String vaultName)
{
return this.recoveryServicesVaultClient
.VaultExtendedInfo
.GetWithHttpMessagesAsync(vaultResourceGroupName, vaultName, this.GetRequestHeaders(false))
.GetAwaiter()
.GetResult()
.Body;
}
public static string GetJobIdFromReponseLocation(
string responseLocation)
{
const string operationResults = "operationresults";
var startIndex = responseLocation.IndexOf(
operationResults,
StringComparison.OrdinalIgnoreCase) +
operationResults.Length +
1;
var endIndex = responseLocation.IndexOf(
"?",
startIndex,
StringComparison.OrdinalIgnoreCase);
return responseLocation.Substring(
startIndex,
endIndex - startIndex);
}
/// <summary>
/// Gets request headers.
/// </summary>
/// <param name="shouldSignRequest">specifies whether to sign the request or not</param>
/// <returns>Custom request headers</returns>
public Dictionary<string, List<string>> GetRequestHeaders(
bool shouldSignRequest = true)
{
var customHeaders = new Dictionary<string, List<string>>();
this.ClientRequestId = Guid.NewGuid() +
"-" +
DateTime.Now.ToUniversalTime()
.ToString("yyyy-MM-dd HH:mm:ssZ") +
"-Ps";
customHeaders.Add(
"x-ms-client-request-id",
new List<string> { this.ClientRequestId });
if (shouldSignRequest)
{
customHeaders.Add(
"Agent-Authentication",
new List<string>
{
this.GenerateAgentAuthenticationHeader(this.ClientRequestId)
});
}
else
{
customHeaders.Add(
"Agent-Authentication",
new List<string> { "" });
}
return customHeaders;
}
public static string GetResourceGroup(
string resourceId)
{
const string resourceGroup = "resourceGroups";
var startIndex = resourceId.IndexOf(
resourceGroup,
StringComparison.OrdinalIgnoreCase) +
resourceGroup.Length +
1;
var endIndex = resourceId.IndexOf(
"/",
startIndex,
StringComparison.OrdinalIgnoreCase);
return resourceId.Substring(
startIndex,
endIndex - startIndex);
}
public static string GetSubscriptionId(
string resourceId)
{
const string subscriptions = "subscriptions";
var startIndex = resourceId.IndexOf(
subscriptions,
StringComparison.OrdinalIgnoreCase) +
subscriptions.Length +
1;
var endIndex = resourceId.IndexOf(
"/",
startIndex,
StringComparison.OrdinalIgnoreCase);
return resourceId.Substring(
startIndex,
endIndex - startIndex);
}
/// <summary>
/// Validates current in-memory Vault Settings.
/// </summary>
/// <param name="resourceName">Resource Name</param>
/// <param name="resourceGroupName">Cloud Service Name</param>
/// <returns>Whether Vault settings are valid or not</returns>
public bool ValidateVaultSettings(
string resourceName,
string resourceGroupName)
{
if (string.IsNullOrEmpty(resourceName) ||
string.IsNullOrEmpty(resourceGroupName))
{
throw new InvalidOperationException(Resources.MissingVaultSettings);
}
var validResourceGroup = false;
var validResource = false;
//foreach (Management.RecoveryServices.Models.ResourceGroup resourceGroup in this.GetRecoveryServicesVaultClient.ResourceGroup.List())
//{
// if (string.Compare(resourceGroup.Name, resourceGroupName, StringComparison.OrdinalIgnoreCase) == 0)
// {
// validResourceGroup = true;
// break;
// }
//}
//if (!validResourceGroup)
//{
// throw new ArgumentException(Properties.Resources.InvalidResourceGroup);
//}
foreach (var vault in this.GetRecoveryServicesVaultClient.Vaults.ListByResourceGroup(
resourceGroupName))
{
if (string.Compare(
vault.Name,
resourceName,
StringComparison.OrdinalIgnoreCase) ==
0)
{
validResource = true;
idPrefixtillvaultName = vault.Id;
break;
}
}
if (!validResource)
{
throw new ArgumentException(Resources.InvalidResource);
}
return true;
}
/// <summary>
/// Gets Site Recovery client.
/// </summary>
/// <returns>Site Recovery Management client</returns>
private SiteRecoveryManagementClient GetSiteRecoveryClient()
{
if (string.IsNullOrEmpty(asrVaultCreds.ResourceName) ||
string.IsNullOrEmpty(asrVaultCreds.ResourceGroupName))
{
throw new InvalidOperationException(Resources.MissingVaultSettings);
}
var creds =
AzureSession.Instance.AuthenticationFactory.GetServiceClientCredentials(
AzureContext);
var siteRecoveryClient = AzureSession.Instance.ClientFactory
.CreateArmClient<SiteRecoveryManagementClient>(
AzureContext,
AzureEnvironment.Endpoint.ResourceManager);
siteRecoveryClient.ResourceGroupName = asrVaultCreds.ResourceGroupName;
siteRecoveryClient.ResourceName = asrVaultCreds.ResourceName;
siteRecoveryClient.SubscriptionId = cloudCredentials.SubscriptionId;
siteRecoveryClient.BaseUri = endPointUri;
if (null == siteRecoveryClient)
{
throw new InvalidOperationException(Resources.NullRecoveryServicesClient);
}
return siteRecoveryClient;
}
private static bool IgnoreCertificateErrorHandler(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
/// <summary>
/// Helper around serialization/deserialization of objects. This one is a thin wrapper around
/// DataContractUtils template class which is the one doing the heavy lifting.
/// </summary>
[SuppressMessage(
"Microsoft.StyleCop.CSharp.MaintainabilityRules",
"SA1402:FileMayOnlyContainASingleClass",
Justification = "Keeping all contracts together.")]
public static class DataContractUtils
{
/// <summary>
/// Deserialize the string to the expected object type.
/// </summary>
/// <typeparam name="T">The object type</typeparam>
/// <param name="xmlString">Serialized string</param>
/// <param name="result">Deserialized object</param>
public static void Deserialize<T>(
string xmlString,
out T result)
{
result = DataContractUtils<T>.Deserialize(xmlString);
}
/// <summary>
/// Serializes the supplied object to the string.
/// </summary>
/// <typeparam name="T">The object type.</typeparam>
/// <param name="obj">Object to serialize</param>
/// <returns>Serialized string.</returns>
public static string Serialize<T>(
T obj)
{
return DataContractUtils<T>.Serialize(obj);
}
}
/// <summary>
/// Template class for DataContractUtils.
/// </summary>
/// <typeparam name="T">The object type</typeparam>
[SuppressMessage(
"Microsoft.StyleCop.CSharp.MaintainabilityRules",
"SA1402:FileMayOnlyContainASingleClass",
Justification = "Keeping all contracts together.")]
public static class DataContractUtils<T>
{
/// <summary>
/// Deserialize the string to the propertyBagContainer.
/// </summary>
/// <param name="xmlString">Serialized string</param>
/// <returns>Deserialized object</returns>
public static T Deserialize(
string xmlString)
{
T propertyBagContainer;
using (Stream stream = new MemoryStream())
{
var data = Encoding.UTF8.GetBytes(xmlString);
stream.Write(
data,
0,
data.Length);
stream.Position = 0;
var deserializer = new DataContractSerializer(typeof(T));
propertyBagContainer = (T)deserializer.ReadObject(stream);
}
return propertyBagContainer;
}
/// <summary>
/// Serializes the propertyBagContainer to the string.
/// </summary>
/// <param name="propertyBagContainer">Property bag</param>
/// <returns>Serialized string </returns>
public static string Serialize(
T propertyBagContainer)
{
var serializer = new DataContractSerializer(typeof(T));
string xmlString;
StringWriter sw = null;
try
{
sw = new StringWriter();
using (var writer = new XmlTextWriter(sw))
{
// Indent the XML so it's human readable.
writer.Formatting = Formatting.Indented;
serializer.WriteObject(
writer,
propertyBagContainer);
writer.Flush();
xmlString = sw.ToString();
}
}
finally
{
if (sw != null)
{
sw.Close();
}
}
return xmlString;
}
}
}
| |
/*
* 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 org.apache.commons.math3.analysis.util;
using FastMath = System.Math;
namespace org.apache.commons.math3.analysis.solvers
{
/// <summary>
/// This class implements the <a href="http://mathworld.wolfram.com/MullersMethod.html">
/// Muller's Method</a> for root finding of real univariate functions. For
/// reference, see <b>Elementary Numerical Analysis</b>, ISBN 0070124477,
/// chapter 3.
/// <para>
/// Muller's method applies to both real and complex functions, but here we
/// restrict ourselves to real functions.
/// This class differs from <seealso cref="MullerSolver"/> in the way it avoids complex
/// operations.</para>
/// Muller's original method would have function evaluation at complex point.
/// Since our f(x) is real, we have to find ways to avoid that. Bracketing
/// condition is one way to go: by requiring bracketing in every iteration,
/// the newly computed approximation is guaranteed to be real.</p>
/// <para>
/// Normally Muller's method converges quadratically in the vicinity of a
/// zero, however it may be very slow in regions far away from zeros. For
/// example, f(x) = exp(x) - 1, min = -50, max = 100. In such case we use
/// bisection as a safety backup if it performs very poorly.</para>
/// <para>
/// The formulas here use divided differences directly.</para>
///
/// @version $Id: MullerSolver.java 1391927 2012-09-30 00:03:30Z erans $
/// @since 1.2 </summary>
/// <seealso cref= MullerSolver2 </seealso>
public class MullerSolver : AbstractUnivariateSolver
{
/// <summary>
/// Default absolute accuracy. </summary>
private const double DEFAULT_ABSOLUTE_ACCURACY = 1e-6;
/// <summary>
/// Construct a solver with default accuracy (1e-6).
/// </summary>
public MullerSolver()
: this(DEFAULT_ABSOLUTE_ACCURACY)
{
}
/// <summary>
/// Construct a solver.
/// </summary>
/// <param name="absoluteAccuracy"> Absolute accuracy. </param>
public MullerSolver(double absoluteAccuracy)
: base(absoluteAccuracy)
{
}
/// <summary>
/// Construct a solver.
/// </summary>
/// <param name="relativeAccuracy"> Relative accuracy. </param>
/// <param name="absoluteAccuracy"> Absolute accuracy. </param>
public MullerSolver(double relativeAccuracy, double absoluteAccuracy)
: base(relativeAccuracy, absoluteAccuracy)
{
}
/// <summary>
/// {@inheritDoc}
/// </summary>
protected internal override double DoSolve()
{
double min = this.Min;
double max = this.Max;
double initial = this.StartValue;
double functionValueAccuracy = this.FunctionValueAccuracy;
this.VerifySequence(min, initial, max);
// check for zeros before verifying bracketing
double fMin = this.ComputeObjectiveValue(min);
if (FastMath.Abs(fMin) < functionValueAccuracy)
{
return min;
}
double fMax = this.ComputeObjectiveValue(max);
if (FastMath.Abs(fMax) < functionValueAccuracy)
{
return max;
}
double fInitial = this.ComputeObjectiveValue(initial);
if (FastMath.Abs(fInitial) < functionValueAccuracy)
{
return initial;
}
this.VerifyBracketing(min, max);
if (this.IsBracketing(min, initial))
{
return this.Solve(min, initial, fMin, fInitial);
}
else
{
return this.Solve(initial, max, fInitial, fMax);
}
}
/// <summary>
/// Find a real root in the given interval.
/// </summary>
/// <param name="min"> Lower bound for the interval. </param>
/// <param name="max"> Upper bound for the interval. </param>
/// <param name="fMin"> function value at the lower bound. </param>
/// <param name="fMax"> function value at the upper bound. </param>
/// <returns> the point at which the function value is zero. </returns>
/// <exception cref="TooManyEvaluationsException"> if the allowed number of calls to
/// the function to be solved has been exhausted. </exception>
private double Solve(double min, double max, double fMin, double fMax)
{
double relativeAccuracy = this.RelativeAccuracy;
double absoluteAccuracy = this.AbsoluteAccuracy;
double functionValueAccuracy = this.FunctionValueAccuracy;
// [x0, x2] is the bracketing interval in each iteration
// x1 is the last approximation and an interpolation point in (x0, x2)
// x is the new root approximation and new x1 for next round
// d01, d12, d012 are divided differences
double x0 = min;
double y0 = fMin;
double x2 = max;
double y2 = fMax;
double x1 = 0.5 * (x0 + x2);
double y1 = this.ComputeObjectiveValue(x1);
double oldx = double.PositiveInfinity;
while (true)
{
// Muller's method employs quadratic interpolation through
// x0, x1, x2 and x is the zero of the interpolating parabola.
// Due to bracketing condition, this parabola must have two
// real roots and we choose one in [x0, x2] to be x.
double d01 = (y1 - y0) / (x1 - x0);
double d12 = (y2 - y1) / (x2 - x1);
double d012 = (d12 - d01) / (x2 - x0);
double c1 = d01 + (x1 - x0) * d012;
double delta = c1 * c1 - 4 * y1 * d012;
double xplus = x1 + (-2.0 * y1) / (c1 + FastMath.Sqrt(delta));
double xminus = x1 + (-2.0 * y1) / (c1 - FastMath.Sqrt(delta));
// xplus and xminus are two roots of parabola and at least
// one of them should lie in (x0, x2)
double x = this.IsSequence(x0, xplus, x2) ? xplus : xminus;
double y = this.ComputeObjectiveValue(x);
// check for convergence
double tolerance = FastMath.Max(relativeAccuracy * FastMath.Abs(x), absoluteAccuracy);
if (FastMath.Abs(x - oldx) <= tolerance || FastMath.Abs(y) <= functionValueAccuracy)
{
return x;
}
// Bisect if convergence is too slow. Bisection would waste
// our calculation of x, hopefully it won't happen often.
// the real number equality test x == x1 is intentional and
// completes the proximity tests above it
bool bisect = (x < x1 && (x1 - x0) > 0.95 * (x2 - x0)) || (x > x1 && (x2 - x1) > 0.95 * (x2 - x0)) || (x == x1);
// prepare the new bracketing interval for next iteration
if (!bisect)
{
x0 = x < x1 ? x0 : x1;
y0 = x < x1 ? y0 : y1;
x2 = x > x1 ? x2 : x1;
y2 = x > x1 ? y2 : y1;
x1 = x;
y1 = y;
oldx = x;
}
else
{
double xm = 0.5 * (x0 + x2);
double ym = this.ComputeObjectiveValue(xm);
if (MyUtils.Signum(y0) + MyUtils.Signum(ym) == 0.0)
{
x2 = xm;
y2 = ym;
}
else
{
x0 = xm;
y0 = ym;
}
x1 = 0.5 * (x0 + x2);
y1 = this.ComputeObjectiveValue(x1);
oldx = double.PositiveInfinity;
}
}
}
}
}
| |
namespace Humidifier.AmazonMQ
{
using System.Collections.Generic;
using BrokerTypes;
public class Broker : Humidifier.Resource
{
public static class Attributes
{
public static string IpAddresses = "IpAddresses" ;
public static string OpenWireEndpoints = "OpenWireEndpoints" ;
public static string ConfigurationRevision = "ConfigurationRevision" ;
public static string StompEndpoints = "StompEndpoints" ;
public static string MqttEndpoints = "MqttEndpoints" ;
public static string AmqpEndpoints = "AmqpEndpoints" ;
public static string Arn = "Arn" ;
public static string ConfigurationId = "ConfigurationId" ;
public static string WssEndpoints = "WssEndpoints" ;
}
public override string AWSTypeName
{
get
{
return @"AWS::AmazonMQ::Broker";
}
}
/// <summary>
/// SecurityGroups
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-securitygroups
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic SecurityGroups
{
get;
set;
}
/// <summary>
/// StorageType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-storagetype
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic StorageType
{
get;
set;
}
/// <summary>
/// EngineVersion
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-engineversion
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic EngineVersion
{
get;
set;
}
/// <summary>
/// Configuration
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-configuration
/// Required: False
/// UpdateType: Mutable
/// Type: ConfigurationId
/// </summary>
public ConfigurationId Configuration
{
get;
set;
}
/// <summary>
/// MaintenanceWindowStartTime
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-maintenancewindowstarttime
/// Required: False
/// UpdateType: Immutable
/// Type: MaintenanceWindow
/// </summary>
public MaintenanceWindow MaintenanceWindowStartTime
{
get;
set;
}
/// <summary>
/// HostInstanceType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-hostinstancetype
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic HostInstanceType
{
get;
set;
}
/// <summary>
/// AutoMinorVersionUpgrade
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-autominorversionupgrade
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic AutoMinorVersionUpgrade
{
get;
set;
}
/// <summary>
/// Users
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-users
/// Required: True
/// UpdateType: Mutable
/// Type: List
/// ItemType: User
/// </summary>
public List<User> Users
{
get;
set;
}
/// <summary>
/// Logs
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-logs
/// Required: False
/// UpdateType: Mutable
/// Type: LogList
/// </summary>
public LogList Logs
{
get;
set;
}
/// <summary>
/// SubnetIds
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-subnetids
/// Required: False
/// UpdateType: Immutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic SubnetIds
{
get;
set;
}
/// <summary>
/// BrokerName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-brokername
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic BrokerName
{
get;
set;
}
/// <summary>
/// DeploymentMode
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-deploymentmode
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic DeploymentMode
{
get;
set;
}
/// <summary>
/// EngineType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-enginetype
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic EngineType
{
get;
set;
}
/// <summary>
/// PubliclyAccessible
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-publiclyaccessible
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic PubliclyAccessible
{
get;
set;
}
/// <summary>
/// EncryptionOptions
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-encryptionoptions
/// Required: False
/// UpdateType: Immutable
/// Type: EncryptionOptions
/// </summary>
public EncryptionOptions EncryptionOptions
{
get;
set;
}
/// <summary>
/// Tags
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-amazonmq-broker.html#cfn-amazonmq-broker-tags
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: TagsEntry
/// </summary>
public List<TagsEntry> Tags
{
get;
set;
}
}
namespace BrokerTypes
{
public class EncryptionOptions
{
/// <summary>
/// KmsKeyId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-encryptionoptions.html#cfn-amazonmq-broker-encryptionoptions-kmskeyid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic KmsKeyId
{
get;
set;
}
/// <summary>
/// UseAwsOwnedKey
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-encryptionoptions.html#cfn-amazonmq-broker-encryptionoptions-useawsownedkey
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic UseAwsOwnedKey
{
get;
set;
}
}
public class MaintenanceWindow
{
/// <summary>
/// DayOfWeek
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-maintenancewindow.html#cfn-amazonmq-broker-maintenancewindow-dayofweek
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DayOfWeek
{
get;
set;
}
/// <summary>
/// TimeOfDay
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-maintenancewindow.html#cfn-amazonmq-broker-maintenancewindow-timeofday
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic TimeOfDay
{
get;
set;
}
/// <summary>
/// TimeZone
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-maintenancewindow.html#cfn-amazonmq-broker-maintenancewindow-timezone
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic TimeZone
{
get;
set;
}
}
public class LogList
{
/// <summary>
/// Audit
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-loglist.html#cfn-amazonmq-broker-loglist-audit
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic Audit
{
get;
set;
}
/// <summary>
/// General
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-loglist.html#cfn-amazonmq-broker-loglist-general
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic General
{
get;
set;
}
}
public class TagsEntry
{
/// <summary>
/// Value
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-tagsentry.html#cfn-amazonmq-broker-tagsentry-value
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Value
{
get;
set;
}
/// <summary>
/// Key
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-tagsentry.html#cfn-amazonmq-broker-tagsentry-key
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Key
{
get;
set;
}
}
public class User
{
/// <summary>
/// Username
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-username
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Username
{
get;
set;
}
/// <summary>
/// Groups
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-groups
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Groups
{
get;
set;
}
/// <summary>
/// ConsoleAccess
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-consoleaccess
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic ConsoleAccess
{
get;
set;
}
/// <summary>
/// Password
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-password
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Password
{
get;
set;
}
}
public class ConfigurationId
{
/// <summary>
/// Revision
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-configurationid.html#cfn-amazonmq-broker-configurationid-revision
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Revision
{
get;
set;
}
/// <summary>
/// Id
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-configurationid.html#cfn-amazonmq-broker-configurationid-id
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Id
{
get;
set;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Collections;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Utils;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Interactivity;
using Avalonia.Threading;
using Avalonia.VisualTree;
namespace Avalonia.Controls
{
/// <summary>
/// Displays a hierarchical tree of data.
/// </summary>
public class TreeView : ItemsControl, ICustomKeyboardNavigation
{
/// <summary>
/// Defines the <see cref="AutoScrollToSelectedItem"/> property.
/// </summary>
public static readonly StyledProperty<bool> AutoScrollToSelectedItemProperty =
SelectingItemsControl.AutoScrollToSelectedItemProperty.AddOwner<TreeView>();
/// <summary>
/// Defines the <see cref="SelectedItem"/> property.
/// </summary>
public static readonly DirectProperty<TreeView, object> SelectedItemProperty =
SelectingItemsControl.SelectedItemProperty.AddOwner<TreeView>(
o => o.SelectedItem,
(o, v) => o.SelectedItem = v);
/// <summary>
/// Defines the <see cref="SelectedItems"/> property.
/// </summary>
public static readonly DirectProperty<TreeView, IList> SelectedItemsProperty =
ListBox.SelectedItemsProperty.AddOwner<TreeView>(
o => o.SelectedItems,
(o, v) => o.SelectedItems = v);
/// <summary>
/// Defines the <see cref="SelectionMode"/> property.
/// </summary>
public static readonly StyledProperty<SelectionMode> SelectionModeProperty =
ListBox.SelectionModeProperty.AddOwner<TreeView>();
private static readonly IList Empty = Array.Empty<object>();
private object _selectedItem;
private IList _selectedItems;
private bool _syncingSelectedItems;
/// <summary>
/// Initializes static members of the <see cref="TreeView"/> class.
/// </summary>
static TreeView()
{
// HACK: Needed or SelectedItem property will not be found in Release build.
}
/// <summary>
/// Occurs when the control's selection changes.
/// </summary>
public event EventHandler<SelectionChangedEventArgs> SelectionChanged
{
add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
}
/// <summary>
/// Gets the <see cref="ITreeItemContainerGenerator"/> for the tree view.
/// </summary>
public new ITreeItemContainerGenerator ItemContainerGenerator =>
(ITreeItemContainerGenerator)base.ItemContainerGenerator;
/// <summary>
/// Gets or sets a value indicating whether to automatically scroll to newly selected items.
/// </summary>
public bool AutoScrollToSelectedItem
{
get => GetValue(AutoScrollToSelectedItemProperty);
set => SetValue(AutoScrollToSelectedItemProperty, value);
}
/// <summary>
/// Gets or sets the selection mode.
/// </summary>
public SelectionMode SelectionMode
{
get => GetValue(SelectionModeProperty);
set => SetValue(SelectionModeProperty, value);
}
/// <summary>
/// Gets or sets the selected item.
/// </summary>
/// <remarks>
/// Note that setting this property only currently works if the item is expanded to be visible.
/// To select non-expanded nodes use `Selection.SelectedIndex`.
/// </remarks>
public object SelectedItem
{
get => _selectedItem;
set
{
var selectedItems = SelectedItems;
SetAndRaise(SelectedItemProperty, ref _selectedItem, value);
if (value != null)
{
if (selectedItems.Count != 1 || selectedItems[0] != value)
{
SelectSingleItem(value);
}
}
else if (SelectedItems.Count > 0)
{
SelectedItems.Clear();
}
}
}
/// <summary>
/// Gets or sets the selected items.
/// </summary>
public IList SelectedItems
{
get
{
if (_selectedItems == null)
{
_selectedItems = new AvaloniaList<object>();
SubscribeToSelectedItems();
}
return _selectedItems;
}
set
{
if (value?.IsFixedSize == true || value?.IsReadOnly == true)
{
throw new NotSupportedException(
"Cannot use a fixed size or read-only collection as SelectedItems.");
}
UnsubscribeFromSelectedItems();
_selectedItems = value ?? new AvaloniaList<object>();
SubscribeToSelectedItems();
}
}
/// <summary>
/// Expands the specified <see cref="TreeViewItem"/> all descendent <see cref="TreeViewItem"/>s.
/// </summary>
/// <param name="item">The item to expand.</param>
public void ExpandSubTree(TreeViewItem item)
{
item.IsExpanded = true;
if (item.Presenter?.Panel != null)
{
foreach (var child in item.Presenter.Panel.Children)
{
if (child is TreeViewItem treeViewItem)
{
ExpandSubTree(treeViewItem);
}
}
}
}
/// <summary>
/// Selects all items in the <see cref="TreeView"/>.
/// </summary>
/// <remarks>
/// Note that this method only selects nodes currently visible due to their parent nodes
/// being expanded: it does not expand nodes.
/// </remarks>
public void SelectAll()
{
SynchronizeItems(SelectedItems, ItemContainerGenerator.Index.Items);
}
/// <summary>
/// Deselects all items in the <see cref="TreeView"/>.
/// </summary>
public void UnselectAll()
{
SelectedItems.Clear();
}
/// <summary>
/// Subscribes to the <see cref="SelectedItems"/> CollectionChanged event, if any.
/// </summary>
private void SubscribeToSelectedItems()
{
if (_selectedItems is INotifyCollectionChanged incc)
{
incc.CollectionChanged += SelectedItemsCollectionChanged;
}
SelectedItemsCollectionChanged(
_selectedItems,
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
private void SelectSingleItem(object item)
{
_syncingSelectedItems = true;
SelectedItems.Clear();
SelectedItems.Add(item);
_syncingSelectedItems = false;
SetAndRaise(SelectedItemProperty, ref _selectedItem, item);
}
/// <summary>
/// Called when the <see cref="SelectedItems"/> CollectionChanged event is raised.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void SelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
IList added = null;
IList removed = null;
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
SelectedItemsAdded(e.NewItems.Cast<object>().ToArray());
if (AutoScrollToSelectedItem)
{
var container = (TreeViewItem)ItemContainerGenerator.Index.ContainerFromItem(e.NewItems[0]);
container?.BringIntoView();
}
added = e.NewItems;
break;
case NotifyCollectionChangedAction.Remove:
if (!_syncingSelectedItems)
{
if (SelectedItems.Count == 0)
{
SelectedItem = null;
}
else
{
var selectedIndex = SelectedItems.IndexOf(_selectedItem);
if (selectedIndex == -1)
{
var old = _selectedItem;
_selectedItem = SelectedItems[0];
RaisePropertyChanged(SelectedItemProperty, old, _selectedItem);
}
}
}
foreach (var item in e.OldItems)
{
MarkItemSelected(item, false);
}
removed = e.OldItems;
break;
case NotifyCollectionChangedAction.Reset:
foreach (IControl container in ItemContainerGenerator.Index.Containers)
{
MarkContainerSelected(container, false);
}
if (SelectedItems.Count > 0)
{
SelectedItemsAdded(SelectedItems);
added = SelectedItems;
}
else if (!_syncingSelectedItems)
{
SelectedItem = null;
}
break;
case NotifyCollectionChangedAction.Replace:
foreach (var item in e.OldItems)
{
MarkItemSelected(item, false);
}
foreach (var item in e.NewItems)
{
MarkItemSelected(item, true);
}
if (SelectedItem != SelectedItems[0] && !_syncingSelectedItems)
{
var oldItem = SelectedItem;
var item = SelectedItems[0];
_selectedItem = item;
RaisePropertyChanged(SelectedItemProperty, oldItem, item);
}
added = e.NewItems;
removed = e.OldItems;
break;
}
if (added?.Count > 0 || removed?.Count > 0)
{
var changed = new SelectionChangedEventArgs(
SelectingItemsControl.SelectionChangedEvent,
removed ?? Empty,
added ?? Empty);
RaiseEvent(changed);
}
}
private void MarkItemSelected(object item, bool selected)
{
var container = ItemContainerGenerator.Index.ContainerFromItem(item);
MarkContainerSelected(container, selected);
}
private void SelectedItemsAdded(IList items)
{
if (items.Count == 0)
{
return;
}
foreach (object item in items)
{
MarkItemSelected(item, true);
}
if (SelectedItem == null && !_syncingSelectedItems)
{
SetAndRaise(SelectedItemProperty, ref _selectedItem, items[0]);
}
}
/// <summary>
/// Unsubscribes from the <see cref="SelectedItems"/> CollectionChanged event, if any.
/// </summary>
private void UnsubscribeFromSelectedItems()
{
if (_selectedItems is INotifyCollectionChanged incc)
{
incc.CollectionChanged -= SelectedItemsCollectionChanged;
}
}
(bool handled, IInputElement next) ICustomKeyboardNavigation.GetNext(IInputElement element,
NavigationDirection direction)
{
if (direction == NavigationDirection.Next || direction == NavigationDirection.Previous)
{
if (!this.IsVisualAncestorOf(element))
{
var result = _selectedItem != null ?
ItemContainerGenerator.Index.ContainerFromItem(_selectedItem) :
ItemContainerGenerator.ContainerFromIndex(0);
return (result != null, result); // SelectedItem may not be in the treeview.
}
return (true, null);
}
return (false, null);
}
/// <inheritdoc/>
protected override IItemContainerGenerator CreateItemContainerGenerator()
{
var result = CreateTreeItemContainerGenerator();
result.Index.Materialized += ContainerMaterialized;
return result;
}
protected virtual ITreeItemContainerGenerator CreateTreeItemContainerGenerator() =>
CreateTreeItemContainerGenerator<TreeViewItem>();
protected virtual ITreeItemContainerGenerator CreateTreeItemContainerGenerator<TVItem>() where TVItem: TreeViewItem, new()
{
return new TreeItemContainerGenerator<TVItem>(
this,
TreeViewItem.HeaderProperty,
TreeViewItem.ItemTemplateProperty,
TreeViewItem.ItemsProperty,
TreeViewItem.IsExpandedProperty);
}
/// <inheritdoc/>
protected override void OnGotFocus(GotFocusEventArgs e)
{
if (e.NavigationMethod == NavigationMethod.Directional)
{
e.Handled = UpdateSelectionFromEventSource(
e.Source,
true,
e.KeyModifiers.HasAllFlags(KeyModifiers.Shift));
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
var direction = e.Key.ToNavigationDirection();
if (direction?.IsDirectional() == true && !e.Handled)
{
if (SelectedItem != null)
{
var next = GetContainerInDirection(
GetContainerFromEventSource(e.Source),
direction.Value,
true);
if (next != null)
{
FocusManager.Instance.Focus(next, NavigationMethod.Directional);
e.Handled = true;
}
}
else
{
SelectedItem = ElementAt(Items, 0);
}
}
if (!e.Handled)
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
bool Match(List<KeyGesture> gestures) => gestures.Any(g => g.Matches(e));
if (this.SelectionMode == SelectionMode.Multiple && Match(keymap.SelectAll))
{
SelectAll();
e.Handled = true;
}
}
}
private TreeViewItem GetContainerInDirection(
TreeViewItem from,
NavigationDirection direction,
bool intoChildren)
{
IItemContainerGenerator parentGenerator = GetParentContainerGenerator(from);
if (parentGenerator == null)
{
return null;
}
var index = parentGenerator.IndexFromContainer(from);
var parent = from.Parent as ItemsControl;
TreeViewItem result = null;
switch (direction)
{
case NavigationDirection.Up:
if (index > 0)
{
var previous = (TreeViewItem)parentGenerator.ContainerFromIndex(index - 1);
result = previous.IsExpanded && previous.ItemCount > 0 ?
(TreeViewItem)previous.ItemContainerGenerator.ContainerFromIndex(previous.ItemCount - 1) :
previous;
}
else
{
result = from.Parent as TreeViewItem;
}
break;
case NavigationDirection.Down:
if (from.IsExpanded && intoChildren && from.ItemCount > 0)
{
result = (TreeViewItem)from.ItemContainerGenerator.ContainerFromIndex(0);
}
else if (index < parent?.ItemCount - 1)
{
result = (TreeViewItem)parentGenerator.ContainerFromIndex(index + 1);
}
else if (parent is TreeViewItem parentItem)
{
return GetContainerInDirection(parentItem, direction, false);
}
break;
}
return result;
}
/// <inheritdoc/>
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (e.Source is IVisual source)
{
var point = e.GetCurrentPoint(source);
if (point.Properties.IsLeftButtonPressed || point.Properties.IsRightButtonPressed)
{
e.Handled = UpdateSelectionFromEventSource(
e.Source,
true,
e.KeyModifiers.HasAllFlags(KeyModifiers.Shift),
e.KeyModifiers.HasAllFlags(KeyModifiers.Control),
point.Properties.IsRightButtonPressed);
}
}
}
/// <summary>
/// Updates the selection for an item based on user interaction.
/// </summary>
/// <param name="container">The container.</param>
/// <param name="select">Whether the item should be selected or unselected.</param>
/// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param>
/// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param>
/// <param name="rightButton">Whether the event is a right-click.</param>
protected void UpdateSelectionFromContainer(
IControl container,
bool select = true,
bool rangeModifier = false,
bool toggleModifier = false,
bool rightButton = false)
{
var item = ItemContainerGenerator.Index.ItemFromContainer(container);
if (item == null)
{
return;
}
IControl selectedContainer = null;
if (SelectedItem != null)
{
selectedContainer = ItemContainerGenerator.Index.ContainerFromItem(SelectedItem);
}
var mode = SelectionMode;
var toggle = toggleModifier || mode.HasAllFlags(SelectionMode.Toggle);
var multi = mode.HasAllFlags(SelectionMode.Multiple);
var range = multi && rangeModifier && selectedContainer != null;
if (rightButton)
{
if (!SelectedItems.Contains(item))
{
SelectSingleItem(item);
}
}
else if (!toggle && !range)
{
SelectSingleItem(item);
}
else if (multi && range)
{
SynchronizeItems(
SelectedItems,
GetItemsInRange(selectedContainer as TreeViewItem, container as TreeViewItem));
}
else
{
var i = SelectedItems.IndexOf(item);
if (i != -1)
{
SelectedItems.Remove(item);
}
else
{
if (multi)
{
SelectedItems.Add(item);
}
else
{
SelectedItem = item;
}
}
}
}
private static IItemContainerGenerator GetParentContainerGenerator(TreeViewItem item)
{
if (item == null)
{
return null;
}
switch (item.Parent)
{
case TreeView treeView:
return treeView.ItemContainerGenerator;
case TreeViewItem treeViewItem:
return treeViewItem.ItemContainerGenerator;
default:
return null;
}
}
/// <summary>
/// Find which node is first in hierarchy.
/// </summary>
/// <param name="treeView">Search root.</param>
/// <param name="nodeA">Nodes to find.</param>
/// <param name="nodeB">Node to find.</param>
/// <returns>Found first node.</returns>
private static TreeViewItem FindFirstNode(TreeView treeView, TreeViewItem nodeA, TreeViewItem nodeB)
{
return FindInContainers(treeView.ItemContainerGenerator, nodeA, nodeB);
}
private static TreeViewItem FindInContainers(ITreeItemContainerGenerator containerGenerator,
TreeViewItem nodeA,
TreeViewItem nodeB)
{
IEnumerable<ItemContainerInfo> containers = containerGenerator.Containers;
foreach (ItemContainerInfo container in containers)
{
TreeViewItem node = FindFirstNode(container.ContainerControl as TreeViewItem, nodeA, nodeB);
if (node != null)
{
return node;
}
}
return null;
}
private static TreeViewItem FindFirstNode(TreeViewItem node, TreeViewItem nodeA, TreeViewItem nodeB)
{
if (node == null)
{
return null;
}
TreeViewItem match = node == nodeA ? nodeA : node == nodeB ? nodeB : null;
if (match != null)
{
return match;
}
return FindInContainers(node.ItemContainerGenerator, nodeA, nodeB);
}
/// <summary>
/// Returns all items that belong to containers between <paramref name="from"/> and <paramref name="to"/>.
/// The range is inclusive.
/// </summary>
/// <param name="from">From container.</param>
/// <param name="to">To container.</param>
private List<object> GetItemsInRange(TreeViewItem from, TreeViewItem to)
{
var items = new List<object>();
if (from == null || to == null)
{
return items;
}
TreeViewItem firstItem = FindFirstNode(this, from, to);
if (firstItem == null)
{
return items;
}
bool wasReversed = false;
if (firstItem == to)
{
var temp = from;
from = to;
to = temp;
wasReversed = true;
}
TreeViewItem node = from;
while (node != to)
{
var item = ItemContainerGenerator.Index.ItemFromContainer(node);
if (item != null)
{
items.Add(item);
}
node = GetContainerInDirection(node, NavigationDirection.Down, true);
}
var toItem = ItemContainerGenerator.Index.ItemFromContainer(to);
if (toItem != null)
{
items.Add(toItem);
}
if (wasReversed)
{
items.Reverse();
}
return items;
}
/// <summary>
/// Updates the selection based on an event that may have originated in a container that
/// belongs to the control.
/// </summary>
/// <param name="eventSource">The control that raised the event.</param>
/// <param name="select">Whether the container should be selected or unselected.</param>
/// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param>
/// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param>
/// <param name="rightButton">Whether the event is a right-click.</param>
/// <returns>
/// True if the event originated from a container that belongs to the control; otherwise
/// false.
/// </returns>
protected bool UpdateSelectionFromEventSource(
IInteractive eventSource,
bool select = true,
bool rangeModifier = false,
bool toggleModifier = false,
bool rightButton = false)
{
var container = GetContainerFromEventSource(eventSource);
if (container != null)
{
UpdateSelectionFromContainer(container, select, rangeModifier, toggleModifier, rightButton);
return true;
}
return false;
}
/// <summary>
/// Tries to get the container that was the source of an event.
/// </summary>
/// <param name="eventSource">The control that raised the event.</param>
/// <returns>The container or null if the event did not originate in a container.</returns>
protected TreeViewItem GetContainerFromEventSource(IInteractive eventSource)
{
var item = ((IVisual)eventSource).GetSelfAndVisualAncestors()
.OfType<TreeViewItem>()
.FirstOrDefault();
if (item != null)
{
if (item.ItemContainerGenerator.Index == ItemContainerGenerator.Index)
{
return item;
}
}
return null;
}
/// <summary>
/// Called when a new item container is materialized, to set its selected state.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void ContainerMaterialized(object sender, ItemContainerEventArgs e)
{
var selectedItem = SelectedItem;
if (selectedItem == null)
{
return;
}
foreach (var container in e.Containers)
{
if (container.Item == selectedItem)
{
((TreeViewItem)container.ContainerControl).IsSelected = true;
if (AutoScrollToSelectedItem)
{
Dispatcher.UIThread.Post(container.ContainerControl.BringIntoView);
}
break;
}
}
}
/// <summary>
/// Sets a container's 'selected' class or <see cref="ISelectable.IsSelected"/>.
/// </summary>
/// <param name="container">The container.</param>
/// <param name="selected">Whether the control is selected</param>
private void MarkContainerSelected(IControl container, bool selected)
{
if (container == null)
{
return;
}
if (container is ISelectable selectable)
{
selectable.IsSelected = selected;
}
else
{
container.Classes.Set(":selected", selected);
}
}
/// <summary>
/// Makes a list of objects equal another (though doesn't preserve order).
/// </summary>
/// <param name="items">The items collection.</param>
/// <param name="desired">The desired items.</param>
private static void SynchronizeItems(IList items, IEnumerable<object> desired)
{
var list = items.Cast<object>().ToList();
var toRemove = list.Except(desired).ToList();
var toAdd = desired.Except(list).ToList();
foreach (var i in toRemove)
{
items.Remove(i);
}
foreach (var i in toAdd)
{
items.Add(i);
}
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web;
using System.Web.Routing;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Events;
using Adxstudio.Xrm.Forums;
using Adxstudio.Xrm.Globalization;
using Adxstudio.Xrm.Metadata;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Tagging;
using Adxstudio.Xrm.Web.Routing;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Diagnostics;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Metadata;
namespace Adxstudio.Xrm
{
/// <summary>
/// Helper methods on the <see cref="Entity"/> class.
/// </summary>
public static class EntityExtensions
{
/// <summary>
/// Retrieves the value of an attribute that may be aliased as a result of a join operation.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="attributeLogicalName"></param>
/// <param name="alias"></param>
/// <returns></returns>
public static T GetAttributeAliasedValue<T>(this Entity entity, string attributeLogicalName, string alias = null)
{
if (entity == null) throw new ArgumentNullException("entity");
if (attributeLogicalName == null) throw new ArgumentNullException("attributeLogicalName");
var prefix = !string.IsNullOrWhiteSpace(alias) ? alias + "." : string.Empty;
var raw = entity.GetAttributeValue(prefix + attributeLogicalName);
var aliasdValue = raw as AliasedValue;
var intermediate = aliasdValue != null ? aliasdValue.Value : raw;
var value = GetPrimitiveValue<T>(intermediate);
return value != null ? (T)value : default(T);
}
/// <summary>
/// Retrieves the <see cref="Enum"/> value for an option set attribute of the entity.
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="entity"></param>
/// <param name="attributeLogicalName"></param>
/// <param name="alias"></param>
/// <returns></returns>
public static TEnum? GetAttributeEnumValue<TEnum>(this Entity entity, string attributeLogicalName, string alias = null)
where TEnum : struct, IComparable, IFormattable, IConvertible
{
var option = GetAttributeAliasedValue<OptionSetValue>(entity, attributeLogicalName, alias);
return option != null ? option.Value.ToEnum<TEnum>() : (TEnum?)null;
}
/// <summary>
/// Retrieves the value of the identifier attribute that may be aliased as a result of a join operation.
/// </summary>
/// <param name="entity"></param>
/// <param name="attributeLogicalName"></param>
/// <param name="alias"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetEntityIdentifier<T>(this Entity entity, string attributeLogicalName, string alias = null) where T : EntityNode
{
var er = GetAttributeAliasedValue<EntityReference>(entity, attributeLogicalName, alias);
var id = er != null ? Activator.CreateInstance(typeof(T), er) as T : null;
return id;
}
/// <summary>
/// Retrieves the value of an interstect's identifier attribute that may be aliased as a result of a join operation.
/// </summary>
/// <param name="entity"></param>
/// <param name="entityLogicalName"></param>
/// <param name="attributeLogicalName"></param>
/// <param name="alias"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetIntersectEntityIdentifier<T>(this Entity entity, string entityLogicalName, string attributeLogicalName, string alias = null) where T : EntityNode
{
var guid = GetAttributeAliasedValue<Guid?>(entity, attributeLogicalName, alias);
var er = guid != null ? new EntityReference(entityLogicalName, guid.Value) : null;
var id = er != null ? Activator.CreateInstance(typeof(T), er) as T : null;
return id;
}
private static object GetPrimitiveValue<T>(object value)
{
if (value is T) return value;
if (value == null) return default(T);
if (value is OptionSetValue && typeof(T).GetUnderlyingType() == typeof(int))
{
return (value as OptionSetValue).Value;
}
if (value is EntityReference && typeof(T).GetUnderlyingType() == typeof(Guid))
{
return (value as EntityReference).Id;
}
if (value is Money && typeof(T).GetUnderlyingType() == typeof(decimal))
{
return (value as Money).Value;
}
if (value is CrmEntityReference && typeof(T).GetUnderlyingType() == typeof(EntityReference))
{
var reference = value as CrmEntityReference;
return new EntityReference(reference.LogicalName, reference.Id) { Name = reference.Name };
}
return value;
}
/// <summary>
/// Retrieves <see cref="PageTagInfo"/> | <see cref="ForumThreadTagInfo"/> | <see cref="EventTagInfo"/>
/// </summary>
/// <param name="entity">Entity</param>
/// <returns><see cref="ITagInfo"/></returns>
public static ITagInfo GetTagInfo(this Entity entity)
{
if (entity == null) return null;
var entityName = entity.LogicalName;
if (entityName == "adx_pagetag") return new PageTagInfo(entity);
if (entityName == "adx_communityforumthreadtag") return new ForumThreadTagInfo(entity);
if (entityName == "adx_eventtag") return new EventTagInfo(entity);
return null;
}
internal static void AssertEntityName(this Entity entity, params string[] expectedEntityName)
{
// accept null values
if (entity == null) return;
if (!HasLogicalName(entity, expectedEntityName))
{
throw new ArgumentException(
ResourceManager.GetString("Extension_Method_Expected_IsDifferent_Exception").FormatWith(
string.Join(" or ", expectedEntityName),
entity.LogicalName));
}
}
private static bool HasLogicalName(this Entity entity, params string[] expectedEntityName)
{
return entity != null && expectedEntityName.Contains(entity.LogicalName);
}
/// <summary>
/// Given a default value, this extension will return the value of the named attribute, or the default value if null.
/// </summary>
/// <param name="entity"></param>
/// <param name="attributeName"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static string GetAttributeValueOrDefault(this Entity entity, string attributeName, string defaultValue)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
object attributeValue;
if (entity.Attributes.TryGetValue(attributeName, out attributeValue))
{
if (attributeValue != null)
{
var value = attributeValue.ToString();
if (!string.IsNullOrEmpty(value))
{
return value;
}
}
}
return defaultValue;
}
/// <summary>
/// Get the label of an entity's option set value.
/// </summary>
/// <param name="entity">Entity</param>
/// <param name="entityMetadata">Entity metadata</param>
/// <param name="attributeLogicalName">Logical name of the option set attribute</param>
/// <param name="languageCode">Optional language code used to return the localized label</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static string GetEnumLabel(this Entity entity, EntityMetadata entityMetadata, string attributeLogicalName, int? languageCode)
{
if (entity == null) throw new ArgumentNullException("entity");
if (entityMetadata == null) throw new ArgumentNullException("entityMetadata");
if (string.IsNullOrWhiteSpace(attributeLogicalName)) throw new ArgumentNullException("attributeLogicalName");
var attributeMetadata = entityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeLogicalName) as EnumAttributeMetadata;
if (attributeMetadata == null)
{
return null;
}
var value = entity.GetAttributeValue<OptionSetValue>(attributeLogicalName);
if (value == null)
{
return null;
}
var option = attributeMetadata.OptionSet.Options.FirstOrDefault(o => o.Value == value.Value);
if (option == null)
{
return null;
}
var localizedLabel = option.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == (languageCode ?? 0));
var label = localizedLabel == null ? option.Label.GetLocalizedLabelString() : localizedLabel.Label;
return label;
}
/// <summary>
/// Modifies the value of an attribute and truncates the string to the max length specified for the attribute.
/// </summary>
/// <param name="entity"></param>
/// <param name="serviceContext"></param>
/// <param name="attributeLogicalName"></param>
/// <param name="value"></param>
/// <param name="metadataCache"></param>
public static void SetAttributeStringTruncatedToMaxLength(this Entity entity, OrganizationServiceContext serviceContext, string attributeLogicalName, string value, IDictionary<string, EntityMetadata> metadataCache)
{
var entityMetadata = serviceContext.GetEntityMetadata(entity.LogicalName, metadataCache);
entity.SetAttributeStringTruncatedToMaxLength(entityMetadata, attributeLogicalName, value);
}
/// <summary>
/// Modifies the value of an attribute and truncates the string to the max length specified for the attribute.
/// </summary>
/// <param name="entity"></param>
/// <param name="serviceContext"></param>
/// <param name="attributeLogicalName"></param>
/// <param name="value"></param>
public static void SetAttributeStringTruncatedToMaxLength(this Entity entity, OrganizationServiceContext serviceContext, string attributeLogicalName, string value)
{
var entityMetadata = serviceContext.GetEntityMetadata(entity.LogicalName);
entity.SetAttributeStringTruncatedToMaxLength(entityMetadata, attributeLogicalName, value);
}
/// <summary>
/// Modifies the value of an attribute and truncates the string to the max length specified for the attribute.
/// </summary>
/// <param name="entity"></param>
/// <param name="entityMetadata"></param>
/// <param name="attributeLogicalName"></param>
/// <param name="value"></param>
public static void SetAttributeStringTruncatedToMaxLength(this Entity entity, EntityMetadata entityMetadata, string attributeLogicalName, string value)
{
if (!string.IsNullOrEmpty(value))
{
if (entityMetadata == null)
{
throw new ApplicationException("Unable to retrieve the entity metadata for {0}.".FormatWith(entity.LogicalName));
}
if (!entityMetadata.Attributes.Select(a => a.LogicalName).Contains(attributeLogicalName))
{
throw new ApplicationException("Attribute {0} could not be found in entity metadata for {1}.".FormatWith(attributeLogicalName, entity.LogicalName));
}
var attribute = entityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attributeLogicalName);
if (attribute == null || attribute.AttributeType != AttributeTypeCode.String)
{
throw new ApplicationException("Attribute {0} is not of type string.".FormatWith(attributeLogicalName));
}
var stringAttributeMetadata = attribute as StringAttributeMetadata;
if (stringAttributeMetadata != null)
{
var maxLength = stringAttributeMetadata.MaxLength ?? 0;
if (maxLength > 0 && value.Length > maxLength)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(@"String length ({0}) is greater than attribute ""{1}"" max length ({2}). String has been truncated.", value.Length, attributeLogicalName, maxLength));
value = value.Truncate(maxLength);
}
}
}
entity.SetAttributeValue<string>(attributeLogicalName, value);
}
/// <summary>
/// Retrieve the url to emit that will download an attached file from the website.
/// </summary>
public static string GetFileAttachmentUrl(this Entity entity, Entity website)
{
return website == null ? GetFileAttachmentUrl(entity) : GetFileAttachmentUrl(entity, website.Id);
}
/// <summary>
/// Retrieve the url to emit that will download an attached file from the website.
/// </summary>
public static string GetFileAttachmentUrl(this Entity entity, EntityReference website)
{
return website == null ? GetFileAttachmentUrl(entity) : GetFileAttachmentUrl(entity, website.Id);
}
/// <summary>
/// Retrieve the url to emit that will download an attached file from the website.
/// </summary>
public static string GetFileAttachmentUrl(this Entity entity, Guid? websiteId = null)
{
var path = GetFileAttachmentPath(entity, websiteId);
return path == null ? null : path.AbsolutePath;
}
/// <summary>
/// Retrieve the path to emit that will download an attached file from the website.
/// </summary>
public static ApplicationPath GetFileAttachmentPath(this Entity entity, Entity website)
{
return website == null ? GetFileAttachmentPath(entity) : GetFileAttachmentPath(entity, website.Id);
}
/// <summary>
/// Retrieve the path to emit that will download an attached file from the website.
/// </summary>
public static ApplicationPath GetFileAttachmentPath(this Entity entity, EntityReference website)
{
return website == null ? GetFileAttachmentPath(entity) : GetFileAttachmentPath(entity, website.Id);
}
/// <summary>
/// Retrieve the path to emit that will download an attached file from the website.
/// </summary>
public static ApplicationPath GetFileAttachmentPath(this Entity entity, Guid? websiteId = null)
{
if (entity == null) return null;
var http = HttpContext.Current;
if (http == null) return null;
var requestContext = new RequestContext(new HttpContextWrapper(http), new RouteData());
VirtualPathData virtualPath;
if (websiteId == null)
{
virtualPath = RouteTable.Routes.GetVirtualPath(requestContext, typeof(EntityRouteHandler).FullName,
new RouteValueDictionary
{
{ "prefix", "_entity" },
{ "logicalName", entity.LogicalName },
{ "id", entity.Id }
});
}
else
{
virtualPath = RouteTable.Routes.GetVirtualPath(requestContext, typeof(EntityRouteHandler).FullName + "PortalScoped", new RouteValueDictionary
{
{ "prefix", "_entity" },
{ "logicalName", entity.LogicalName },
{ "id", entity.Id },
{ "__portalScopeId__", websiteId }
});
}
return virtualPath == null
? null
: ApplicationPath.FromAbsolutePath(VirtualPathUtility.ToAbsolute(virtualPath.VirtualPath));
}
/// <summary>
/// Returns an <see cref="EntityReference"/> to a language container for the given entity. Only web pages currently have a language container (root web page).
/// </summary>
/// <param name="entity">Entity to analyze.</param>
/// <returns>An <see cref="EntityReference"/> to the language container for web pages (root web page). Otherwise an <see cref="EntityReference"/> to the given entity.</returns>
public static EntityReference ToLanguageContainerEntityReference(this Entity entity)
{
if (entity.LogicalName == "adx_webpage")
{
var rootWebPage = entity.GetAttributeValue<EntityReference>("adx_rootwebpageid");
if (rootWebPage != null)
{
return rootWebPage;
}
}
return entity.ToEntityReference();
}
}
}
| |
//
// 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.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations of Azure SQL Database that interact with
/// Azure Key Vault Server Keys. Contains operations to: Add, Delete, and
/// Retrieve Server Ke.
/// </summary>
internal partial class ServerKeyOperations : IServiceOperations<SqlManagementClient>, IServerKeyOperations
{
/// <summary>
/// Initializes a new instance of the ServerKeyOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ServerKeyOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Begins creating a new Azure SQL Server Key or updating an existing
/// Azure SQL Server Key. To determine the status of the operation
/// call GetCreateOrUpdateOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which to add the
/// Server Key.
/// </param>
/// <param name='keyName'>
/// Required. The name of the Azure SQL Server Key.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a
/// Server Key.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Azure Sql Server Key operation request.
/// </returns>
public async Task<ServerKeyCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string serverName, string keyName, ServerKeyCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (keyName == null)
{
throw new ArgumentNullException("keyName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("keyName", keyName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/keys/";
url = url + Uri.EscapeDataString(keyName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject serverKeyCreateOrUpdateParametersValue = new JObject();
requestDoc = serverKeyCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
serverKeyCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Uri != null)
{
propertiesValue["uri"] = parameters.Properties.Uri;
}
if (parameters.Properties.ServerKeyType != null)
{
propertiesValue["serverKeyType"] = parameters.Properties.ServerKeyType;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerKeyCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerKeyCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken operationValue = responseDoc["operation"];
if (operationValue != null && operationValue.Type != JTokenType.Null)
{
string operationInstance = ((string)operationValue);
result.Operation = operationInstance;
}
JToken startTimeValue = responseDoc["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTime startTimeInstance = ((DateTime)startTimeValue);
result.StartTime = startTimeInstance;
}
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
ServerKey serverKeyInstance = new ServerKey();
result.ServerKey = serverKeyInstance;
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
ServerKeyProperties propertiesInstance = new ServerKeyProperties();
serverKeyInstance.Properties = propertiesInstance;
JToken serverKeyTypeValue = propertiesValue2["serverKeyType"];
if (serverKeyTypeValue != null && serverKeyTypeValue.Type != JTokenType.Null)
{
string serverKeyTypeInstance = ((string)serverKeyTypeValue);
propertiesInstance.ServerKeyType = serverKeyTypeInstance;
}
JToken uriValue = propertiesValue2["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
string uriInstance = ((string)uriValue);
propertiesInstance.Uri = uriInstance;
}
JToken thumbprintValue = propertiesValue2["thumbprint"];
if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null)
{
string thumbprintInstance = ((string)thumbprintValue);
propertiesInstance.Thumbprint = thumbprintInstance;
}
JToken creationDateValue = propertiesValue2["creationDate"];
if (creationDateValue != null && creationDateValue.Type != JTokenType.Null)
{
DateTime creationDateInstance = ((DateTime)creationDateValue);
propertiesInstance.CreationDate = creationDateInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverKeyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverKeyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serverKeyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverKeyInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serverKeyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Created)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Begins deleting an existing Azure SQL Server Key.To determine the
/// status of the operation call GetDeleteOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Server Key belongs
/// </param>
/// <param name='keyName'>
/// Required. The name of the Azure SQL Server Key.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to an Azure Sql Server Key Delete request.
/// </returns>
public async Task<ServerKeyDeleteResponse> BeginDeleteAsync(string resourceGroupName, string serverName, string keyName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (keyName == null)
{
throw new ArgumentNullException("keyName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("keyName", keyName);
TracingAdapter.Enter(invocationId, this, "BeginDeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/keys/";
url = url + Uri.EscapeDataString(keyName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerKeyDeleteResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerKeyDeleteResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken operationValue = responseDoc["operation"];
if (operationValue != null && operationValue.Type != JTokenType.Null)
{
string operationInstance = ((string)operationValue);
result.Operation = operationInstance;
}
JToken startTimeValue = responseDoc["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTime startTimeInstance = ((DateTime)startTimeValue);
result.StartTime = startTimeInstance;
}
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Creates a new Azure SQL Server Key or updates an existing Azure SQL
/// Server Key.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which to add the
/// Server Key.
/// </param>
/// <param name='keyName'>
/// Required. The name of the Azure SQL Server Key.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a
/// Server Key.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Azure Sql Server Key operation request.
/// </returns>
public async Task<ServerKeyCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string keyName, ServerKeyCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
SqlManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("keyName", keyName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ServerKeyCreateOrUpdateResponse response = await client.ServerKey.BeginCreateOrUpdateAsync(resourceGroupName, serverName, keyName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
ServerKeyCreateOrUpdateResponse result = await client.ServerKey.GetCreateOrUpdateOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 5;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.ServerKey.GetCreateOrUpdateOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Deletes an existing Azure SQL Server Key.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Server Key belongs
/// </param>
/// <param name='keyName'>
/// Required. The name of the Azure SQL Server Key to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to an Azure Sql Server Key Delete request.
/// </returns>
public async Task<ServerKeyDeleteResponse> DeleteAsync(string resourceGroupName, string serverName, string keyName, CancellationToken cancellationToken)
{
SqlManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("keyName", keyName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ServerKeyDeleteResponse response = await client.ServerKey.BeginDeleteAsync(resourceGroupName, serverName, keyName, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
ServerKeyDeleteResponse result = await client.ServerKey.GetDeleteOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 5;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.ServerKey.GetDeleteOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Gets an Azure Sql Server Key.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server that has the
/// key.
/// </param>
/// <param name='keyName'>
/// Required. The name of the Azure Key Vault Key to be retrieved from
/// the Azure SQL Database Server.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Server Key request.
/// </returns>
public async Task<ServerKeyGetResponse> GetAsync(string resourceGroupName, string serverName, string keyName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (keyName == null)
{
throw new ArgumentNullException("keyName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("keyName", keyName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/keys/";
url = url + Uri.EscapeDataString(keyName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerKeyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerKeyGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ServerKey serverKeyInstance = new ServerKey();
result.ServerKey = serverKeyInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServerKeyProperties propertiesInstance = new ServerKeyProperties();
serverKeyInstance.Properties = propertiesInstance;
JToken serverKeyTypeValue = propertiesValue["serverKeyType"];
if (serverKeyTypeValue != null && serverKeyTypeValue.Type != JTokenType.Null)
{
string serverKeyTypeInstance = ((string)serverKeyTypeValue);
propertiesInstance.ServerKeyType = serverKeyTypeInstance;
}
JToken uriValue = propertiesValue["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
string uriInstance = ((string)uriValue);
propertiesInstance.Uri = uriInstance;
}
JToken thumbprintValue = propertiesValue["thumbprint"];
if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null)
{
string thumbprintInstance = ((string)thumbprintValue);
propertiesInstance.Thumbprint = thumbprintInstance;
}
JToken creationDateValue = propertiesValue["creationDate"];
if (creationDateValue != null && creationDateValue.Type != JTokenType.Null)
{
DateTime creationDateInstance = ((DateTime)creationDateValue);
propertiesInstance.CreationDate = creationDateInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverKeyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverKeyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serverKeyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverKeyInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serverKeyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the status of an Azure SQL Server Key create or update
/// operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a Azure Sql Server Key operation request.
/// </returns>
public async Task<ServerKeyCreateOrUpdateResponse> GetCreateOrUpdateOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetCreateOrUpdateOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerKeyCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerKeyCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken operationValue = responseDoc["operation"];
if (operationValue != null && operationValue.Type != JTokenType.Null)
{
string operationInstance = ((string)operationValue);
result.Operation = operationInstance;
}
JToken startTimeValue = responseDoc["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTime startTimeInstance = ((DateTime)startTimeValue);
result.StartTime = startTimeInstance;
}
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
ServerKey serverKeyInstance = new ServerKey();
result.ServerKey = serverKeyInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServerKeyProperties propertiesInstance = new ServerKeyProperties();
serverKeyInstance.Properties = propertiesInstance;
JToken serverKeyTypeValue = propertiesValue["serverKeyType"];
if (serverKeyTypeValue != null && serverKeyTypeValue.Type != JTokenType.Null)
{
string serverKeyTypeInstance = ((string)serverKeyTypeValue);
propertiesInstance.ServerKeyType = serverKeyTypeInstance;
}
JToken uriValue = propertiesValue["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
string uriInstance = ((string)uriValue);
propertiesInstance.Uri = uriInstance;
}
JToken thumbprintValue = propertiesValue["thumbprint"];
if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null)
{
string thumbprintInstance = ((string)thumbprintValue);
propertiesInstance.Thumbprint = thumbprintInstance;
}
JToken creationDateValue = propertiesValue["creationDate"];
if (creationDateValue != null && creationDateValue.Type != JTokenType.Null)
{
DateTime creationDateInstance = ((DateTime)creationDateValue);
propertiesInstance.CreationDate = creationDateInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverKeyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverKeyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serverKeyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverKeyInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serverKeyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.Created)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the status of an Azure SQL Server Key delete operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to an Azure Sql Server Key Delete request.
/// </returns>
public async Task<ServerKeyDeleteResponse> GetDeleteOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetDeleteOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerKeyDeleteResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerKeyDeleteResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken operationValue = responseDoc["operation"];
if (operationValue != null && operationValue.Type != JTokenType.Null)
{
string operationInstance = ((string)operationValue);
result.Operation = operationInstance;
}
JToken startTimeValue = responseDoc["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTime startTimeInstance = ((DateTime)startTimeValue);
result.StartTime = startTimeInstance;
}
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets all Azure SQL Database Server Keys for a server.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Server Key request.
/// </returns>
public async Task<ServerKeyListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/keys";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerKeyListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerKeyListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ServerKey serverKeyInstance = new ServerKey();
result.ServerKeys.Add(serverKeyInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServerKeyProperties propertiesInstance = new ServerKeyProperties();
serverKeyInstance.Properties = propertiesInstance;
JToken serverKeyTypeValue = propertiesValue["serverKeyType"];
if (serverKeyTypeValue != null && serverKeyTypeValue.Type != JTokenType.Null)
{
string serverKeyTypeInstance = ((string)serverKeyTypeValue);
propertiesInstance.ServerKeyType = serverKeyTypeInstance;
}
JToken uriValue = propertiesValue["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
string uriInstance = ((string)uriValue);
propertiesInstance.Uri = uriInstance;
}
JToken thumbprintValue = propertiesValue["thumbprint"];
if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null)
{
string thumbprintInstance = ((string)thumbprintValue);
propertiesInstance.Thumbprint = thumbprintInstance;
}
JToken creationDateValue = propertiesValue["creationDate"];
if (creationDateValue != null && creationDateValue.Type != JTokenType.Null)
{
DateTime creationDateInstance = ((DateTime)creationDateValue);
propertiesInstance.CreationDate = creationDateInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverKeyInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverKeyInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
serverKeyInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverKeyInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serverKeyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
using NUnit.Framework;
namespace ZXing.Common.ReedSolomon.Test
{
/// <summary>
///
/// </summary>
/// <author>Rustam Abdullaev</author>
[TestFixture]
public sealed class ReedSolomonTestCase
{
private const int DECODER_RANDOM_TEST_ITERATIONS = 3;
private const int DECODER_TEST_ITERATIONS = 10;
[Test]
public void testDataMatrix()
{
// real life test cases
testEncodeDecode(GenericGF.DATA_MATRIX_FIELD_256,
new int[] { 142, 164, 186 }, new int[] { 114, 25, 5, 88, 102 });
testEncodeDecode(GenericGF.DATA_MATRIX_FIELD_256, new int[] {
0x69, 0x75, 0x75, 0x71, 0x3B, 0x30, 0x30, 0x64,
0x70, 0x65, 0x66, 0x2F, 0x68, 0x70, 0x70, 0x68,
0x6D, 0x66, 0x2F, 0x64, 0x70, 0x6E, 0x30, 0x71,
0x30, 0x7B, 0x79, 0x6A, 0x6F, 0x68, 0x30, 0x81,
0xF0, 0x88, 0x1F, 0xB5 },
new int[] {
0x1C, 0x64, 0xEE, 0xEB, 0xD0, 0x1D, 0x00, 0x03,
0xF0, 0x1C, 0xF1, 0xD0, 0x6D, 0x00, 0x98, 0xDA,
0x80, 0x88, 0xBE, 0xFF, 0xB7, 0xFA, 0xA9, 0x95 });
// synthetic test cases
testEncodeDecodeRandom(GenericGF.DATA_MATRIX_FIELD_256, 10, 240);
testEncodeDecodeRandom(GenericGF.DATA_MATRIX_FIELD_256, 128, 127);
testEncodeDecodeRandom(GenericGF.DATA_MATRIX_FIELD_256, 220, 35);
}
[Test]
public void testQRCode()
{
// Test case from example given in ISO 18004, Annex I
testEncodeDecode(GenericGF.QR_CODE_FIELD_256, new int[] {
0x10, 0x20, 0x0C, 0x56, 0x61, 0x80, 0xEC, 0x11,
0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11 },
new int[] {
0xA5, 0x24, 0xD4, 0xC1, 0xED, 0x36, 0xC7, 0x87,
0x2C, 0x55 });
testEncodeDecode(GenericGF.QR_CODE_FIELD_256, new int[] {
0x72, 0x67, 0x2F, 0x77, 0x69, 0x6B, 0x69, 0x2F,
0x4D, 0x61, 0x69, 0x6E, 0x5F, 0x50, 0x61, 0x67,
0x65, 0x3B, 0x3B, 0x00, 0xEC, 0x11, 0xEC, 0x11,
0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11 },
new int[] {
0xD8, 0xB8, 0xEF, 0x14, 0xEC, 0xD0, 0xCC, 0x85,
0x73, 0x40, 0x0B, 0xB5, 0x5A, 0xB8, 0x8B, 0x2E,
0x08, 0x62 });
// real life test cases
// synthetic test cases
testEncodeDecodeRandom(GenericGF.QR_CODE_FIELD_256, 10, 240);
testEncodeDecodeRandom(GenericGF.QR_CODE_FIELD_256, 128, 127);
testEncodeDecodeRandom(GenericGF.QR_CODE_FIELD_256, 220, 35);
}
[Test]
public void testAztec()
{
// real life test cases
testEncodeDecode(GenericGF.AZTEC_PARAM,
new int[] { 0x5, 0x6 }, new int[] { 0x3, 0x2, 0xB, 0xB, 0x7 });
testEncodeDecode(GenericGF.AZTEC_PARAM,
new int[] { 0x0, 0x0, 0x0, 0x9 }, new int[] { 0xA, 0xD, 0x8, 0x6, 0x5, 0x6 });
testEncodeDecode(GenericGF.AZTEC_PARAM,
new int[] { 0x2, 0x8, 0x8, 0x7 }, new int[] { 0xE, 0xC, 0xA, 0x9, 0x6, 0x8 });
testEncodeDecode(GenericGF.AZTEC_DATA_6, new int[] {
0x9, 0x32, 0x1, 0x29, 0x2F, 0x2, 0x27, 0x25, 0x1, 0x1B },
new int[] {
0x2C, 0x2, 0xD, 0xD, 0xA, 0x16, 0x28, 0x9, 0x22, 0xA, 0x14 });
testEncodeDecode(GenericGF.AZTEC_DATA_8, new int[] {
0xE0, 0x86, 0x42, 0x98, 0xE8, 0x4A, 0x96, 0xC6,
0xB9, 0xF0, 0x8C, 0xA7, 0x4A, 0xDA, 0xF8, 0xCE,
0xB7, 0xDE, 0x88, 0x64, 0x29, 0x8E, 0x84, 0xA9,
0x6C, 0x6B, 0x9F, 0x08, 0xCA, 0x74, 0xAD, 0xAF,
0x8C, 0xEB, 0x7C, 0x10, 0xC8, 0x53, 0x1D, 0x09,
0x52, 0xD8, 0xD7, 0x3E, 0x11, 0x94, 0xE9, 0x5B,
0x5F, 0x19, 0xD6, 0xFB, 0xD1, 0x0C, 0x85, 0x31,
0xD0, 0x95, 0x2D, 0x8D, 0x73, 0xE1, 0x19, 0x4E,
0x95, 0xB5, 0xF1, 0x9D, 0x6F },
new int[] {
0x31, 0xD7, 0x04, 0x46, 0xB2, 0xC1, 0x06, 0x94,
0x17, 0xE5, 0x0C, 0x2B, 0xA3, 0x99, 0x15, 0x7F,
0x16, 0x3C, 0x66, 0xBA, 0x33, 0xD9, 0xE8, 0x87,
0x86, 0xBB, 0x4B, 0x15, 0x4E, 0x4A, 0xDE, 0xD4,
0xED, 0xA1, 0xF8, 0x47, 0x2A, 0x50, 0xA6, 0xBC,
0x53, 0x7D, 0x29, 0xFE, 0x06, 0x49, 0xF3, 0x73,
0x9F, 0xC1, 0x75 });
testEncodeDecode(GenericGF.AZTEC_DATA_10, new int[] {
0x15C, 0x1E1, 0x2D5, 0x02E, 0x048, 0x1E2, 0x037, 0x0CD,
0x02E, 0x056, 0x26A, 0x281, 0x1C2, 0x1A6, 0x296, 0x045,
0x041, 0x0AA, 0x095, 0x2CE, 0x003, 0x38F, 0x2CD, 0x1A2,
0x036, 0x1AD, 0x04E, 0x090, 0x271, 0x0D3, 0x02E, 0x0D5,
0x2D4, 0x032, 0x2CA, 0x281, 0x0AA, 0x04E, 0x024, 0x2D3,
0x296, 0x281, 0x0E2, 0x08A, 0x1AA, 0x28A, 0x280, 0x07C,
0x286, 0x0A1, 0x1D0, 0x1AD, 0x154, 0x032, 0x2C2, 0x1C1,
0x145, 0x02B, 0x2D4, 0x2B0, 0x033, 0x2D5, 0x276, 0x1C1,
0x282, 0x10A, 0x2B5, 0x154, 0x003, 0x385, 0x20F, 0x0C4,
0x02D, 0x050, 0x266, 0x0D5, 0x033, 0x2D5, 0x276, 0x1C1,
0x0D4, 0x2A0, 0x08F, 0x0C4, 0x024, 0x20F, 0x2E2, 0x1AD,
0x154, 0x02E, 0x056, 0x26A, 0x281, 0x090, 0x1E5, 0x14E,
0x0CF, 0x2B6, 0x1C1, 0x28A, 0x2A1, 0x04E, 0x0D5, 0x003,
0x391, 0x122, 0x286, 0x1AD, 0x2D4, 0x028, 0x262, 0x2EA,
0x0A2, 0x004, 0x176, 0x295, 0x201, 0x0D5, 0x024, 0x20F,
0x116, 0x0C1, 0x056, 0x095, 0x213, 0x004, 0x1EA, 0x28A,
0x02A, 0x234, 0x2CE, 0x037, 0x157, 0x0D3, 0x262, 0x026,
0x262, 0x2A0, 0x086, 0x106, 0x2A1, 0x126, 0x1E5, 0x266,
0x26A, 0x2A1, 0x0E6, 0x1AA, 0x281, 0x2B6, 0x271, 0x154,
0x02F, 0x0C4, 0x02D, 0x213, 0x0CE, 0x003, 0x38F, 0x2CD,
0x1A2, 0x036, 0x1B5, 0x26A, 0x086, 0x280, 0x086, 0x1AA,
0x2A1, 0x226, 0x1AD, 0x0CF, 0x2A6, 0x292, 0x2C6, 0x022,
0x1AA, 0x256, 0x0D5, 0x02D, 0x050, 0x266, 0x0D5, 0x004,
0x176, 0x295, 0x201, 0x0D3, 0x055, 0x031, 0x2CD, 0x2EA,
0x1E2, 0x261, 0x1EA, 0x28A, 0x004, 0x145, 0x026, 0x1A6,
0x1C6, 0x1F5, 0x2CE, 0x034, 0x051, 0x146, 0x1E1, 0x0B0,
0x1B0, 0x261, 0x0D5, 0x025, 0x142, 0x1C0, 0x07C, 0x0B0,
0x1E6, 0x081, 0x044, 0x02F, 0x2CF, 0x081, 0x290, 0x0A2,
0x1A6, 0x281, 0x0CD, 0x155, 0x031, 0x1A2, 0x086, 0x262,
0x2A1, 0x0CD, 0x0CA, 0x0E6, 0x1E5, 0x003, 0x394, 0x0C5,
0x030, 0x26F, 0x053, 0x0C1, 0x1B6, 0x095, 0x2D4, 0x030,
0x26F, 0x053, 0x0C0, 0x07C, 0x2E6, 0x295, 0x143, 0x2CD,
0x2CE, 0x037, 0x0C9, 0x144, 0x2CD, 0x040, 0x08E, 0x054,
0x282, 0x022, 0x2A1, 0x229, 0x053, 0x0D5, 0x262, 0x027,
0x26A, 0x1E8, 0x14D, 0x1A2, 0x004, 0x26A, 0x296, 0x281,
0x176, 0x295, 0x201, 0x0E2, 0x2C4, 0x143, 0x2D4, 0x026,
0x262, 0x2A0, 0x08F, 0x0C4, 0x031, 0x213, 0x2B5, 0x155,
0x213, 0x02F, 0x143, 0x121, 0x2A6, 0x1AD, 0x2D4, 0x034,
0x0C5, 0x026, 0x295, 0x003, 0x396, 0x2A1, 0x176, 0x295,
0x201, 0x0AA, 0x04E, 0x004, 0x1B0, 0x070, 0x275, 0x154,
0x026, 0x2C1, 0x2B3, 0x154, 0x2AA, 0x256, 0x0C1, 0x044,
0x004, 0x23F },
new int[] {
0x379, 0x099, 0x348, 0x010, 0x090, 0x196, 0x09C, 0x1FF,
0x1B0, 0x32D, 0x244, 0x0DE, 0x201, 0x386, 0x163, 0x11F,
0x39B, 0x344, 0x3FE, 0x02F, 0x188, 0x113, 0x3D9, 0x102,
0x04A, 0x2E1, 0x1D1, 0x18E, 0x077, 0x262, 0x241, 0x20D,
0x1B8, 0x11D, 0x0D0, 0x0A5, 0x29C, 0x24D, 0x3E7, 0x006,
0x2D0, 0x1B7, 0x337, 0x178, 0x0F1, 0x1E0, 0x00B, 0x01E,
0x0DA, 0x1C6, 0x2D9, 0x00D, 0x28B, 0x34A, 0x252, 0x27A,
0x057, 0x0CA, 0x2C2, 0x2E4, 0x3A6, 0x0E3, 0x22B, 0x307,
0x174, 0x292, 0x10C, 0x1ED, 0x2FD, 0x2D4, 0x0A7, 0x051,
0x34F, 0x07A, 0x1D5, 0x01D, 0x22E, 0x2C2, 0x1DF, 0x08F,
0x105, 0x3FE, 0x286, 0x2A2, 0x3B1, 0x131, 0x285, 0x362,
0x315, 0x13C, 0x0F9, 0x1A2, 0x28D, 0x246, 0x1B3, 0x12C,
0x2AD, 0x0F8, 0x222, 0x0EC, 0x39F, 0x358, 0x014, 0x229,
0x0C8, 0x360, 0x1C2, 0x031, 0x098, 0x041, 0x3E4, 0x046,
0x332, 0x318, 0x2E3, 0x24E, 0x3E2, 0x1E1, 0x0BE, 0x239,
0x306, 0x3A5, 0x352, 0x351, 0x275, 0x0ED, 0x045, 0x229,
0x0BF, 0x05D, 0x253, 0x1BE, 0x02E, 0x35A, 0x0E4, 0x2E9,
0x17A, 0x166, 0x03C, 0x007 });
testEncodeDecode(GenericGF.AZTEC_DATA_12, new int[] {
0x571, 0xE1B, 0x542, 0xE12, 0x1E2, 0x0DC, 0xCD0, 0xB85,
0x69A, 0xA81, 0x709, 0xA6A, 0x584, 0x510, 0x4AA, 0x256,
0xCE0, 0x0F8, 0xFB3, 0x5A2, 0x0D9, 0xAD1, 0x389, 0x09C,
0x4D3, 0x0B8, 0xD5B, 0x503, 0x2B2, 0xA81, 0x2A8, 0x4E0,
0x92D, 0x3A5, 0xA81, 0x388, 0x8A6, 0xAA8, 0xAA0, 0x07C,
0xA18, 0xA17, 0x41A, 0xD55, 0x032, 0xB09, 0xC15, 0x142,
0xBB5, 0x2B0, 0x0CE, 0xD59, 0xD9C, 0x1A0, 0x90A, 0xAD5,
0x540, 0x0F8, 0x583, 0xCC4, 0x0B4, 0x509, 0x98D, 0x50C,
0xED5, 0x9D9, 0xC13, 0x52A, 0x023, 0xCC4, 0x092, 0x0FB,
0x89A, 0xD55, 0x02E, 0x15A, 0x6AA, 0x049, 0x079, 0x54E,
0x33E, 0xB67, 0x068, 0xAA8, 0x44E, 0x354, 0x03E, 0x452,
0x2A1, 0x9AD, 0xB50, 0x289, 0x8AE, 0xA28, 0x804, 0x5DA,
0x958, 0x04D, 0x509, 0x20F, 0x458, 0xC11, 0x589, 0x584,
0xC04, 0x7AA, 0x8A0, 0xAA3, 0x4B3, 0x837, 0x55C, 0xD39,
0x882, 0x698, 0xAA0, 0x219, 0x06A, 0x852, 0x679, 0x666,
0x9AA, 0xA13, 0x99A, 0xAA0, 0x6B6, 0x9C5, 0x540, 0xBCC,
0x40B, 0x613, 0x338, 0x03E, 0x3EC, 0xD68, 0x836, 0x6D6,
0x6A2, 0x1A8, 0x021, 0x9AA, 0xA86, 0x266, 0xB4C, 0xFA9,
0xA92, 0xB18, 0x226, 0xAA5, 0x635, 0x42D, 0x142, 0x663,
0x540, 0x45D, 0xA95, 0x804, 0xD31, 0x543, 0x1B3, 0x6EA,
0x78A, 0x617, 0xAA8, 0xA01, 0x145, 0x099, 0xA67, 0x19F,
0x5B3, 0x834, 0x145, 0x467, 0x84B, 0x06C, 0x261, 0x354,
0x255, 0x09C, 0x01F, 0x0B0, 0x798, 0x811, 0x102, 0xFB3,
0xC81, 0xA40, 0xA26, 0x9A8, 0x133, 0x555, 0x0C5, 0xA22,
0x1A6, 0x2A8, 0x4CD, 0x328, 0xE67, 0x940, 0x3E5, 0x0C5,
0x0C2, 0x6F1, 0x4CC, 0x16D, 0x895, 0xB50, 0x309, 0xBC5,
0x330, 0x07C, 0xB9A, 0x955, 0x0EC, 0xDB3, 0x837, 0x325,
0x44B, 0x344, 0x023, 0x854, 0xA08, 0x22A, 0x862, 0x914,
0xCD5, 0x988, 0x279, 0xA9E, 0x853, 0x5A2, 0x012, 0x6AA,
0x5A8, 0x15D, 0xA95, 0x804, 0xE2B, 0x114, 0x3B5, 0x026,
0x98A, 0xA02, 0x3CC, 0x40C, 0x613, 0xAD5, 0x558, 0x4C2,
0xF50, 0xD21, 0xA99, 0xADB, 0x503, 0x431, 0x426, 0xA54,
0x03E, 0x5AA, 0x15D, 0xA95, 0x804, 0xAA1, 0x380, 0x46C,
0x070, 0x9D5, 0x540, 0x9AC, 0x1AC, 0xD54, 0xAAA, 0x563,
0x044, 0x401, 0x220, 0x9F1, 0x4F0, 0xDAA, 0x170, 0x90F,
0x106, 0xE66, 0x85C, 0x2B4, 0xD54, 0x0B8, 0x4D3, 0x52C,
0x228, 0x825, 0x512, 0xB67, 0x007, 0xC7D, 0x9AD, 0x106,
0xCD6, 0x89C, 0x484, 0xE26, 0x985, 0xC6A, 0xDA8, 0x195,
0x954, 0x095, 0x427, 0x049, 0x69D, 0x2D4, 0x09C, 0x445,
0x355, 0x455, 0x003, 0xE50, 0xC50, 0xBA0, 0xD6A, 0xA81,
0x958, 0x4E0, 0xA8A, 0x15D, 0xA95, 0x806, 0x76A, 0xCEC,
0xE0D, 0x048, 0x556, 0xAAA, 0x007, 0xC2C, 0x1E6, 0x205,
0xA28, 0x4CC, 0x6A8, 0x676, 0xACE, 0xCE0, 0x9A9, 0x501,
0x1E6, 0x204, 0x907, 0xDC4, 0xD6A, 0xA81, 0x70A, 0xD35,
0x502, 0x483, 0xCAA, 0x719, 0xF5B, 0x383, 0x455, 0x422,
0x71A, 0xA01, 0xF22, 0x915, 0x0CD, 0x6DA, 0x814, 0x4C5,
0x751, 0x440, 0x22E, 0xD4A, 0xC02, 0x6A8, 0x490, 0x7A2,
0xC60, 0x8AC, 0x4AC, 0x260, 0x23D, 0x545, 0x055, 0x1A5,
0x9C1, 0xBAA, 0xE69, 0xCC4, 0x134, 0xC55, 0x010, 0xC83,
0x542, 0x933, 0xCB3, 0x34D, 0x550, 0x9CC, 0xD55, 0x035,
0xB4E, 0x2AA, 0x05E, 0x620, 0x5B0, 0x999, 0xC01, 0xF1F,
0x66B, 0x441, 0xB36, 0xB35, 0x10D, 0x401, 0x0CD, 0x554,
0x313, 0x35A, 0x67D, 0x4D4, 0x958, 0xC11, 0x355, 0x2B1,
0xAA1, 0x68A, 0x133, 0x1AA, 0x022, 0xED4, 0xAC0, 0x269,
0x8AA, 0x18D, 0x9B7, 0x53C, 0x530, 0xBD5, 0x450, 0x08A,
0x284, 0xCD3, 0x38C, 0xFAD, 0x9C1, 0xA0A, 0x2A3, 0x3C2,
0x583, 0x613, 0x09A, 0xA12, 0xA84, 0xE00, 0xF85, 0x83C,
0xC40, 0x888, 0x17D, 0x9E4, 0x0D2, 0x051, 0x34D, 0x409,
0x9AA, 0xA86, 0x2D1, 0x10D, 0x315, 0x426, 0x699, 0x473,
0x3CA, 0x01F, 0x286, 0x286, 0x137, 0x8A6, 0x60B, 0x6C4,
0xADA, 0x818, 0x4DE, 0x299, 0x803, 0xE5C, 0xD4A, 0xA87,
0x66D, 0x9C1, 0xB99, 0x2A2, 0x59A, 0x201, 0x1C2, 0xA50,
0x411, 0x543, 0x148, 0xA66, 0xACC, 0x413, 0xCD4, 0xF42,
0x9AD, 0x100, 0x935, 0x52D, 0x40A, 0xED4, 0xAC0, 0x271,
0x588, 0xA1D, 0xA81, 0x34C, 0x550, 0x11E, 0x620, 0x630,
0x9D6, 0xAAA, 0xC26, 0x17A, 0x869, 0x0D4, 0xCD6, 0xDA8,
0x1A1, 0x8A1, 0x352, 0xA01, 0xF2D, 0x50A, 0xED4, 0xAC0,
0x255, 0x09C, 0x023, 0x603, 0x84E, 0xAAA, 0x04D, 0x60D,
0x66A, 0xA55, 0x52B, 0x182, 0x220, 0x091, 0x00F, 0x8A7,
0x86D, 0x50B, 0x848, 0x788, 0x373, 0x342, 0xE15, 0xA6A,
0xA05, 0xC26, 0x9A9, 0x611, 0x441, 0x2A8, 0x95B, 0x380,
0x3E3, 0xECD, 0x688, 0x366, 0xB44, 0xE24, 0x271, 0x34C,
0x2E3, 0x56D, 0x40C, 0xACA, 0xA04, 0xAA1, 0x382, 0x4B4,
0xE96, 0xA04, 0xE22, 0x29A, 0xAA2, 0xA80, 0x1F2, 0x862,
0x85D, 0x06B, 0x554, 0x0CA, 0xC27, 0x054, 0x50A, 0xED4,
0xAC0, 0x33B, 0x567, 0x670, 0x682, 0x42A, 0xB55, 0x500,
0x3E1, 0x60F, 0x310, 0x2D1, 0x426, 0x635, 0x433, 0xB56,
0x767, 0x04D, 0x4A8, 0x08F, 0x310, 0x248, 0x3EE, 0x26B,
0x554, 0x0B8, 0x569, 0xAA8, 0x124, 0x1E5, 0x538, 0xCFA,
0xD9C, 0x1A2, 0xAA1, 0x138, 0xD50, 0x0F9, 0x148, 0xA86,
0x6B6, 0xD40, 0xA26, 0x2BA, 0x8A2, 0x011, 0x76A, 0x560,
0x135, 0x424, 0x83D, 0x163, 0x045, 0x625, 0x613, 0x011,
0xEAA, 0x282, 0xA8D, 0x2CE, 0x0DD, 0x573, 0x4E6, 0x209,
0xA62, 0xA80, 0x864, 0x1AA, 0x149, 0x9E5, 0x99A, 0x6AA,
0x84E, 0x66A, 0xA81, 0xADA, 0x715, 0x502, 0xF31, 0x02D,
0x84C, 0xCE0, 0x0F8, 0xFB3, 0x5A2, 0x0D9, 0xB59, 0xA88,
0x6A0, 0x086, 0x6AA, 0xA18, 0x99A, 0xD33, 0xEA6, 0xA4A,
0xC60, 0x89A, 0xA95, 0x8D5, 0x0B4, 0x509, 0x98D, 0x501,
0x176, 0xA56, 0x013, 0x4C5, 0x50C, 0x6CD, 0xBA9, 0xE29,
0x85E, 0xAA2, 0x804, 0x514, 0x266, 0x99C, 0x67D, 0x6CE,
0x0D0, 0x515, 0x19E, 0x12C, 0x1B0, 0x984, 0xD50, 0x954,
0x270, 0x07C, 0x2C1, 0xE62, 0x044, 0x40B, 0xECF, 0x206,
0x902, 0x89A, 0x6A0, 0x4CD, 0x554, 0x316, 0x888, 0x698,
0xAA1, 0x334, 0xCA3, 0x99E, 0x500, 0xF94, 0x314, 0x309,
0xBC5, 0x330, 0x5B6, 0x256, 0xD40, 0xC26, 0xF14, 0xCC0,
0x1F2, 0xE6A, 0x554, 0x3B3, 0x6CE, 0x0DC, 0xC95, 0x12C,
0xD10, 0x08E, 0x152, 0x820, 0x8AA, 0x18A, 0x453, 0x356,
0x620, 0x9E6, 0xA7A, 0x14D, 0x688, 0x049, 0xAA9, 0x6A0,
0x576, 0xA56, 0x013, 0x8AC, 0x450, 0xED4, 0x09A, 0x62A,
0x808, 0xF31, 0x031, 0x84E, 0xB55, 0x561, 0x30B, 0xD43,
0x486, 0xA66, 0xB6D, 0x40D, 0x0C5, 0x09A, 0x950, 0x0F9,
0x6A8, 0x576, 0xA56, 0x012, 0xA84, 0xE01, 0x1B0, 0x1C2,
0x755, 0x502, 0x6B0, 0x6B3, 0x552, 0xAA9, 0x58C, 0x111,
0x004, 0x882, 0x7C5, 0x3C3, 0x6A8, 0x5C2, 0x43C, 0x41B,
0x99A, 0x170, 0xAD3, 0x550, 0x2E1, 0x34D, 0x4B0, 0x8A2,
0x095, 0x44A, 0xD9C, 0x01F, 0x1F6, 0x6B4, 0x41B, 0x35A,
0x271, 0x213, 0x89A, 0x617, 0x1AB, 0x6A0, 0x656, 0x550,
0x255, 0x09C, 0x125, 0xA74, 0xB50, 0x271, 0x114, 0xD55,
0x154, 0x00F, 0x943, 0x142, 0xE83, 0x5AA, 0xA06, 0x561,
0x382, 0xA28, 0x576, 0xA56, 0x019, 0xDAB, 0x3B3, 0x834,
0x121, 0x55A, 0xAA8, 0x01F, 0x0B0, 0x798, 0x816, 0x8A1,
0x331, 0xAA1, 0x9DA, 0xB3B, 0x382, 0x6A5, 0x404, 0x798,
0x812, 0x41F, 0x713, 0x5AA, 0xA05, 0xC2B, 0x4D5, 0x409,
0x20F, 0x2A9, 0xC67, 0xD6C, 0xE0D, 0x155, 0x089, 0xC6A,
0x807, 0xC8A, 0x454, 0x335, 0xB6A, 0x051, 0x315, 0xD45,
0x100, 0x8BB, 0x52B, 0x009, 0xAA1, 0x241, 0xE8B, 0x182,
0x2B1, 0x2B0, 0x980, 0x8F5, 0x514, 0x154, 0x696, 0x706,
0xEAB, 0x9A7, 0x310, 0x4D3, 0x154, 0x043, 0x20D, 0x50A,
0x4CF, 0x2CC, 0xD35, 0x542, 0x733, 0x554, 0x0D6, 0xD38,
0xAA8, 0x179, 0x881, 0x6C2, 0x667, 0x007, 0xC7D, 0x9AD,
0x106, 0xCDA, 0xCD4, 0x435, 0x004, 0x335, 0x550, 0xC4C,
0xD69, 0x9F5, 0x352, 0x563, 0x044, 0xD54, 0xAC6, 0xA85,
0xA28, 0x4CC, 0x6A8, 0x08B, 0xB52, 0xB00, 0x9A6, 0x2A8,
0x636, 0x6DD, 0x4F1, 0x4C2, 0xF55, 0x140, 0x228, 0xA13,
0x34C, 0xE33, 0xEB6, 0x706, 0x828, 0xA8C, 0xF09, 0x60D,
0x84C, 0x26A, 0x84A, 0xA13, 0x803, 0xE16, 0x0F3, 0x102,
0x220, 0x5F6, 0x790, 0x348, 0x144, 0xD35, 0x026, 0x6AA,
0xA18, 0xB44, 0x434, 0xC55, 0x099, 0xA65, 0x1CC, 0xF28,
0x07C, 0xA18, 0xA18, 0x4DE, 0x299, 0x82D, 0xB12, 0xB6A,
0x061, 0x378, 0xA66, 0x00F, 0x973, 0x52A, 0xA1D, 0x9B6,
0x706, 0xE64, 0xA89, 0x668, 0x804, 0x70A, 0x941, 0x045,
0x50C, 0x522, 0x99A, 0xB31, 0x04F, 0x353, 0xD0A, 0x6B4,
0x402, 0x4D5, 0x4B5, 0x02B, 0xB52, 0xB00, 0x9C5, 0x622,
0x876, 0xA04, 0xD31, 0x540, 0x479, 0x881, 0x8C2, 0x75A,
0xAAB, 0x098, 0x5EA, 0x1A4, 0x353, 0x35B, 0x6A0, 0x686,
0x284, 0xD4A, 0x807, 0xCB5, 0x42B, 0xB52, 0xB00, 0x954,
0x270, 0x08D, 0x80E, 0x13A, 0xAA8, 0x135, 0x835, 0x9AA,
0x801, 0xF14, 0xF0D, 0xAA1, 0x709, 0x0F1, 0x06E, 0x668,
0x5C2, 0xB4D, 0x540, 0xB84, 0xD35, 0x2C2, 0x288, 0x255,
0x12B, 0x670, 0x07C, 0x7D9, 0xAD1, 0x06C, 0xD68, 0x9C4,
0x84E, 0x269, 0x85C, 0x6AD, 0xA81, 0x959, 0x540, 0x954,
0x270, 0x496, 0x9D2, 0xD40, 0x9C4, 0x453, 0x554, 0x550,
0x03E, 0x50C, 0x50B, 0xA0D, 0x6AA, 0x819, 0x584, 0xE0A,
0x8A1, 0x5DA, 0x958, 0x067, 0x6AC, 0xECE, 0x0D0, 0x485,
0x56A, 0xAA0, 0x07C, 0x2C1, 0xE62, 0x05A, 0x284, 0xCC6,
0xA86, 0x76A, 0xCEC, 0xE09, 0xA95, 0x011, 0xE62, 0x049,
0x07D, 0xC4D, 0x6AA, 0x817, 0x0AD, 0x355, 0x024, 0x83C,
0xAA7, 0x19F, 0x5B3, 0x834, 0x554, 0x227, 0x1AA, 0x01F,
0x229, 0x150, 0xCD6, 0xDA8, 0x144, 0xC57, 0x514, 0x402,
0x2ED, 0x4AC, 0x026, 0xA84, 0x907, 0xA2C, 0x608, 0xAC4,
0xAC2, 0x602, 0x3D5, 0x450, 0x551, 0xA59, 0xC1B, 0xAAE,
0x69C, 0xC41, 0x34C, 0x550, 0x10C, 0x835, 0x429, 0x33C,
0xB33, 0x4D5, 0x509, 0xCCD, 0x550, 0x35B, 0x4E2, 0xAA0,
0x5E6, 0x205, 0xB09, 0x99C, 0x09F },
new int[] {
0xD54, 0x221, 0x154, 0x7CD, 0xBF3, 0x112, 0x89B, 0xC5E,
0x9CD, 0x07E, 0xFB6, 0x78F, 0x7FA, 0x16F, 0x377, 0x4B4,
0x62D, 0x475, 0xBC2, 0x861, 0xB72, 0x9D0, 0x76A, 0x5A1,
0x22A, 0xF74, 0xDBA, 0x8B1, 0x139, 0xDCD, 0x012, 0x293,
0x705, 0xA34, 0xDD5, 0x3D2, 0x7F8, 0x0A6, 0x89A, 0x346,
0xCE0, 0x690, 0x40E, 0xFF3, 0xC4D, 0x97F, 0x9C9, 0x016,
0x73A, 0x923, 0xBCE, 0xFA9, 0xE6A, 0xB92, 0x02A, 0x07C,
0x04B, 0x8D5, 0x753, 0x42E, 0x67E, 0x87C, 0xEE6, 0xD7D,
0x2BF, 0xFB2, 0xFF8, 0x42F, 0x4CB, 0x214, 0x779, 0x02D,
0x606, 0xA02, 0x08A, 0xD4F, 0xB87, 0xDDF, 0xC49, 0xB51,
0x0E9, 0xF89, 0xAEF, 0xC92, 0x383, 0x98D, 0x367, 0xBD3,
0xA55, 0x148, 0x9DB, 0x913, 0xC79, 0x6FF, 0x387, 0x6EA,
0x7FA, 0xC1B, 0x12D, 0x303, 0xBCA, 0x503, 0x0FB, 0xB14,
0x0D4, 0xAD1, 0xAFC, 0x9DD, 0x404, 0x145, 0x6E5, 0x8ED,
0xF94, 0xD72, 0x645, 0xA21, 0x1A8, 0xABF, 0xC03, 0x91E,
0xD53, 0x48C, 0x471, 0x4E4, 0x408, 0x33C, 0x5DF, 0x73D,
0xA2A, 0x454, 0xD77, 0xC48, 0x2F5, 0x96A, 0x9CF, 0x047,
0x611, 0xE92, 0xC2F, 0xA98, 0x56D, 0x919, 0x615, 0x535,
0x67A, 0x8C1, 0x2E2, 0xBC4, 0xBE8, 0x328, 0x04F, 0x257,
0x3F9, 0xFA5, 0x477, 0x12E, 0x94B, 0x116, 0xEF7, 0x65F,
0x6B3, 0x915, 0xC64, 0x9AF, 0xB6C, 0x6A2, 0x50D, 0xEA3,
0x26E, 0xC23, 0x817, 0xA42, 0x71A, 0x9DD, 0xDA8, 0x84D,
0x3F3, 0x85B, 0xB00, 0x1FC, 0xB0A, 0xC2F, 0x00C, 0x095,
0xC58, 0x0E3, 0x807, 0x962, 0xC4B, 0x29A, 0x6FC, 0x958,
0xD29, 0x59E, 0xB14, 0x95A, 0xEDE, 0xF3D, 0xFB8, 0x0E5,
0x348, 0x2E7, 0x38E, 0x56A, 0x410, 0x3B1, 0x4B0, 0x793,
0xAB7, 0x0BC, 0x648, 0x719, 0xE3E, 0xFB4, 0x3B4, 0xE5C,
0x950, 0xD2A, 0x50B, 0x76F, 0x8D2, 0x3C7, 0xECC, 0x87C,
0x53A, 0xBA7, 0x4C3, 0x148, 0x437, 0x820, 0xECD, 0x660,
0x095, 0x2F4, 0x661, 0x6A4, 0xB74, 0x5F3, 0x1D2, 0x7EC,
0x8E2, 0xA40, 0xA6F, 0xFC3, 0x3BE, 0x1E9, 0x52C, 0x233,
0x173, 0x4EF, 0xA7C, 0x40B, 0x14C, 0x88D, 0xF30, 0x8D9,
0xBDB, 0x0A6, 0x940, 0xD46, 0xB2B, 0x03E, 0x46A, 0x641,
0xF08, 0xAFF, 0x496, 0x68A, 0x7A4, 0x0BA, 0xD43, 0x515,
0xB26, 0xD8F, 0x05C, 0xD6E, 0xA2C, 0xF25, 0x628, 0x4E5,
0x81D, 0xA2A, 0x1FF, 0x302, 0xFBD, 0x6D9, 0x711, 0xD8B,
0xE5C, 0x5CF, 0x42E, 0x008, 0x863, 0xB6F, 0x1E1, 0x3DA,
0xACE, 0x82B, 0x2DB, 0x7EB, 0xC15, 0x79F, 0xA79, 0xDAF,
0x00D, 0x2F6, 0x0CE, 0x370, 0x7E8, 0x9E6, 0x89F, 0xAE9,
0x175, 0xA95, 0x06B, 0x9DF, 0xAFF, 0x45B, 0x823, 0xAA4,
0xC79, 0x773, 0x886, 0x854, 0x0A5, 0x6D1, 0xE55, 0xEBB,
0x518, 0xE50, 0xF8F, 0x8CC, 0x834, 0x388, 0xCD2, 0xFC1,
0xA55, 0x1F8, 0xD1F, 0xE08, 0xF93, 0x362, 0xA22, 0x9FA,
0xCE5, 0x3C3, 0xDD4, 0xC53, 0xB94, 0xAD0, 0x6EB, 0x68D,
0x660, 0x8FC, 0xBCD, 0x914, 0x16F, 0x4C0, 0x134, 0xE1A,
0x76F, 0x9CB, 0x660, 0xEA0, 0x320, 0x15A, 0xCE3, 0x7E8,
0x03E, 0xB9A, 0xC90, 0xA14, 0x256, 0x1A8, 0x639, 0x7C6,
0xA59, 0xA65, 0x956, 0x9E4, 0x592, 0x6A9, 0xCFF, 0x4DC,
0xAA3, 0xD2A, 0xFDE, 0xA87, 0xBF5, 0x9F0, 0xC32, 0x94F,
0x675, 0x9A6, 0x369, 0x648, 0x289, 0x823, 0x498, 0x574,
0x8D1, 0xA13, 0xD1A, 0xBB5, 0xA19, 0x7F7, 0x775, 0x138,
0x949, 0xA4C, 0xE36, 0x126, 0xC85, 0xE05, 0xFEE, 0x962,
0x36D, 0x08D, 0xC76, 0x1E1, 0x1EC, 0x8D7, 0x231, 0xB68,
0x03C, 0x1DE, 0x7DF, 0x2B1, 0x09D, 0xC81, 0xDA4, 0x8F7,
0x6B9, 0x947, 0x9B0 });
// synthetic test cases
testEncodeDecodeRandom(GenericGF.AZTEC_PARAM, 2, 5); // compact mode message
testEncodeDecodeRandom(GenericGF.AZTEC_PARAM, 4, 6); // full mode message
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_6, 10, 7);
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_6, 20, 12);
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_8, 20, 11);
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_8, 128, 127);
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_10, 128, 128);
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_10, 768, 255);
testEncodeDecodeRandom(GenericGF.AZTEC_DATA_12, 3072, 1023);
}
private static void corrupt(int[] received, int howMany, Random random, int max)
{
//BitSet corrupted = new BitSet(received.Length);
var corrupted = new BitArray(received.Length);
for (int j = 0; j < howMany; j++)
{
int location = random.Next(received.Length);
int value = random.Next(max);
if (corrupted[location] || received[location] == value)
{
j--;
}
else
{
corrupted[location] = true;
received[location] = value;
}
}
}
private static void testEncodeDecodeRandom(GenericGF field, int dataSize, int ecSize)
{
Assert.IsTrue(dataSize > 0 && dataSize <= field.Size - 3, "Invalid data size for " + field);
Assert.IsTrue(ecSize > 0 && ecSize + dataSize <= field.Size, "Invalid ECC size for " + field);
ReedSolomonEncoder encoder = new ReedSolomonEncoder(field);
int[] message = new int[dataSize + ecSize];
int[] dataWords = new int[dataSize];
int[] ecWords = new int[ecSize];
Random random = getPseudoRandom();
int iterations = field.Size > 256 ? 1 : DECODER_RANDOM_TEST_ITERATIONS;
for (int i = 0; i < iterations; i++)
{
// generate random data
for (int k = 0; k < dataSize; k++)
{
dataWords[k] = random.Next(field.Size);
}
// generate ECC words
Array.Copy(dataWords, 0, message, 0, dataWords.Length);
encoder.encode(message, ecWords.Length);
Array.Copy(message, dataSize, ecWords, 0, ecSize);
// check to see if Decoder can fix up to ecWords/2 random errors
testDecoder(field, dataWords, ecWords);
}
}
private static void testEncodeDecode(GenericGF field, int[] dataWords, int[] ecWords)
{
testEncoder(field, dataWords, ecWords);
testDecoder(field, dataWords, ecWords);
}
private static void testEncoder(GenericGF field, int[] dataWords, int[] ecWords)
{
ReedSolomonEncoder encoder = new ReedSolomonEncoder(field);
int[] messageExpected = new int[dataWords.Length + ecWords.Length];
int[] message = new int[dataWords.Length + ecWords.Length];
Array.Copy(dataWords, 0, messageExpected, 0, dataWords.Length);
Array.Copy(ecWords, 0, messageExpected, dataWords.Length, ecWords.Length);
Array.Copy(dataWords, 0, message, 0, dataWords.Length);
encoder.encode(message, ecWords.Length);
assertDataEquals("Encode in " + field + " (" + dataWords.Length + ',' + ecWords.Length + ") failed",
messageExpected, message);
}
private static void testDecoder(GenericGF field, int[] dataWords, int[] ecWords)
{
ReedSolomonDecoder decoder = new ReedSolomonDecoder(field);
int[] message = new int[dataWords.Length + ecWords.Length];
int maxErrors = ecWords.Length / 2;
Random random = getPseudoRandom();
int iterations = field.Size > 256 ? 1 : DECODER_TEST_ITERATIONS;
for (int j = 0; j < iterations; j++)
{
for (int i = 0; i < ecWords.Length; i++)
{
if (i > 10 && i < ecWords.Length / 2 - 10)
{
// performance improvement - skip intermediate cases in long-running tests
i += ecWords.Length / 10;
}
Array.Copy(dataWords, 0, message, 0, dataWords.Length);
Array.Copy(ecWords, 0, message, dataWords.Length, ecWords.Length);
corrupt(message, i, random, field.Size);
if (!decoder.decode(message, ecWords.Length))
{
// fail only if maxErrors exceeded
Assert.IsTrue(i > maxErrors, "Decode in " + field + " (" + dataWords.Length + ',' + ecWords.Length + ") failed at " + i);
// else stop
break;
}
if (i < maxErrors)
{
assertDataEquals("Decode in " + field + " (" + dataWords.Length + ',' + ecWords.Length + ") failed at " +
i + " errors",
dataWords,
message);
}
}
}
}
private static void assertDataEquals(String message, int[] expected, int[] received)
{
for (int i = 0; i < expected.Length; i++)
{
if (expected[i] != received[i])
{
var receivedCopy = new int[expected.Length];
Array.Copy(received, receivedCopy, expected.Length);
Assert.Fail(message + ". Mismatch at " + i + ". Expected " + arrayToString(expected) + ", got " +
arrayToString(receivedCopy));
}
}
}
private static String arrayToString(int[] data)
{
StringBuilder sb = new StringBuilder("{");
for (int i = 0; i < data.Length; i++)
{
sb.AppendFormat(i > 0 ? ",%X" : "%X", data[i]);
}
return sb.Append('}').ToString();
}
private static Random getPseudoRandom()
{
// return new SecureRandom(new byte[] {(byte) 0xDE, (byte) 0xAD, (byte) 0xBE, (byte) 0xEF});
return new Random((int)DateTime.Now.Ticks);
}
}
}
| |
using Loon.Core.Graphics;
using Loon.Action.Map;
using Loon.Utils;
using Loon.Utils.Collection;
using System.Collections.Generic;
using Loon.Core.Geom;
using Loon.Core;
using Loon.Action.Sprite.Node;
using System.Runtime.CompilerServices;
using System.IO;
using System;
using Loon.Core.Input;
using Loon.Core.Event;
using Loon.Core.Timer;
using Loon.Core.Graphics.Opengl;
using Loon.Physics;
using Loon.Java;
namespace Loon.Action.Sprite
{
public abstract class SpriteBatchScreen : Screen
{
private int keySize = 0;
private float objX = 0, objY = 0;
private ArrayMap keyActions = new ArrayMap(CollectionUtils.INITIAL_CAPACITY);
private SpriteBatch batch;
private List<SpriteBatchObject> objects;
private List<SpriteBatchObject> pendingAdd;
private List<SpriteBatchObject> pendingRemove;
private List<TileMap> tiles = new List<TileMap>(10);
private Vector2f offset = new Vector2f();
private LObject follow;
private TileMap indexTile;
private LNNode content;
private LNNode modal;
private LNNode hoverNode;
private LNNode selectedNode;
private LNNode[] clickNode = new LNNode[1];
private bool isClicked;
protected internal UpdateListener updateListener;
private bool usePhysics = false;
private PPhysManager _manager;
private PWorldBox _box;
private bool _fixed = false;
private float _dt = 1F / 60F;
private void LimitWorld(bool _fixed) {
if (_fixed) {
if (this._box == null) {
this._box = new PWorldBox(_manager, 0f, 0f, GetWidth(),
GetHeight());
}
if (_physicsRect != null) {
this._box.Set(_physicsRect.x, _physicsRect.y,
_physicsRect.width, _physicsRect.height);
}
this._box.Build();
} else {
if (_box != null) {
this._box.RemoveWorld();
}
}
}
public PPhysManager GetPhysicsManager() {
if (!usePhysics) {
throw new Loon.Java.RuntimeException("You do not set the physics engine !");
}
return _manager;
}
public bool IsPhysics() {
return usePhysics;
}
private RectBox _physicsRect;
public void SetPhysicsRect(float x, float y, float w, float h) {
if (this._physicsRect == null) {
this._physicsRect = new RectBox(x, y, w, h);
} else {
this._physicsRect.SetBounds(x, y, w, h);
}
}
public void SetPhysics(bool fix, PPhysManager man) {
this._manager = man;
this._fixed = fix;
this.LimitWorld(_fixed);
this.usePhysics = true;
}
public void SetPhysics(bool fix, float scale, float gx, float gy) {
if (_manager == null) {
this._manager = new PPhysManager(scale, gx, gy);
} else {
this._manager.scale = scale;
this._manager.gravity.Set(gx, gy);
}
this._manager.SetEnableGravity(true);
this._manager.SetStart(true);
this._fixed = fix;
this.LimitWorld(_fixed);
this.usePhysics = true;
}
public void SetPhysics(bool fix) {
SetPhysics(fix, 10F);
}
public void SetPhysics(bool fix, float scale) {
if (_manager == null) {
this._manager = new PPhysManager(scale);
} else {
this._manager.scale = scale;
}
this._manager.SetEnableGravity(true);
this._manager.SetStart(true);
this._fixed = fix;
this.LimitWorld(_fixed);
this.usePhysics = true;
}
public float GetTimeStep() {
return this._dt;
}
public void SetTimeStep(float dt) {
this._dt = dt;
}
public override void OnResume() {
if (usePhysics) {
_manager.SetStart(true);
_manager.SetEnableGravity(true);
}
}
public override void OnPause()
{
if (usePhysics) {
_manager.SetStart(false);
_manager.SetEnableGravity(false);
}
}
public bool IsFixed() {
return _fixed;
}
public void SetUpdateListener(UpdateListener u)
{
this.updateListener = u;
}
public interface UpdateListener
{
void Act(SpriteBatchObject obj, long elapsedTime);
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void LoadNodeDef(string resName)
{
DefinitionReader.Get().Load(resName);
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void LoadNodeDef(Stream res)
{
DefinitionReader.Get().Load(res);
}
public SpriteBatchScreen()
: base()
{
this.objects = new List<SpriteBatchObject>(10);
this.pendingAdd = new List<SpriteBatchObject>(10);
this.pendingRemove = new List<SpriteBatchObject>(10);
this.Init();
}
public virtual SpriteBatch GetSpriteBatch()
{
return batch;
}
private void Init()
{
SetNode(new LNNode(this, LSystem.screenRect));
}
public virtual void SetNode(LNNode node)
{
if (content == node)
{
return;
}
this.content = node;
}
public virtual LNNode Node()
{
return content;
}
public virtual int Size()
{
return (content == null) ? 0 : content.GetNodeCount();
}
public virtual void RunAction(LNAction action)
{
if (content != null)
{
content.RunAction(action);
}
}
public virtual void AddNode(LNNode node)
{
AddNode(node, 0);
}
public virtual void Add(LNNode node)
{
AddNode(node, 0);
}
public virtual void AddNode(LNNode node, int z)
{
if (node == null)
{
return;
}
this.content.AddNode(node, z);
this.ProcessTouchMotionEvent();
}
public virtual int RemoveNode(LNNode node)
{
int removed = this.RemoveNode(this.content, node);
if (removed != -1)
{
this.ProcessTouchMotionEvent();
}
return removed;
}
public virtual int RemoveNode(Type clazz)
{
int removed = this.RemoveNode(this.content, clazz);
if (removed != -1)
{
this.ProcessTouchMotionEvent();
}
return removed;
}
private int RemoveNode(LNNode container, LNNode node)
{
int removed = container.RemoveNode(node);
LNNode[] nodes = container.childs;
int i = 0;
while (removed == -1 && i < nodes.Length - 1)
{
if (nodes[i].IsContainer())
{
removed = this.RemoveNode(nodes[i], node);
}
i++;
}
return removed;
}
private int RemoveNode(LNNode container, Type clazz)
{
int removed = container.RemoveNode(clazz);
LNNode[] nodes = container.childs;
int i = 0;
while (removed == -1 && i < nodes.Length - 1)
{
if (nodes[i].IsContainer())
{
removed = this.RemoveNode(nodes[i], clazz);
}
i++;
}
return removed;
}
private void ProcessEvents()
{
this.ProcessTouchMotionEvent();
if (this.hoverNode != null && this.hoverNode.IsEnabled())
{
this.ProcessTouchEvent();
}
if (this.selectedNode != null && this.selectedNode.IsEnabled())
{
this.ProcessKeyEvent();
}
}
private void ProcessTouchMotionEvent()
{
if (this.hoverNode != null && this.hoverNode.IsEnabled()
&& this.GetInput().IsMoving())
{
if (GetTouchDY() != 0 || GetTouchDY() != 0)
{
this.hoverNode.ProcessTouchDragged();
}
}
else
{
if (Touch.IsDrag() || Touch.IsMove() || Touch.IsDown())
{
LNNode node = this.FindNode(GetTouchX(), GetTouchY());
if (node != null)
{
this.hoverNode = node;
}
}
}
}
private void ProcessTouchEvent()
{
int pressed = GetTouchPressed(), released = GetTouchReleased();
if (pressed > NO_BUTTON)
{
if (!isClicked)
{
this.hoverNode.ProcessTouchPressed();
}
this.clickNode[0] = this.hoverNode;
if (this.hoverNode.IsFocusable())
{
if ((pressed == Touch.TOUCH_DOWN || pressed == Touch.TOUCH_UP)
&& this.hoverNode != this.selectedNode)
{
this.SelectNode(this.hoverNode);
}
}
}
if (released > NO_BUTTON)
{
if (!isClicked)
{
this.hoverNode.ProcessTouchReleased();
}
}
this.isClicked = false;
}
private void ProcessKeyEvent()
{
if (GetKeyPressed() != NO_KEY)
{
this.selectedNode.KeyPressed();
}
if (GetKeyReleased() != NO_KEY && this.selectedNode != null)
{
this.selectedNode.ProcessKeyReleased();
}
}
public virtual LNNode FindNode(int x, int y)
{
if (content == null)
{
return null;
}
if (this.modal != null && !this.modal.IsContainer())
{
return content.FindNode(x, y);
}
LNNode panel = (this.modal == null) ? this.content
: (this.modal);
LNNode node = panel.FindNode(x, y);
return node;
}
public virtual void ClearFocus()
{
this.DeselectNode();
}
internal void DeselectNode()
{
if (this.selectedNode == null)
{
return;
}
this.selectedNode.SetSelected(false);
this.selectedNode = null;
}
public virtual bool SelectNode(LNNode node)
{
if (!node.IsVisible() || !node.IsEnabled() || !node.IsFocusable())
{
return false;
}
this.DeselectNode();
node.SetSelected(true);
this.selectedNode = node;
return true;
}
public virtual void SetNodeStat(LNNode node, bool active)
{
if (!active)
{
if (this.hoverNode == node)
{
this.ProcessTouchMotionEvent();
}
if (this.selectedNode == node)
{
this.DeselectNode();
}
this.clickNode[0] = null;
if (this.modal == node)
{
this.modal = null;
}
}
else
{
this.ProcessTouchMotionEvent();
}
if (node == null)
{
return;
}
if (node.IsContainer())
{
LNNode[] nodes = (node).childs;
int size = (node).GetNodeCount();
for (int i = 0; i < size; i++)
{
this.SetNodeStat(nodes[i], active);
}
}
}
public virtual void ClearNodesStat(LNNode[] node)
{
bool checkTouchMotion = false;
for (int i = 0; i < node.Length; i++)
{
if (this.hoverNode == node[i])
{
checkTouchMotion = true;
}
if (this.selectedNode == node[i])
{
this.DeselectNode();
}
this.clickNode[0] = null;
}
if (checkTouchMotion)
{
this.ProcessTouchMotionEvent();
}
}
internal void ValidateContainer(LNNode container)
{
if (content == null)
{
return;
}
LNNode[] nodes = container.childs;
int size = container.GetNodeCount();
for (int i = 0; i < size; i++)
{
if (nodes[i].IsContainer())
{
this.ValidateContainer(nodes[i]);
}
}
}
public virtual List<LNNode> GetNodes(Type clazz)
{
if (content == null)
{
return null;
}
if (clazz == null)
{
return null;
}
LNNode[] nodes = content.childs;
int size = nodes.Length;
List<LNNode> l = new List<LNNode>(size);
for (int i = size; i > 0; i--)
{
LNNode node = nodes[i - 1];
Type cls = node.GetType();
if (clazz == null || clazz == cls || clazz.IsInstanceOfType(node)
|| clazz.Equals(cls))
{
l.Add(node);
}
}
return l;
}
public virtual LNNode GetTopNode()
{
if (content == null)
{
return null;
}
LNNode[] nodes = content.childs;
int size = nodes.Length;
if (size > 1)
{
return nodes[1];
}
return null;
}
public virtual LNNode GetBottomNode()
{
if (content == null)
{
return null;
}
LNNode[] nodes = content.childs;
int size = nodes.Length;
if (size > 0)
{
return nodes[size - 1];
}
return null;
}
public virtual void SetSize(int w, int h)
{
if (content != null)
{
this.content.SetSize(w, h);
}
}
public virtual LNNode GetHoverNode()
{
return this.hoverNode;
}
public virtual LNNode GetSelectedNode()
{
return this.selectedNode;
}
public virtual LNNode GetModal()
{
return this.modal;
}
public virtual void SetModal(LNNode node)
{
if (node != null && !node.IsVisible())
{
throw new Exception(
"Can't set invisible node as modal node!");
}
this.modal = node;
}
public virtual LNNode Get()
{
if (content != null)
{
return content.Get();
}
return null;
}
public virtual void Commits()
{
if (IsClose())
{
return;
}
int additionCount = pendingAdd.Count;
if (additionCount > 0)
{
for (int i = 0; i < additionCount; i++)
{
SpriteBatchObject obj = pendingAdd[i];
objects.Add(obj);
}
pendingAdd.Clear();
}
int removalCount = pendingRemove.Count;
if (removalCount > 0)
{
for (int i = 0; i < removalCount; i++)
{
SpriteBatchObject obj = pendingRemove[i];
CollectionUtils.Remove(objects, obj);
}
pendingRemove.Clear();
}
}
public virtual SpriteBatchObject Add(SpriteBatchObject obj0)
{
pendingAdd.Add(obj0);
return obj0;
}
public virtual SpriteBatchObject Remove(SpriteBatchObject obj0)
{
pendingRemove.Add(obj0);
if (usePhysics)
{
UnbindPhysics(obj0);
}
return obj0;
}
public virtual void RemoveTileObjects()
{
int count = objects.Count;
SpriteBatchObject[] objectArray = objects.ToArray();
for (int i = 0; i < count; i++)
{
SpriteBatchObject o = (SpriteBatchObject)objectArray[i];
pendingRemove.Add(o);
if (usePhysics)
{
UnbindPhysics(o);
}
}
pendingAdd.Clear();
}
public virtual SpriteBatchObject FindObject(float x, float y)
{
foreach (SpriteBatchObject o in objects)
{
if ((o.GetX() == x && o.GetY() == y) || (o.GetRectBox().Contains(x, y)))
{
return o;
}
}
return null;
}
public virtual TileMap GetIndexTile()
{
return indexTile;
}
public virtual void SetIndexTile(TileMap indexTile)
{
this.indexTile = indexTile;
}
public virtual void Follow(LObject o)
{
this.follow = o;
}
public override void OnLoad()
{
if (batch == null)
{
batch = new SpriteBatch(1024);
}
content.SetScreen(this);
foreach (LNNode node in content.childs)
{
if (node != null)
{
node.OnSceneActive();
}
}
}
public override void OnLoaded()
{
Create();
}
public abstract void Create();
public virtual void AddActionKey(Int32 keyCode, ActionKey e)
{
keyActions.Put(keyCode, e);
keySize = keyActions.Size();
}
public virtual void RemoveActionKey(Int32 keyCode)
{
keyActions.Remove(keyCode);
keySize = keyActions.Size();
}
public virtual void PressActionKey(Int32 keyCode)
{
ActionKey key = (ActionKey)keyActions.GetValue(keyCode);
if (key != null)
{
key.Press();
}
}
public virtual void ReleaseActionKey(Int32 keyCode)
{
ActionKey key = (ActionKey)keyActions.GetValue(keyCode);
if (key != null)
{
key.Release();
}
}
public virtual void ClearActionKey()
{
keyActions.Clear();
keySize = 0;
}
public virtual void ReleaseActionKeys()
{
keySize = keyActions.Size();
if (keySize > 0)
{
for (int i = 0; i < keySize; i++)
{
ActionKey act = (ActionKey)keyActions.Get(i);
act.Release();
}
}
}
public virtual void SetOffset(TileMap tile, float sx, float sy)
{
offset.Set(sx, sy);
tile.SetOffset(offset);
}
public virtual Vector2f GetOffset()
{
return offset;
}
public virtual void putTileMap(TileMap t)
{
tiles.Add(t);
}
public virtual void RemoveTileMap(TileMap t)
{
tiles.Remove(t);
}
public virtual void AddTileObject(SpriteBatchObject o)
{
Add(o);
}
public virtual JumpObject AddJumpObject(float x, float y, float w, float h,
Animation a)
{
JumpObject o = null;
if (indexTile != null)
{
o = new JumpObject(x, y, w, h, a, indexTile);
}
else if (tiles.Count > 0)
{
o = new JumpObject(x, y, w, h, a, tiles[0]);
}
else
{
return null;
}
Add(o);
return o;
}
public virtual MoveObject AddMoveObject(float x, float y, float w, float h,
Animation a)
{
MoveObject o = null;
if (indexTile != null)
{
o = new MoveObject(x, y, w, h, a, indexTile);
}
else if (tiles.Count > 0)
{
o = new MoveObject(x, y, w, h, a, tiles[0]);
}
else
{
return null;
}
Add(o);
return o;
}
public virtual void RemoveTileObject(SpriteBatchObject o)
{
Remove(o);
}
private Dictionary<SpriteBatchObject, PBody> _Bodys = new Dictionary<SpriteBatchObject, PBody>(
CollectionUtils.INITIAL_CAPACITY);
public PBody FindPhysics(SpriteBatchObject o)
{
if (usePhysics)
{
PBody body = (PBody)CollectionUtils.Get(_Bodys, o);
return body;
}
else
{
throw new RuntimeException("You do not set the physics engine !");
}
}
public void UnbindPhysics(SpriteBatchObject o)
{
if (usePhysics)
{
PBody body = (PBody)CollectionUtils.Remove(_Bodys, o);
if (body != null)
{
body.SetTag(null);
_manager.world.RemoveBody(body);
}
}
}
public PBody AddPhysics(bool fix, SpriteBatchObject o, float density)
{
return BindPhysics(fix, Add(o), density);
}
public PBody AddPhysics(bool fix, SpriteBatchObject o)
{
return BindPhysics(fix, Add(o), 1F);
}
public PBody AddTexturePhysics(bool fix, SpriteBatchObject o,
float density)
{
return BindTexturePhysics(fix, Add(o), density);
}
public PBody AddTexturePhysics(bool fix, SpriteBatchObject o)
{
return BindTexturePhysics(fix, Add(o), 1F);
}
public PBody BindPhysics(bool fix, SpriteBatchObject o, float density)
{
if (usePhysics)
{
PBody body = _manager.AddBox(fix, o.GetRectBox(),
MathUtils.ToRadians(o.GetRotation()), density);
body.SetTag(o);
CollectionUtils.Put(_Bodys,o, body);
return body;
}
else
{
throw new RuntimeException("You do not set the physics engine !");
}
}
public PBody AddCirclePhysics(bool fix, SpriteBatchObject o,
float density)
{
return BindCirclePhysics(fix, Add(o), density);
}
public PBody AddCirclePhysics(bool fix, SpriteBatchObject o)
{
return BindCirclePhysics(fix, Add(o), 1F);
}
public PBody BindCirclePhysics(bool fix, SpriteBatchObject o)
{
return BindCirclePhysics(fix, Add(o), 1F);
}
public PBody BindCirclePhysics(bool fix, SpriteBatchObject o,
float density)
{
if (usePhysics)
{
RectBox rect = o.GetRectBox();
float r = (rect.width + rect.height) / 4;
PBody body = _manager.AddCircle(fix, o.X(), o.Y(), r,
MathUtils.ToRadians(o.GetRotation()), density);
body.SetTag(o);
CollectionUtils.Put(_Bodys,o, body);
return body;
}
else
{
throw new RuntimeException("You do not set the physics engine !");
}
}
public PBody BindTexturePhysics(bool fix, SpriteBatchObject o,
float density)
{
if (usePhysics)
{
PBody body = _manager.AddShape(fix, o.GetAnimation()
.GetSpriteImage(), MathUtils.ToRadians(o.GetRotation()),
density);
if (body.Size() > 0)
{
body.Inner_shapes()[0].SetPosition(o.X() / _manager.scale,
o.Y() / _manager.scale);
}
body.SetTag(o);
CollectionUtils.Put(_Bodys, o, body);
return body;
}
else
{
throw new RuntimeException("You do not set the physics engine !");
}
}
public PBody BindTexturePhysics(bool fix, SpriteBatchObject o)
{
return BindTexturePhysics(fix, o, 1F);
}
public PBody BindPhysics(bool fix, SpriteBatchObject o)
{
return BindPhysics(fix, o, 1F);
}
public PBody BindPhysics(PBody body, SpriteBatchObject o)
{
if (usePhysics)
{
body.SetTag(o);
_manager.AddBody(body);
CollectionUtils.Put(_Bodys, o, body);
return body;
}
else
{
throw new RuntimeException("You do not set the physics engine !");
}
}
public override void Alter(LTimerContext timer)
{
for (int i = 0; i < keySize; i++)
{
ActionKey act = (ActionKey)keyActions.Get(i);
if (act.IsPressed())
{
act.Act(elapsedTime);
if (act.isReturn)
{
return;
}
}
}
if (content.IsVisible())
{
ProcessEvents();
content.UpdateNode(timer.GetMilliseconds());
}
if (usePhysics)
{
if (_dt < 0)
{
_manager.Step(timer.GetMilliseconds());
}
else
{
_manager.Step(_dt);
}
}
if (follow != null)
{
if (usePhysics)
{
_manager.Offset(follow.GetX(), follow.GetY());
}
foreach (TileMap tile in tiles)
{
float offsetX = GetHalfWidth() - follow.GetX();
offsetX = MathUtils.Min(offsetX, 0);
offsetX = MathUtils.Max(offsetX, GetWidth() - tile.GetWidth());
float offsetY = GetHalfHeight() - follow.GetY();
offsetY = MathUtils.Min(offsetY, 0);
offsetY = MathUtils
.Max(offsetY, GetHeight() - tile.GetHeight());
SetOffset(tile, offsetX, offsetY);
tile.Update(elapsedTime);
}
}
foreach (SpriteBatchObject o in objects)
{
if (usePhysics)
{
PBody body = (PBody)CollectionUtils.Get(_Bodys, o);
if (body != null)
{
PShape shape = body.Inner_shapes()[0];
float rotation = (shape.GetAngle() * MathUtils.RAD_TO_DEG) % 360;
AABB aabb = shape.GetAABB();
o.SetLocation(_manager.GetScreenX(aabb.minX),
_manager.GetScreenY(aabb.minY));
o.SetRotation(rotation);
}
}
o.Update(elapsedTime);
if (updateListener != null)
{
updateListener.Act(o, elapsedTime);
}
}
Update(elapsedTime);
Commits();
}
public override void Draw(GLEx g)
{
if (IsOnLoadComplete())
{
batch.Begin();
Before(batch);
foreach (TileMap tile in tiles)
{
tile.Draw(g, batch, offset.X(), offset.Y());
}
foreach (SpriteBatchObject o in objects)
{
objX = o.GetX() + offset.x;
objY = o.GetY() + offset.y;
if (Contains(objX, objY))
{
o.Draw(batch, offset.x, offset.y);
}
}
if (content.IsVisible())
{
content.DrawNode(batch);
}
After(batch);
batch.End();
}
}
public abstract void After(SpriteBatch batch);
public abstract void Before(SpriteBatch batch);
public override void OnKeyDown(LKey e)
{
keySize = keyActions.Size();
if (keySize > 0)
{
int keyCode = e.GetKeyCode();
for (int i = 0; i < keySize; i++)
{
Int32 code = (Int32)keyActions.GetKey(i);
if (code == keyCode)
{
ActionKey act = (ActionKey)keyActions.GetValue(code);
act.Press();
}
}
}
Press(e);
}
public abstract void Press(LKey e);
public override void OnKeyUp(LKey e)
{
keySize = keyActions.Size();
if (keySize > 0)
{
int keyCode = e.GetKeyCode();
for (int i = 0; i < keySize; i++)
{
Int32 code = (Int32)keyActions.GetKey(i);
if (code == keyCode)
{
ActionKey act = (ActionKey)keyActions.GetValue(code);
act.Release();
}
}
}
Release(e);
}
public abstract void Release(LKey e);
public abstract void Update(long elapsedTime);
public abstract void Close();
public override void SetAutoDestory(bool a)
{
base.SetAutoDestory(a);
if (content != null)
{
content.SetAutoDestroy(a);
}
}
public override bool IsAutoDestory()
{
if (content != null)
{
return content.IsAutoDestory();
}
return base.IsAutoDestory();
}
public override void Dispose()
{
if (usePhysics)
{
_manager.SetStart(false);
_manager.SetEnableGravity(false);
_Bodys.Clear();
}
this.keySize = 0;
if (batch != null)
{
batch.Dispose();
batch = null;
}
if (content != null)
{
content.Dispose();
content = null;
}
if (indexTile != null)
{
indexTile.Dispose();
indexTile = null;
}
if (objects != null)
{
objects.Clear();
objects = null;
}
if (pendingAdd != null)
{
pendingAdd.Clear();
pendingAdd = null;
}
if (pendingRemove != null)
{
pendingRemove.Clear();
pendingRemove = null;
}
tiles.Clear();
Close();
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml;
using Gallio.Common;
using Gallio.Common.Platform;
using Gallio.Properties;
using Gallio.Common.Reflection;
using Gallio.Runtime.Extensibility;
using Gallio.Runtime.Loader;
using Gallio.Runtime.Logging;
using Gallio.Runtime.ProgressMonitoring;
namespace Gallio.Runtime
{
/// <summary>
/// Default implementation of <see cref="IRuntime" />.
/// </summary>
public class DefaultRuntime : IRuntime
{
private IRegistry registry;
private readonly IPluginLoader pluginLoader;
private readonly IAssemblyLoader assemblyLoader;
private readonly RuntimeSetup runtimeSetup;
private readonly List<string> pluginDirectories;
private readonly DispatchLogger dispatchLogger;
private readonly RuntimeConditionContext conditionContext;
private bool debugMode;
/// <summary>
/// Initializes the runtime.
/// </summary>
/// <param name="registry">The registry.</param>
/// <param name="pluginLoader">The plugin loader.</param>
/// <param name="assemblyLoader">The assembly loader.</param>
/// <param name="runtimeSetup">The runtime setup options.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="registry"/>,
/// <paramref name="pluginLoader"/>, <paramref name="assemblyLoader"/> or
/// <paramref name="runtimeSetup" /> is null.</exception>
public DefaultRuntime(IRegistry registry, IPluginLoader pluginLoader,
IAssemblyLoader assemblyLoader, RuntimeSetup runtimeSetup)
{
if (registry == null)
throw new ArgumentNullException("registry");
if (pluginLoader == null)
throw new ArgumentNullException("pluginLoader");
if (assemblyLoader == null)
throw new ArgumentNullException(@"assemblyResolverManager");
if (runtimeSetup == null)
throw new ArgumentNullException(@"runtimeSetup");
this.registry = registry;
this.pluginLoader = pluginLoader;
this.assemblyLoader = assemblyLoader;
this.runtimeSetup = runtimeSetup.Copy();
dispatchLogger = new DispatchLogger();
pluginDirectories = new List<string>();
conditionContext = new RuntimeConditionContext();
}
/// <inheritdoc />
public void Dispose()
{
if (registry != null)
{
registry.Dispose();
registry = null;
}
}
/// <inheritdoc />
public IRegistry Registry
{
get
{
ThrowIfDisposed();
return registry;
}
}
/// <inheritdoc />
public IServiceLocator ServiceLocator
{
get
{
ThrowIfDisposed();
return registry.ServiceLocator;
}
}
/// <inheritdoc />
public IResourceLocator ResourceLocator
{
get
{
ThrowIfDisposed();
return registry.ResourceLocator;
}
}
/// <inheritdoc />
public ILogger Logger
{
get
{
ThrowIfDisposed();
return dispatchLogger;
}
}
/// <inheritdoc />
public IAssemblyLoader AssemblyLoader
{
get
{
ThrowIfDisposed();
return assemblyLoader;
}
}
/// <inheritdoc />
public RuntimeConditionContext RuntimeConditionContext
{
get
{
ThrowIfDisposed();
return conditionContext;
}
}
/// <inheritdoc />
public void Initialize()
{
ThrowIfDisposed();
try
{
ConfigureForDebugging();
SetRuntimePath();
SetInstallationConfiguration();
ConfigureDefaultPluginDirectories();
ConfigurePluginDirectoriesFromSetup();
ConfigurePluginDirectoriesFromInstallationConfiguration();
ConfigurePluginLoaderForInstallationId();
RegisterBuiltInComponents();
RegisterLoadedPlugins();
foreach (IPluginDescriptor pluginDescriptor in registry.Plugins)
{
if (! pluginDescriptor.IsDisabled
&& pluginDescriptor.EnableCondition != null
&& !pluginDescriptor.EnableCondition.Evaluate(conditionContext))
{
pluginDescriptor.Disable(string.Format("The plugin enable condition was not satisfied. "
+ "Please note that this is the intended behavior for plugins that must be hosted inside third party applications in order to work. "
+ "Enable condition: '{0}'.", pluginDescriptor.EnableCondition));
}
}
foreach (IPluginDescriptor pluginDescriptor in registry.Plugins)
{
if (! pluginDescriptor.IsDisabled)
{
foreach (string searchPath in pluginDescriptor.GetSearchPaths(null))
assemblyLoader.AddHintDirectory(searchPath);
}
}
LogDisabledPlugins();
}
catch (Exception ex)
{
throw new RuntimeException(Resources.DefaultRuntime_RuntimeCannotBeInitialized, ex);
}
}
private void RegisterBuiltInComponents()
{
IPluginDescriptor builtInPlugin = registry.RegisterPlugin(
new PluginRegistration("BuiltIn", new TypeName(typeof(DefaultPlugin)), new DirectoryInfo(runtimeSetup.RuntimePath))
{
TraitsProperties =
{
{ "Name", "Gallio Built-In Components" },
{ "Description", "Provides built-in runtime services." },
{ "Version", typeof(DefaultRuntime).Assembly.GetName().Version.ToString() }
}
});
RegisterBuiltInComponent(builtInPlugin, "BuiltIn.Registry", typeof(IRegistry), registry);
RegisterBuiltInComponent(builtInPlugin, "BuiltIn.ServiceLocator", typeof(IServiceLocator), registry.ServiceLocator);
RegisterBuiltInComponent(builtInPlugin, "BuiltIn.Logger", typeof(ILogger), dispatchLogger);
RegisterBuiltInComponent(builtInPlugin, "BuiltIn.Runtime", typeof(IRuntime), this);
RegisterBuiltInComponent(builtInPlugin, "BuiltIn.AssemblyLoader", typeof(IAssemblyLoader), assemblyLoader);
RegisterBuiltInComponent(builtInPlugin, "BuiltIn.PluginLoader", typeof(IPluginLoader), pluginLoader);
}
private void RegisterBuiltInComponent(IPluginDescriptor builtInPluginDescriptor,
string serviceId, Type serviceType, object component)
{
IServiceDescriptor serviceDescriptor = registry.RegisterService(
new ServiceRegistration(builtInPluginDescriptor, serviceId, new TypeName(serviceType)));
registry.RegisterComponent(
new ComponentRegistration(builtInPluginDescriptor, serviceDescriptor, serviceId, new TypeName(component.GetType()))
{
ComponentHandlerFactory = new InstanceHandlerFactory(component)
});
}
private void RegisterLoadedPlugins()
{
string configurationFilePath = runtimeSetup.ConfigurationFilePath;
if (configurationFilePath != null)
{
FileInfo configurationFile = new FileInfo(configurationFilePath);
if (configurationFile.Exists)
{
var document = new XmlDocument();
document.Load(configurationFilePath);
var gallioElement = document.SelectSingleNode("/configuration/gallio") as XmlElement;
if (gallioElement != null)
LoadConfigurationData(gallioElement, pluginLoader, configurationFile.Directory);
}
pluginLoader.AddPluginPath(configurationFilePath);
}
else
{
XmlNode sectionData = (XmlNode)ConfigurationManager.GetSection(GallioSectionHandler.SectionName);
if (sectionData != null)
{
var gallioElement = sectionData as XmlElement;
if (gallioElement != null)
LoadConfigurationData(gallioElement, pluginLoader, new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory));
}
}
foreach (string path in pluginDirectories)
pluginLoader.AddPluginPath(path);
var pluginCatalog = new PluginCatalog();
pluginLoader.PopulateCatalog(pluginCatalog, NullProgressMonitor.CreateInstance());
pluginCatalog.ApplyTo(registry);
}
private static void LoadConfigurationData(XmlElement gallioElement, IPluginLoader pluginLoader, DirectoryInfo baseDirectory)
{
foreach (XmlElement pluginElement in gallioElement.GetElementsByTagName("plugin", SchemaConstants.XmlNamespace))
pluginLoader.AddPluginXml(pluginElement.OuterXml, baseDirectory);
}
private void LogDisabledPlugins()
{
foreach (IPluginDescriptor plugin in registry.Plugins)
{
if (plugin.IsDisabled)
{
dispatchLogger.Log(LogSeverity.Debug, string.Format("Disabled plugin '{0}': {1}", plugin.PluginId, plugin.DisabledReason));
}
}
}
/// <inheritdoc />
public RuntimeSetup GetRuntimeSetup()
{
return runtimeSetup.Copy();
}
/// <inheritdoc />
public IList<AssemblyBinding> GetAllPluginAssemblyBindings()
{
ThrowIfDisposed();
var result = new List<AssemblyBinding>();
foreach (IPluginDescriptor plugin in registry.Plugins)
result.AddRange(plugin.AssemblyBindings);
return result;
}
/// <inheritdoc />
public bool VerifyInstallation()
{
ThrowIfDisposed();
dispatchLogger.Log(LogSeverity.Info, "Checking plugins.");
bool success = true;
if (! debugMode)
VerifyFiles(ref success);
VerifyPlugins(ref success);
VerifyServices(ref success);
VerifyComponents(ref success);
return success;
}
/// <inheritdoc />
public event EventHandler<LogEntrySubmittedEventArgs> LogMessage
{
add
{
ThrowIfDisposed();
dispatchLogger.LogMessage += value;
}
remove
{
ThrowIfDisposed();
dispatchLogger.LogMessage -= value;
}
}
/// <inheritdoc />
public void AddLogListener(ILogger logger)
{
ThrowIfDisposed();
dispatchLogger.AddLogListener(logger); // note: callee checks arguments
}
/// <inheritdoc />
public void RemoveLogListener(ILogger logger)
{
ThrowIfDisposed();
dispatchLogger.RemoveLogListener(logger); // note: callee checks arguments
}
private void VerifyFiles(ref bool success)
{
var filePaths = new Dictionary<string, IPluginDescriptor>(StringComparer.OrdinalIgnoreCase);
// Make a list of all files in the runtime path.
foreach (var pluginDirectory in pluginDirectories)
{
foreach (var filePath in Directory.GetFiles(pluginDirectory, "*.*", SearchOption.AllDirectories))
{
string fullFilePath = Path.GetFullPath(filePath);
if (!filePaths.ContainsKey(fullFilePath))
{
filePaths.Add(fullFilePath, null);
}
}
}
// Mark all files referenced by plugins. Make note of files that we did not find.
foreach (var plugin in registry.Plugins)
{
foreach (var relativeFilePath in plugin.FilePaths)
{
var absoluteFilePath = Path.Combine(plugin.BaseDirectory.FullName, relativeFilePath);
IPluginDescriptor otherPlugin;
if (filePaths.TryGetValue(absoluteFilePath, out otherPlugin))
{
if (otherPlugin != null)
{
dispatchLogger.Log(LogSeverity.Error, string.Format("Plugin '{0}' contains file '{1}' but it has also been claimed by plugin '{2}'. Every file should be owned by exactly one plugin.",
plugin.PluginId, relativeFilePath, otherPlugin.PluginId));
success = false;
}
else
{
filePaths[absoluteFilePath] = plugin;
}
}
else
{
dispatchLogger.Log(LogSeverity.Error, string.Format("Plugin '{0}' contains file '{1}' but it does not exist.",
plugin.PluginId, relativeFilePath));
success = false;
}
}
}
// Find any files that have not been claimed by any plugin.
foreach (var pair in filePaths)
{
if (pair.Value == null)
{
dispatchLogger.Log(LogSeverity.Info, string.Format("File '{0}' does not appear to be owned by any plugin.", pair.Key));
}
}
}
private void VerifyPlugins(ref bool success)
{
foreach (var plugin in registry.Plugins)
{
if (plugin.IsDisabled)
{
dispatchLogger.Log(LogSeverity.Warning, string.Format("Plugin '{0}' is disabled: {1}'",
plugin.PluginId, plugin.DisabledReason));
continue;
}
VerifyPluginAssemblyBindings(plugin, ref success);
VerifyPluginObject(plugin, ref success);
VerifyPluginTraits(plugin, ref success);
}
}
private void VerifyPluginAssemblyBindings(IPluginDescriptor plugin, ref bool success)
{
foreach (AssemblyBinding assemblyBinding in plugin.AssemblyBindings)
{
try
{
if (assemblyBinding.CodeBase != null && assemblyBinding.CodeBase.IsFile)
{
var assemblyName = AssemblyName.GetAssemblyName(assemblyBinding.CodeBase.LocalPath);
if (assemblyName.FullName != assemblyBinding.AssemblyName.FullName)
{
success = false;
dispatchLogger.Log(LogSeverity.Error, string.Format(
"Plugin '{0}' has an incorrect assembly binding. Accoding to the plugin metadata we expected assembly name '{1}' but it was actually '{2}' when loaded.",
plugin.PluginId, assemblyBinding.AssemblyName.FullName, assemblyName.FullName));
}
}
else if (assemblyBinding.CodeBase == null)
{
try
{
Assembly.Load(assemblyBinding.AssemblyName);
}
catch (FileNotFoundException)
{
success = false;
dispatchLogger.Log(LogSeverity.Error, string.Format(
"Plugin '{0}' expects assembly '{1}' to be installed in the GAC but it was not found.",
plugin.PluginId, assemblyBinding.AssemblyName.FullName));
}
}
}
catch (Exception ex)
{
success = false;
dispatchLogger.Log(LogSeverity.Error, string.Format("Plugin '{0}' has an assembly reference for that could not be loaded with code base '{1}'.",
plugin.PluginId, assemblyBinding.CodeBase), ex);
}
}
}
private void VerifyPluginObject(IPluginDescriptor plugin, ref bool success)
{
try
{
plugin.ResolvePlugin();
}
catch (Exception ex)
{
success = false;
dispatchLogger.Log(LogSeverity.Error, "Unresolvable plugin.", ex);
}
}
private void VerifyPluginTraits(IPluginDescriptor plugin, ref bool success)
{
try
{
plugin.ResolveTraits();
}
catch (Exception ex)
{
success = false;
dispatchLogger.Log(LogSeverity.Error, "Unresolvable plugin traits.", ex);
}
}
private void VerifyServices(ref bool success)
{
foreach (var service in registry.Services)
{
if (service.IsDisabled)
continue;
VerifyServiceType(service, ref success);
VerifyServiceTraitsType(service, ref success);
}
}
private void VerifyServiceType(IServiceDescriptor service, ref bool success)
{
try
{
service.ResolveServiceType();
}
catch (Exception ex)
{
success = false;
dispatchLogger.Log(LogSeverity.Error, "Unresolvable service type.", ex);
}
}
private void VerifyServiceTraitsType(IServiceDescriptor service, ref bool success)
{
try
{
service.ResolveTraitsType();
}
catch (Exception ex)
{
success = false;
dispatchLogger.Log(LogSeverity.Error, "Unresolvable service traits type.", ex);
}
}
private void VerifyComponents(ref bool success)
{
foreach (var component in registry.Components)
{
if (component.IsDisabled)
continue;
VerifyComponentObject(component, ref success);
VerifyComponentTraits(component, ref success);
}
}
private void VerifyComponentObject(IComponentDescriptor component, ref bool success)
{
try
{
component.ResolveComponent();
}
catch (Exception ex)
{
success = false;
dispatchLogger.Log(LogSeverity.Error, "Unresolvable component.", ex);
}
}
private void VerifyComponentTraits(IComponentDescriptor component, ref bool success)
{
try
{
component.ResolveTraits();
}
catch (Exception ex)
{
success = false;
dispatchLogger.Log(LogSeverity.Error, "Unresolvable component traits.", ex);
}
}
private void ThrowIfDisposed()
{
if (registry == null)
throw new ObjectDisposedException("The runtime has been disposed.");
}
private void AddPluginDirectory(string pluginDirectory)
{
if (!pluginDirectories.Contains(pluginDirectory))
pluginDirectories.Add(pluginDirectory);
}
private void SetRuntimePath()
{
if (runtimeSetup.RuntimePath == null)
{
Assembly entryAssembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
runtimeSetup.RuntimePath = Path.GetDirectoryName(AssemblyUtils.GetFriendlyAssemblyLocation(entryAssembly));
}
runtimeSetup.RuntimePath = Path.GetFullPath(runtimeSetup.RuntimePath);
}
private void SetInstallationConfiguration()
{
if (runtimeSetup.InstallationConfiguration == null)
runtimeSetup.InstallationConfiguration = InstallationConfiguration.LoadFromRegistry();
}
private void ConfigureDefaultPluginDirectories()
{
AddPluginDirectory(runtimeSetup.RuntimePath);
}
private void ConfigurePluginDirectoriesFromSetup()
{
foreach (string pluginDirectory in runtimeSetup.PluginDirectories)
AddPluginDirectory(pluginDirectory);
}
private void ConfigurePluginDirectoriesFromInstallationConfiguration()
{
if (runtimeSetup.InstallationConfiguration != null)
{
foreach (string pluginDirectory in runtimeSetup.InstallationConfiguration.AdditionalPluginDirectories)
AddPluginDirectory(pluginDirectory);
}
}
private void ConfigurePluginLoaderForInstallationId()
{
pluginLoader.InstallationId = runtimeSetup.InstallationConfiguration.InstallationId;
}
// Configure the runtime for debugging purposes within Visual Studio.
// This code makes assumptions about the layout of the projects on disk that
// help to make debugging work "magically". Unless a specific runtime
// path has been set, it is overridden with the location of the Gallio project
// "bin" folder and the root directory of the source tree is added
// the list of plugin directories to ensure that plugins can be resolved.
[Conditional("DEBUG")]
private void ConfigureForDebugging()
{
// Find the root "src" dir.
string initPath;
if (! string.IsNullOrEmpty(runtimeSetup.RuntimePath))
initPath = runtimeSetup.RuntimePath;
else if (! string.IsNullOrEmpty(runtimeSetup.ConfigurationFilePath))
initPath = runtimeSetup.ConfigurationFilePath;
else
initPath = AssemblyUtils.GetAssemblyLocalPath(Assembly.GetExecutingAssembly());
string srcDir = initPath;
while (srcDir != null && Path.GetFileName(srcDir) != @"src")
srcDir = Path.GetDirectoryName(srcDir);
if (srcDir == null)
return; // not found!
// Force the runtime path to be set to where the primary Gallio assemblies and Gallio.Host.exe
// are located.
runtimeSetup.RuntimePath = Path.Combine(srcDir, @"Gallio\Gallio\bin");
// Add the solution folder to the list of plugin directories so that we can resolve
// all plugins that have been compiled within the solution.
AddPluginDirectory(srcDir);
// Remember we are in debug mode.
debugMode = true;
}
}
}
| |
// 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.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// GalleryImageOperations operations.
/// </summary>
internal partial class GalleryImageOperations : IServiceOperations<DevTestLabsClient>, IGalleryImageOperations
{
/// <summary>
/// Initializes a new instance of the GalleryImageOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal GalleryImageOperations(DevTestLabsClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DevTestLabsClient
/// </summary>
public DevTestLabsClient Client { get; private set; }
/// <summary>
/// List gallery images in a given lab.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<GalleryImage>>> ListWithHttpMessagesAsync(string resourceGroupName, string labName, ODataQuery<GalleryImage> odataQuery = default(ODataQuery<GalleryImage>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (this.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("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/galleryimages").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (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<IPage<GalleryImage>>();
_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 = SafeJsonConvert.DeserializeObject<Page<GalleryImage>>(_responseContent, this.Client.DeserializationSettings);
}
catch (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>
/// List gallery images in a given lab.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<GalleryImage>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (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<IPage<GalleryImage>>();
_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 = SafeJsonConvert.DeserializeObject<Page<GalleryImage>>(_responseContent, this.Client.DeserializationSettings);
}
catch (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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
namespace System.Xml.Serialization
{
/// <include file='doc\XmlAnyElementAttributes.uex' path='docs/doc[@for="XmlAnyElementAttributes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlAnyElementAttributes : IList
{
private List<XmlAnyElementAttribute> _list = new List<XmlAnyElementAttribute>();
/// <include file='doc\XmlAnyElementAttributes.uex' path='docs/doc[@for="XmlAnyElementAttributes.this"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlAnyElementAttribute this[int index]
{
get { return _list[index]; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_list[index] = value;
}
}
/// <include file='doc\XmlAnyElementAttributes.uex' path='docs/doc[@for="XmlAnyElementAttributes.Add"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Add(XmlAnyElementAttribute value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
int index = _list.Count;
_list.Add(value);
return index;
}
/// <include file='doc\XmlAnyElementAttributes.uex' path='docs/doc[@for="XmlAnyElementAttributes.Insert"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Insert(int index, XmlAnyElementAttribute value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_list.Insert(index, value);
}
/// <include file='doc\XmlAnyElementAttributes.uex' path='docs/doc[@for="XmlAnyElementAttributes.IndexOf"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int IndexOf(XmlAnyElementAttribute value)
{
return _list.IndexOf(value);
}
/// <include file='doc\XmlAnyElementAttributes.uex' path='docs/doc[@for="XmlAnyElementAttributes.Contains"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool Contains(XmlAnyElementAttribute value)
{
return _list.Contains(value);
}
/// <include file='doc\XmlAnyElementAttributes.uex' path='docs/doc[@for="XmlAnyElementAttributes.Remove"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Remove(XmlAnyElementAttribute value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (!_list.Remove(value))
{
throw new ArgumentException(SR.Arg_RemoveArgNotFound);
}
}
/// <include file='doc\XmlAnyElementAttributes.uex' path='docs/doc[@for="XmlAnyElementAttributes.CopyTo"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void CopyTo(XmlAnyElementAttribute[] array, int index)
{
_list.CopyTo(array, index);
}
private IList List
{
get { return _list; }
}
public int Count
{
get
{
return _list == null ? 0 : _list.Count;
}
}
public void Clear()
{
_list.Clear();
}
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
bool IList.IsReadOnly
{
get { return List.IsReadOnly; }
}
bool IList.IsFixedSize
{
get { return List.IsFixedSize; }
}
bool ICollection.IsSynchronized
{
get { return List.IsSynchronized; }
}
Object ICollection.SyncRoot
{
get { return List.SyncRoot; }
}
void ICollection.CopyTo(Array array, int index)
{
List.CopyTo(array, index);
}
Object IList.this[int index]
{
get
{
return List[index];
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
List[index] = value;
}
}
bool IList.Contains(Object value)
{
return List.Contains(value);
}
int IList.Add(Object value)
{
if (value == null)
{
throw new ArgumentException(nameof(value));
}
return List.Add(value);
}
void IList.Remove(Object value)
{
if (value == null)
{
throw new ArgumentException(nameof(value));
}
var attribute = value as XmlAnyElementAttribute;
if (attribute == null)
{
throw new ArgumentException(SR.Arg_RemoveArgNotFound);
}
Remove(attribute);
}
int IList.IndexOf(Object value)
{
return List.IndexOf(value);
}
void IList.Insert(int index, Object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
List.Insert(index, value);
}
public IEnumerator GetEnumerator()
{
return List.GetEnumerator();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Entities.Icons;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Modules.UserDefinedTable.Components;
using DotNetNuke.Modules.UserDefinedTable.Controllers.Caches;
using DotNetNuke.Modules.UserDefinedTable.Interfaces;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.Utilities;
using DotNetNuke.UI.WebControls;
using Globals = DotNetNuke.Common.Globals;
namespace DotNetNuke.Modules.UserDefinedTable
{
public partial class EditForm : PortalModuleBase, IActionable, IFormEvents
{
EditControls _editControls;
int _userDefinedRowId;
CaptchaControl _ctlCaptcha;
bool _hasUpdatePermission;
bool _hasDeletePermission;
readonly IDictionary<Label,Control> _labelcontrols= new Dictionary<Label, Control>();
readonly IDictionary<PropertyLabelControl, Control> _propertylabelcontrols = new Dictionary<PropertyLabelControl, Control>();
UserDefinedTableController _udtController;
UserDefinedTableController UdtController
{
get { return _udtController ?? (_udtController = new UserDefinedTableController(ModuleContext)); }
}
DataSet _data;
DataSet Data
{
get
{
if (_data == null)
{
if (! int.TryParse(Request.QueryString[DataTableColumn.RowId], out _userDefinedRowId))
{
_userDefinedRowId = Convert.ToInt32(- 1);
}
_data = UdtController.GetRow(_userDefinedRowId);
}
return _data;
}
}
DataRow CurrentRow
{
get
{
if (Data.Tables[DataSetTableName.Data].Rows.Count == 0)
{
var r = Data.Tables[DataSetTableName.Data].NewRow();
r[DataTableColumn.RowId] = _userDefinedRowId;
Data.Tables[DataSetTableName.Data].Rows.Add(r);
}
return Data.Tables[DataSetTableName.Data].Rows[0];
}
}
Components.Settings _settings;
new Components.Settings Settings
{ get { return _settings ?? (_settings = new Components.Settings(ModuleContext.Settings)); } }
bool IsNewRow
{
get { return _userDefinedRowId == - 1; }
}
#region Private Methods
void BuildCssForm (IEnumerable<FormColumnInfo> editForm)
{
EditFormPlaceholder.Visible = true;
Control currentContainer = EditFormPlaceholder;
foreach (var currentField in editForm)
{
if (currentField.IsCollapsible)
{
EditFormPlaceholder.Controls.Add(GetSeparatorFormPattern(currentField.Title, true));
var fieldset = new HtmlGenericControl("fieldset");
currentContainer = fieldset;
fieldset.Visible = currentField.Visible;
EditFormPlaceholder.Controls.Add(currentContainer);
}
else if (currentField.IsSeparator && currentField.Visible)
{
EditFormPlaceholder.Controls.Add(GetSeparatorFormPattern(currentField.Title));
currentContainer = EditFormPlaceholder;
}
else
{
var divFormItem = new HtmlGenericControl("div");
divFormItem.Attributes.Add("class", string.Format("dnnFormItem"));
divFormItem.Controls.Add(GetLabel(currentField.Title, currentField.Help, currentField.EditControl));
if (currentField.EditControl != null)
{
divFormItem.Controls.Add(currentField.EditControl);
}
divFormItem.Visible = currentField.Visible;
if (!currentField.IsUserDefinedField) currentContainer = EditFormPlaceholder;
currentContainer.Controls.Add(divFormItem);
}
}
}
Control GetLabel(string title, string help, Control editcontrol)
{
if (help == string.Empty)
{
var l = new Label
{
Text = string.Format("<span>{0}</span>", title),
AssociatedControlID = editcontrol.ID
};
var d = new HtmlGenericControl("div");
d.Attributes.Add("class", "dnnFormLabelWithoutHelp");
d.Controls.Add(l);
_labelcontrols.Add(l, editcontrol);
return d;
}
var label = new PropertyLabelControl
{
ID = string.Format("{0}_label", XmlConvert.EncodeName(title)),
Caption = title,
HelpText = help,
EditControl = editcontrol,
};
_propertylabelcontrols.Add(label, editcontrol);
return label;
}
static Control GetSeparatorFormPattern(string title, bool expendable=false)
{
return title == string.Empty
? new LiteralControl("<h2 class=\"dnnFormSectionHead\"/>")
: (expendable
? new LiteralControl(string.Format("<h2 class=\"dnnFormSectionHead\"><a>{0}</a></h2>", title))
: new LiteralControl(string.Format("<h2 class=\"dnnFormSectionHead\">{0}</h2>", title)));
}
void CheckPermission(bool isUsersOwnItem = true)
{
var security = new ModuleSecurity(ModuleContext);
if (
!((! IsNewRow && security.IsAllowedToEditRow(isUsersOwnItem)) ||
(IsNewRow && security.IsAllowedToAddRow() && (security.IsAllowedToAdministrateModule() || HasAddPermissonByQuota() ))))
{
if (IsNested())
{
cmdUpdate.Enabled = false;
divForm.Visible = true;
}
else
{
Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true);
}
}
else
{
_hasUpdatePermission = true;
}
_hasDeletePermission = Convert.ToBoolean(security.IsAllowedToDeleteRow(isUsersOwnItem) && ! IsNewRow);
cmdDelete.Visible = _hasDeletePermission;
}
bool IsNested()
{
return (Parent.Parent ) is PortalModuleBase;
}
bool HasAddPermissonByQuota()
{
var userquota = Settings.UserRecordQuota ;
if (userquota > 0 && Request.IsAuthenticated )
{
var ds = UdtController.GetDataSet(false);
return ModuleSecurity.HasAddPermissonByQuota(ds.Tables[DataSetTableName.Fields],
ds.Tables[DataSetTableName.Data], userquota,
UserInfo.Username);
}
return true;
}
void CheckPermission(string createdBy)
{
CheckPermission(ModuleContext.PortalSettings.UserInfo.Username == createdBy &&
createdBy != Definition.NameOfAnonymousUser);
}
bool CaptchaNeeded()
{
return ModuleContext.PortalSettings.UserId == - 1 && Settings.ForceCaptchaForAnonymous ;
}
void ShowUponSubmit()
{
var message = new HtmlGenericControl("div")
{InnerHtml = Settings.SubmissionText };
message.Attributes["class"] = "dnnFormMessage dnnFormSuccess";
MessagePlaceholder. Controls.Add(message);
}
void BuildEditForm()
{
var fieldSettingsTable = FieldSettingsController.GetFieldSettingsTable(ModuleId);
var editForm = new List<FormColumnInfo>();
FormColumnInfo currentField;
var security = new ModuleSecurity(ModuleContext);
_editControls = new EditControls(ModuleContext);
foreach (DataRow dr in Data.Tables[DataSetTableName.Fields].Rows)
{
var fieldTitle = dr[FieldsTableColumn.Title].AsString();
var dataTypeName = dr[FieldsTableColumn.Type].AsString();
var dataType = DataType.ByName(dataTypeName);
var isColumnEditable =
Convert.ToBoolean((! dataType.SupportsHideOnEdit ||
Convert.ToBoolean(dr[FieldsTableColumn.ShowOnEdit])) &&
(! Convert.ToBoolean(dr[FieldsTableColumn.IsPrivate]) ||
security.IsAllowedToEditAllColumns()));
//If Column is hidden, the Fieldtype falls back to "String" as the related EditControl works perfect even if it is not visibile
//EditControls of other user defined datatypes may use core controls (e.g. UrlControl or RTE) which are not rock solid regarding viewstate.
if (! isColumnEditable && dataType.IsUserDefinedField)
{
dataTypeName = "String";
}
currentField = new FormColumnInfo {IsUserDefinedField = dataType.IsUserDefinedField};
if (dataType.IsSeparator)
{
var fieldId = (int)dr[FieldsTableColumn.Id];
currentField.IsCollapsible = Data.Tables[DataSetTableName.FieldSettings].GetFieldSetting("IsCollapsible", fieldId).AsBoolean();
currentField.IsSeparator = true;
if (dr[FieldsTableColumn.Visible].AsBoolean())
{
currentField.Title = fieldTitle;
}
currentField.Visible = isColumnEditable;
}
else
{
currentField.Help = dr[FieldsTableColumn.HelpText].AsString();
currentField.Title = dr[FieldsTableColumn.Title].AsString();
currentField.Required =
Convert.ToBoolean(dr[FieldsTableColumn.Required].AsBoolean() &&
dataType.IsUserDefinedField);
//advanced Settings: Dynamic control
currentField.EditControl = _editControls.Add(dr[FieldsTableColumn.Title].AsString(),
dataTypeName, Convert.ToInt32(dr[FieldsTableColumn.Id]),
dr[FieldsTableColumn.HelpText].AsString(),
dr[FieldsTableColumn.Default].AsString(),
dr[FieldsTableColumn.Required].AsBoolean(),
dr[FieldsTableColumn.ValidationRule].AsString(),
dr[FieldsTableColumn.ValidationMessage].AsString(),
dr[FieldsTableColumn.EditStyle].AsString(),
dr[FieldsTableColumn.InputSettings].AsString(),
dr[FieldsTableColumn.OutputSettings].AsString(),
dr[FieldsTableColumn.NormalizeFlag].AsBoolean(),
dr[FieldsTableColumn.MultipleValues].AsBoolean(),
fieldSettingsTable,
this );
currentField.Visible = isColumnEditable;
}
editForm.Add(currentField);
}
if (CaptchaNeeded())
{
_ctlCaptcha = new CaptchaControl
{
ID = "Captcha",
CaptchaWidth = Unit.Pixel(130),
CaptchaHeight = Unit.Pixel(40),
ToolTip = Localization.GetString("CaptchaToolTip", LocalResourceFile),
ErrorMessage = Localization.GetString("CaptchaError", LocalResourceFile)
};
currentField = new FormColumnInfo
{
Title = Localization.GetString("Captcha", LocalResourceFile),
EditControl = _ctlCaptcha,
Visible = true,
IsUserDefinedField = false
};
editForm.Add(currentField);
}
BuildCssForm(editForm);
//Change captions of buttons in Form mode
if (IsNewRow && Settings.ListOrForm.Contains("Form"))
{
cmdUpdate.Attributes["resourcekey"] = "cmdSend.Text";
}
}
#endregion
#region Event Handlers
protected override void OnInit(EventArgs e)
{
Page.RegisterRequiresViewStateEncryption();
BuildEditForm();
cmdCancel.Click += cmdCancel_Click;
cmdDelete.Click += cmdDelete_Click;
cmdUpdate.Click += cmdUpdate_Click;
Load += Page_Load;
PreRender += EditForm_PreRender;
}
void EditForm_PreRender(object sender, EventArgs e)
{
foreach (var labelcontrol in _labelcontrols)
{
var label = labelcontrol.Key;
var control = (EditControl) labelcontrol.Value;
if (control.ValueControl != null) label.AssociatedControlID = control.ValueControl.ID;
}
foreach(var labelcontrol in _propertylabelcontrols )
{
var label = labelcontrol.Key;
var control = labelcontrol.Value as EditControl ;
if (control!=null && control.ValueControl != null) label.EditControl = control.ValueControl;
}
}
void Page_Load(object sender, EventArgs e)
{
try
{
if (Page.IsPostBack == false)
{
EnsureActionButton();
ClientAPI.AddButtonConfirm(cmdDelete, Localization.GetString("DeleteItem", LocalResourceFile));
}
if (! IsNewRow)
{
if (! Page.IsPostBack)
{
//Clear all default values
foreach (var edit in _editControls.Values)
{
edit.Value = "";
}
}
foreach (DataRow field in Data.Tables[DataSetTableName.Fields].Rows)
{
var dataTypeName = field[FieldsTableColumn.Type].AsString();
var dataType = DataType.ByName(dataTypeName);
var value = CurrentRow[field[FieldsTableColumn.Title].ToString()].ToString();
if (! dataType.IsSeparator)
{
if (! Page.IsPostBack)
{
_editControls[field[FieldsTableColumn.Title].ToString()].Value = value;
}
if (field[FieldsTableColumn.Type].ToString() == "CreatedBy")
{
CheckPermission(value);
}
}
}
}
else //New Entry
{
//Default Values already have been set in BuildEditForms
cmdDelete.Visible = false;
CheckPermission();
if (! Page.IsPostBack && Request.QueryString["OnSubmit"].AsInt() == ModuleContext.ModuleId)
{
ShowUponSubmit();
}
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
CheckPermission(false);
}
}
void cmdCancel_Click(object sender, EventArgs e)
{
try
{
if (Settings.ListOrForm.Contains("Form") && IsNewRow )
{
Response.Redirect(Request.RawUrl);
}
else
{
Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true);
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
void cmdUpdate_Click(object sender, EventArgs e)
{
if (_hasUpdatePermission)
{
try
{
// clear cached html content
new CachedHtmlContentController().DeleteCachedHtmlContentsByModuleId(ModuleContext.ModuleId);
//warning message of validation has failed
var warningMessage = string.Empty;
warningMessage = _editControls.Values.Where(edit => ! edit.IsValid())
.Aggregate(warningMessage,
(current, edit) => current + string.Format(
"<li><b>{0}</b><br />{1}</li>",
edit.FieldTitle,
edit.ValidationMessage));
if (CaptchaNeeded() && ! _ctlCaptcha.IsValid)
{
warningMessage += string.Format("<li><b>{0}</b><br />{1}</li>",
Localization.GetString("Captcha.Text", LocalResourceFile),
Localization.GetString("CaptchaError.Text", LocalResourceFile));
}
if (warningMessage == string.Empty)
{
//'Save values for every field separately
foreach (var edit in _editControls.Values)
{
var value = edit.Value;
CurrentRow[edit.FieldTitle] = value;
}
UdtController.UpdateRow(Data);
RecordUpdated();
switch (Settings.ListOrForm)
{
case "List":
Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true);
break;
case "FormAndList":
case "ListAndForm":
var url = IsNewRow
? Request.RawUrl
: Globals.NavigateURL(ModuleContext.TabId);
Response.Redirect(url,
true);
break;
case "Form":
switch (Settings.UponSubmitAction )
{
case "Text":
divForm.Visible = false;
ShowUponSubmit();
break;
case "Form":
Response.Redirect(
Globals.NavigateURL(ModuleContext.TabId, "",
string.Format("OnSubmit={0}", ModuleId)), true);
break;
default:
var strRedirectUrl = Settings.UponSubmitRedirect ?? Globals.NavigateURL(ModuleContext.TabId);
Response.Redirect(Globals.LinkClick(strRedirectUrl, ModuleContext.TabId,
ModuleContext.ModuleId));
break;
}
break;
}
}
else
{
var moduleControl = (PortalModuleBase) (((Parent.Parent) is PortalModuleBase) ? Parent.Parent : this);
UI.Skins.Skin.AddModuleMessage(moduleControl, string.Format("<ul style=\"padding-left:1.6em;padding-bottom:0;\">{0}</ul>", warningMessage),
ModuleMessage.ModuleMessageType.RedError);
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
}
void cmdDelete_Click(object sender, EventArgs e)
{
if (_hasDeletePermission)
{
try
{
// clear cached html content
new CachedHtmlContentController().DeleteCachedHtmlContentsByModuleId(ModuleContext.ModuleId);
UdtController.DeleteRow(_userDefinedRowId);
RecordDeleted();
Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true);
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
}
#endregion
#region Optional Interfaces
public void EnsureActionButton()
{
var useButtons = Settings.UseButtonsInForm;
var sec = new ModuleSecurity(ModuleId, TabId, Settings );
if (sec.IsAllowedToViewList() && Settings.OnlyFormIsShown )
{
var url = Globals.NavigateURL(TabId, "", "show=records");
var title = Localization.GetString("List.Action", LocalResourceFile);
cmdShowRecords.NavigateUrl = url;
cmdShowRecords.Text = title;
cmdShowRecords.Visible = useButtons;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Add the "ManageUDT" link to the current action list.
/// </summary>
/// <returns>ModuleActionCollection</returns>
/// -----------------------------------------------------------------------------
public ModuleActionCollection ModuleActions
{
get
{
var useButtons = Settings.UseButtonsInForm;
var cmdName = useButtons ? "" : ModuleActionType.AddContent;
var actions = new ModuleActionCollection();
var sec = new ModuleSecurity(ModuleId, TabId,Settings );
if (sec.IsAllowedToViewList() && Settings.OnlyFormIsShown )
{
var url = Globals.NavigateURL(TabId, "", "show=records");
var title = Localization.GetString("List.Action", LocalResourceFile);
actions.Add(ModuleContext.GetNextActionID(),
title,cmdName,
"", Utilities.IconURL("View"), url, false, SecurityAccessLevel.View, true, false);
}
return actions;
}
}
public event Action RecordUpdated = delegate { };
public event Action RecordDeleted = delegate { };
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
function initializeConvexEditor()
{
echo(" % - Initializing Sketch Tool");
exec( "./convexEditor.cs" );
exec( "./convexEditorGui.gui" );
exec( "./convexEditorToolbar.ed.gui" );
exec( "./convexEditorGui.cs" );
ConvexEditorGui.setVisible( false );
ConvexEditorOptionsWindow.setVisible( false );
ConvexEditorTreeWindow.setVisible( false );
ConvexEditorToolbar.setVisible( false );
EditorGui.add( ConvexEditorGui );
EditorGui.add( ConvexEditorOptionsWindow );
EditorGui.add( ConvexEditorTreeWindow );
EditorGui.add( ConvexEditorToolbar );
new ScriptObject( ConvexEditorPlugin )
{
superClass = "EditorPlugin";
editorGui = ConvexEditorGui;
};
// Note that we use the WorldEditor's Toolbar.
%map = new ActionMap();
%map.bindCmd( keyboard, "1", "ConvexEditorNoneModeBtn.performClick();", "" ); // Select
%map.bindCmd( keyboard, "2", "ConvexEditorMoveModeBtn.performClick();", "" ); // Move
%map.bindCmd( keyboard, "3", "ConvexEditorRotateModeBtn.performClick();", "" );// Rotate
%map.bindCmd( keyboard, "4", "ConvexEditorScaleModeBtn.performClick();", "" ); // Scale
ConvexEditorPlugin.map = %map;
ConvexEditorPlugin.initSettings();
}
function ConvexEditorPlugin::onWorldEditorStartup( %this )
{
// Add ourselves to the window menu.
%accel = EditorGui.addToEditorsMenu( "Sketch Tool", "", ConvexEditorPlugin );
// Add ourselves to the ToolsToolbar
%tooltip = "Sketch Tool (" @ %accel @ ")";
EditorGui.addToToolsToolbar( "ConvexEditorPlugin", "ConvexEditorPalette", expandFilename("tools/convexEditor/images/convex-editor-btn"), %tooltip );
//connect editor windows
GuiWindowCtrl::attach( ConvexEditorOptionsWindow, ConvexEditorTreeWindow);
// Allocate our special menu.
// It will be added/removed when this editor is activated/deactivated.
if ( !isObject( ConvexActionsMenu ) )
{
singleton PopupMenu( ConvexActionsMenu )
{
superClass = "MenuBuilder";
barTitle = "Sketch";
Item[0] = "Hollow Selected Shape" TAB "" TAB "ConvexEditorGui.hollowSelection();";
item[1] = "Recenter Selected Shape" TAB "" TAB "ConvexEditorGui.recenterSelection();";
};
}
%this.popupMenu = ConvexActionsMenu;
exec( "./convexEditorSettingsTab.ed.gui" );
ESettingsWindow.addTabPage( EConvexEditorSettingsPage );
}
function ConvexEditorPlugin::onActivated( %this )
{
%this.readSettings();
EditorGui.bringToFront( ConvexEditorGui );
ConvexEditorGui.setVisible( true );
ConvexEditorToolbar.setVisible( true );
ConvexEditorGui.makeFirstResponder( true );
%this.map.push();
// Set the status bar here until all tool have been hooked up
EditorGuiStatusBar.setInfo( "Sketch Tool." );
EditorGuiStatusBar.setSelection( "" );
// Add our menu.
EditorGui.menuBar.insert( ConvexActionsMenu, EditorGui.menuBar.dynamicItemInsertPos );
// Sync the pallete button state with the gizmo mode.
%mode = GlobalGizmoProfile.mode;
switch$ (%mode)
{
case "None":
ConvexEditorNoneModeBtn.performClick();
case "Move":
ConvexEditorMoveModeBtn.performClick();
case "Rotate":
ConvexEditorRotateModeBtn.performClick();
case "Scale":
ConvexEditorScaleModeBtn.performClick();
}
Parent::onActivated( %this );
}
function ConvexEditorPlugin::onDeactivated( %this )
{
%this.writeSettings();
ConvexEditorGui.setVisible( false );
ConvexEditorOptionsWindow.setVisible( false );
ConvexEditorTreeWindow.setVisible( false );
ConvexEditorToolbar.setVisible( false );
%this.map.pop();
// Remove our menu.
EditorGui.menuBar.remove( ConvexActionsMenu );
Parent::onDeactivated( %this );
}
function ConvexEditorPlugin::onEditMenuSelect( %this, %editMenu )
{
%hasSelection = false;
if ( ConvexEditorGui.hasSelection() )
%hasSelection = true;
%editMenu.enableItem( 3, false ); // Cut
%editMenu.enableItem( 4, false ); // Copy
%editMenu.enableItem( 5, false ); // Paste
%editMenu.enableItem( 6, %hasSelection ); // Delete
%editMenu.enableItem( 8, %hasSelection ); // Deselect
}
function ConvexEditorPlugin::handleDelete( %this )
{
ConvexEditorGui.handleDelete();
}
function ConvexEditorPlugin::handleDeselect( %this )
{
ConvexEditorGui.handleDeselect();
}
function ConvexEditorPlugin::handleCut( %this )
{
//WorldEditorInspectorPlugin.handleCut();
}
function ConvexEditorPlugin::handleCopy( %this )
{
//WorldEditorInspectorPlugin.handleCopy();
}
function ConvexEditorPlugin::handlePaste( %this )
{
//WorldEditorInspectorPlugin.handlePaste();
}
function ConvexEditorPlugin::isDirty( %this )
{
return ConvexEditorGui.isDirty;
}
function ConvexEditorPlugin::onSaveMission( %this, %missionFile )
{
if( ConvexEditorGui.isDirty )
{
$MissionGroup.save( %missionFile );
ConvexEditorGui.isDirty = false;
}
}
//-----------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------
function ConvexEditorPlugin::initSettings( %this )
{
EditorSettings.beginGroup( "ConvexEditor", true );
EditorSettings.setDefaultValue( "MaterialName", "Grid512_OrangeLines_Mat" );
EditorSettings.endGroup();
}
function ConvexEditorPlugin::readSettings( %this )
{
EditorSettings.beginGroup( "ConvexEditor", true );
ConvexEditorGui.materialName = EditorSettings.value("MaterialName");
EditorSettings.endGroup();
}
function ConvexEditorPlugin::writeSettings( %this )
{
EditorSettings.beginGroup( "ConvexEditor", true );
EditorSettings.setValue( "MaterialName", ConvexEditorGui.materialName );
EditorSettings.endGroup();
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CSC.BuildService.Model.ProjectRunner;
using CSC.Common.Infrastructure.Serialization;
using CSC.Common.Infrastructure.Utilities;
using CSC.CSClassroom.Model.Projects;
using CSC.CSClassroom.Model.Users;
using CSC.CSClassroom.Service.Classrooms;
using CSC.CSClassroom.Service.Projects;
using CSC.CSClassroom.WebApp.Filters;
using CSC.CSClassroom.WebApp.Settings;
using CSC.CSClassroom.WebApp.ViewModels.Project;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace CSC.CSClassroom.WebApp.Controllers
{
/// <summary>
/// The project controller.
/// </summary>
[Route(ClassroomRoutePrefix)]
public class ProjectController : BaseClassroomController
{
/// <summary>
/// The section service.
/// </summary>
private ISectionService SectionService { get; }
/// <summary>
/// The classroom service.
/// </summary>
private IProjectService ProjectService { get; }
/// <summary>
/// The build service.
/// </summary>
private IBuildService BuildService { get; }
/// <summary>
/// The JSON serializer.
/// </summary>
private readonly IJsonSerializer _jsonSerializer;
/// <summary>
/// The domain name.
/// </summary>
private readonly WebAppHost _webAppHost;
/// <summary>
/// Constructor.
/// </summary>
public ProjectController(
BaseControllerArgs args,
IClassroomService classroomService,
ISectionService sectionService,
IProjectService projectService,
IBuildService buildService,
IJsonSerializer jsonSerializer,
WebAppHost webAppHost)
: base(args, classroomService)
{
SectionService = sectionService;
ProjectService = projectService;
BuildService = buildService;
_jsonSerializer = jsonSerializer;
_webAppHost = webAppHost;
}
/// <summary>
/// Shows all projects.
/// </summary>
[Route("ProjectsAdmin")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> Admin()
{
var projects = await ProjectService.GetProjectsAsync(ClassroomName);
return View(projects);
}
/// <summary>
/// Shows the status of all proejcts.
/// </summary>
[Route("Projects")]
[ClassroomAuthorization(ClassroomRole.General)]
public async Task<IActionResult> Index(int? userId)
{
if (userId == null)
{
userId = User.Id;
}
if (userId != User.Id && ClassroomRole < ClassroomRole.Admin)
{
return Forbid();
}
var projectStatusResults = await ProjectService.GetProjectStatusAsync
(
ClassroomName,
userId.Value
);
var viewModel = new ProjectStatusResultsViewModel
(
projectStatusResults,
TimeZoneProvider
);
return View(viewModel);
}
/// <summary>
/// Asks the user to select a project report to show.
/// </summary>
[ClassroomAuthorization(ClassroomRole.Admin)]
[Route("ProjectReport")]
public async Task<IActionResult> SectionReport(
string sectionName,
string projectName)
{
var projects = await ProjectService.GetProjectsAsync(ClassroomName);
ViewBag.SectionNames = new List<SelectListItem>
(
Classroom.Sections.OrderBy(s => s.Name).Select
(
section => new SelectListItem()
{
Text = section.DisplayName,
Value = section.Name,
Selected = (sectionName == section.Name)
}
)
);
ViewBag.ProjectNames = new List<SelectListItem>
(
projects.OrderBy(p => p.Name, new NaturalComparer()).Select
(
project => new SelectListItem()
{
Text = project.Name,
Value = project.Name,
Selected = (project.Name == projectName)
}
)
);
return View("SelectSectionReport");
}
/// <summary>
/// Returns a project report.
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
[Route("ProjectReport")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public IActionResult SectionReport(
SelectProjectReport selectProjectReport)
{
return RedirectToAction
(
"SectionBuildResults",
"Build",
new
{
projectName = selectProjectReport.ProjectName,
sectionName = selectProjectReport.SectionName
}
);
}
/// <summary>
/// Creates a new project.
/// </summary>
[Route("CreateProject")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public IActionResult Create()
{
return View("CreateEdit");
}
/// <summary>
/// Creates a new project.
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
[Route("CreateProject")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> Create(Project project)
{
if (ModelState.IsValid)
{
await ProjectService.CreateProjectAsync(ClassroomName, project);
return RedirectToAction("Admin");
}
else
{
return View("CreateEdit", project);
}
}
/// <summary>
/// Edits a project.
/// </summary>
[Route("Projects/{projectName}/Edit")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> Edit(string projectName)
{
if (projectName == null)
{
return NotFound();
}
var project = await ProjectService.GetProjectAsync(ClassroomName, projectName);
if (project == null)
{
return NotFound();
}
return View("CreateEdit", project);
}
/// <summary>
/// Edits a project.
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
[Route("Projects/{projectName}/Edit")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> Edit(string projectName, Project project)
{
if (ModelState.IsValid)
{
await ProjectService.UpdateProjectAsync(ClassroomName, project);
return RedirectToAction("Admin");
}
else
{
return View("CreateEdit", project);
}
}
/// <summary>
/// Deletes a project.
/// </summary>
[Route("Projects/{projectName}/Delete")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> Delete(string projectName)
{
if (projectName == null)
{
return NotFound();
}
var project = await ProjectService.GetProjectAsync(ClassroomName, projectName);
if (project == null)
{
return NotFound();
}
return View(project);
}
/// <summary>
/// Deletes a project.
/// </summary>
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Route("Projects/{projectName}/Delete")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> DeleteConfirmed(string projectName)
{
await ProjectService.DeleteProjectAsync(ClassroomName, projectName);
return RedirectToAction("Admin");
}
/// <summary>
/// Creates student repositories.
/// </summary>
[Route("Projects/{projectName}/CreateStudentRepositories")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> CreateStudentRepositories(string projectName)
{
var project = await ProjectService.GetProjectAsync(ClassroomName, projectName);
if (project == null)
{
return NotFound();
}
var fileList = await ProjectService.GetTemplateFileListAsync(ClassroomName, projectName);
return View
(
new CreateStudentReposViewModel(project, fileList)
);
}
/// <summary>
/// Creates student repositories.
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
[Route("Projects/{projectName}/CreateStudentRepositories")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> CreateStudentRepositories(
string projectName,
string sectionName,
bool overwrite)
{
var webhookUrl = GetWebhookUrl();
var results = await ProjectService.CreateStudentRepositoriesAsync
(
ClassroomName,
projectName,
sectionName,
webhookUrl,
overwrite
);
return View("CreateStudentRepositoryResults", results);
}
/// <summary>
/// Called when a commit is pushed to a GitHub repository
/// </summary>
[HttpPost]
[Route("Projects/OnRepositoryPush")]
[Authorization(RequiredAccess.Anonymous)]
public async Task<IActionResult> OnRepositoryPush()
{
string gitHubEventHeader = Request.Headers["X-GitHub-Event"];
if (gitHubEventHeader != "push" && gitHubEventHeader != "ping")
return BadRequest();
byte[] requestBody;
using (var contentStream = new MemoryStream())
{
await Request.Body.CopyToAsync(contentStream);
requestBody = contentStream.ToArray();
string signature = Request.Headers["X-Hub-Signature"];
if (!ProjectService.VerifyGitHubWebhookPayloadSigned(requestBody, signature))
return BadRequest();
}
if (gitHubEventHeader == "ping")
return NoContent();
await ProjectService.OnRepositoryPushAsync
(
ClassroomName,
Encoding.UTF8.GetString(requestBody),
Url.Action("OnBuildCompleted")
);
return NoContent();
}
/// <summary>
/// Called to check GitHub for any commits that did not trigger a
/// webhook notification, for a single student.
/// </summary>
[Route("Projects/{projectName}/CheckForCommits")]
[ClassroomAuthorization(ClassroomRole.General)]
public async Task<IActionResult> CheckForCommits(string projectName, int? userId)
{
if (userId == null)
{
userId = User.Id;
}
if (ClassroomRole < ClassroomRole.Admin && userId != User.Id)
{
return Forbid();
}
var project = await ProjectService.GetProjectAsync(ClassroomName, projectName);
if (project == null)
{
return NotFound();
}
return View(new CheckForCommitsViewModel(project, userId.Value));
}
/// <summary>
/// Called to check GitHub for any commits that did not trigger a
/// webhook notification, for a single student.
/// </summary>
[HttpPost]
[Route("Projects/{projectName}/CheckForCommits")]
[ClassroomAuthorization(ClassroomRole.General)]
public async Task<IActionResult> CheckForCommitsConfirmed(string projectName, int? userId)
{
if (userId == null)
{
userId = User.Id;
}
if (ClassroomRole < ClassroomRole.Admin && userId != User.Id)
{
return Forbid();
}
var result = await ProjectService.ProcessMissedCommitsForStudentAsync
(
ClassroomName,
projectName,
userId.Value,
Url.Action("OnBuildCompleted")
);
if (!result)
{
return NotFound();
}
return RedirectToAction
(
"LatestBuildResult",
"Build",
userId != User.Id ? new { userId } : null
);
}
/// <summary>
/// Called to check GitHub for any commits that did not trigger a
/// webhook notification.
/// </summary>
[Route("Projects/{projectName}/CheckForCommitsAllStudents")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> CheckForCommitsAllStudents(string projectName)
{
var project = await ProjectService.GetProjectAsync(ClassroomName, projectName);
if (project == null)
{
return NotFound();
}
return View(project);
}
/// <summary>
/// Called to check GitHub for any commits that did not trigger a
/// webhook notification.
/// </summary>
[HttpPost]
[Route("Projects/{projectName}/CheckForCommitsAllStudents")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> CheckForCommitsAllStudentsConfirmed(string projectName)
{
var result = await ProjectService.ProcessMissedCommitsForAllStudentsAsync
(
ClassroomName,
projectName,
Url.Action("OnBuildCompleted")
);
if (!result)
{
return NotFound();
}
return RedirectToAction("Admin");
}
/// <summary>
/// Called when a commit is pushed to a GitHub repository
/// </summary>
[HttpPost]
[Route("Projects/OnBuildCompleted")]
[Authorization(RequiredAccess.Anonymous)]
public async Task<IActionResult> OnBuildCompleted([FromBody] ProjectJobResult projectJobResult)
{
await BuildService.OnBuildCompletedAsync(projectJobResult);
return NoContent();
}
/// <summary>
/// Returns the webhook URL.
/// </summary>
private string GetWebhookUrl()
{
return $"{_webAppHost.HostName}{Url.Action("OnRepositoryPush")}";
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: uploads/uploads_service.proto
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace KillrVideo.Uploads {
/// <summary>
/// Service that handles processing/re-encoding of uploaded videos
/// </summary>
public static class UploadsService
{
static readonly string __ServiceName = "killrvideo.uploads.UploadsService";
static readonly Marshaller<global::KillrVideo.Uploads.GetUploadDestinationRequest> __Marshaller_GetUploadDestinationRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Uploads.GetUploadDestinationRequest.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.Uploads.GetUploadDestinationResponse> __Marshaller_GetUploadDestinationResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Uploads.GetUploadDestinationResponse.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.Uploads.MarkUploadCompleteRequest> __Marshaller_MarkUploadCompleteRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Uploads.MarkUploadCompleteRequest.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.Uploads.MarkUploadCompleteResponse> __Marshaller_MarkUploadCompleteResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Uploads.MarkUploadCompleteResponse.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.Uploads.GetStatusOfVideoRequest> __Marshaller_GetStatusOfVideoRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Uploads.GetStatusOfVideoRequest.Parser.ParseFrom);
static readonly Marshaller<global::KillrVideo.Uploads.GetStatusOfVideoResponse> __Marshaller_GetStatusOfVideoResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Uploads.GetStatusOfVideoResponse.Parser.ParseFrom);
static readonly Method<global::KillrVideo.Uploads.GetUploadDestinationRequest, global::KillrVideo.Uploads.GetUploadDestinationResponse> __Method_GetUploadDestination = new Method<global::KillrVideo.Uploads.GetUploadDestinationRequest, global::KillrVideo.Uploads.GetUploadDestinationResponse>(
MethodType.Unary,
__ServiceName,
"GetUploadDestination",
__Marshaller_GetUploadDestinationRequest,
__Marshaller_GetUploadDestinationResponse);
static readonly Method<global::KillrVideo.Uploads.MarkUploadCompleteRequest, global::KillrVideo.Uploads.MarkUploadCompleteResponse> __Method_MarkUploadComplete = new Method<global::KillrVideo.Uploads.MarkUploadCompleteRequest, global::KillrVideo.Uploads.MarkUploadCompleteResponse>(
MethodType.Unary,
__ServiceName,
"MarkUploadComplete",
__Marshaller_MarkUploadCompleteRequest,
__Marshaller_MarkUploadCompleteResponse);
static readonly Method<global::KillrVideo.Uploads.GetStatusOfVideoRequest, global::KillrVideo.Uploads.GetStatusOfVideoResponse> __Method_GetStatusOfVideo = new Method<global::KillrVideo.Uploads.GetStatusOfVideoRequest, global::KillrVideo.Uploads.GetStatusOfVideoResponse>(
MethodType.Unary,
__ServiceName,
"GetStatusOfVideo",
__Marshaller_GetStatusOfVideoRequest,
__Marshaller_GetStatusOfVideoResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::KillrVideo.Uploads.UploadsServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of UploadsService</summary>
public abstract class UploadsServiceBase
{
/// <summary>
/// Gets an upload destination for a user to upload a video
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::KillrVideo.Uploads.GetUploadDestinationResponse> GetUploadDestination(global::KillrVideo.Uploads.GetUploadDestinationRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Marks an upload as complete
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::KillrVideo.Uploads.MarkUploadCompleteResponse> MarkUploadComplete(global::KillrVideo.Uploads.MarkUploadCompleteRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Gets the status of an uploaded video
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::KillrVideo.Uploads.GetStatusOfVideoResponse> GetStatusOfVideo(global::KillrVideo.Uploads.GetStatusOfVideoRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for UploadsService</summary>
public class UploadsServiceClient : ClientBase<UploadsServiceClient>
{
/// <summary>Creates a new client for UploadsService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public UploadsServiceClient(Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for UploadsService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public UploadsServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected UploadsServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected UploadsServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Gets an upload destination for a user to upload a video
/// </summary>
public virtual global::KillrVideo.Uploads.GetUploadDestinationResponse GetUploadDestination(global::KillrVideo.Uploads.GetUploadDestinationRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetUploadDestination(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets an upload destination for a user to upload a video
/// </summary>
public virtual global::KillrVideo.Uploads.GetUploadDestinationResponse GetUploadDestination(global::KillrVideo.Uploads.GetUploadDestinationRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetUploadDestination, null, options, request);
}
/// <summary>
/// Gets an upload destination for a user to upload a video
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.Uploads.GetUploadDestinationResponse> GetUploadDestinationAsync(global::KillrVideo.Uploads.GetUploadDestinationRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetUploadDestinationAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets an upload destination for a user to upload a video
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.Uploads.GetUploadDestinationResponse> GetUploadDestinationAsync(global::KillrVideo.Uploads.GetUploadDestinationRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetUploadDestination, null, options, request);
}
/// <summary>
/// Marks an upload as complete
/// </summary>
public virtual global::KillrVideo.Uploads.MarkUploadCompleteResponse MarkUploadComplete(global::KillrVideo.Uploads.MarkUploadCompleteRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return MarkUploadComplete(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Marks an upload as complete
/// </summary>
public virtual global::KillrVideo.Uploads.MarkUploadCompleteResponse MarkUploadComplete(global::KillrVideo.Uploads.MarkUploadCompleteRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_MarkUploadComplete, null, options, request);
}
/// <summary>
/// Marks an upload as complete
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.Uploads.MarkUploadCompleteResponse> MarkUploadCompleteAsync(global::KillrVideo.Uploads.MarkUploadCompleteRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return MarkUploadCompleteAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Marks an upload as complete
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.Uploads.MarkUploadCompleteResponse> MarkUploadCompleteAsync(global::KillrVideo.Uploads.MarkUploadCompleteRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_MarkUploadComplete, null, options, request);
}
/// <summary>
/// Gets the status of an uploaded video
/// </summary>
public virtual global::KillrVideo.Uploads.GetStatusOfVideoResponse GetStatusOfVideo(global::KillrVideo.Uploads.GetStatusOfVideoRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetStatusOfVideo(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets the status of an uploaded video
/// </summary>
public virtual global::KillrVideo.Uploads.GetStatusOfVideoResponse GetStatusOfVideo(global::KillrVideo.Uploads.GetStatusOfVideoRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetStatusOfVideo, null, options, request);
}
/// <summary>
/// Gets the status of an uploaded video
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.Uploads.GetStatusOfVideoResponse> GetStatusOfVideoAsync(global::KillrVideo.Uploads.GetStatusOfVideoRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetStatusOfVideoAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets the status of an uploaded video
/// </summary>
public virtual AsyncUnaryCall<global::KillrVideo.Uploads.GetStatusOfVideoResponse> GetStatusOfVideoAsync(global::KillrVideo.Uploads.GetStatusOfVideoRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetStatusOfVideo, null, options, request);
}
protected override UploadsServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new UploadsServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(UploadsServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_GetUploadDestination, serviceImpl.GetUploadDestination)
.AddMethod(__Method_MarkUploadComplete, serviceImpl.MarkUploadComplete)
.AddMethod(__Method_GetStatusOfVideo, serviceImpl.GetStatusOfVideo).Build();
}
}
}
#endregion
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.Abstract;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using WebCache = System.Web.Caching.Cache;
using WebCacheDependency = System.Web.Caching.CacheDependency;
using WebCacheItemPriority = System.Web.Caching.CacheItemPriority;
using WebCacheItemRemovedCallback = System.Web.Caching.CacheItemRemovedCallback;
namespace Contoso.Abstract
{
/// <summary>
/// IWebServiceCache
/// </summary>
public interface IWebServiceCache : IServiceCache
{
/// <summary>
/// Gets the cache.
/// </summary>
WebCache Cache { get; }
}
/// <summary>
/// WebServiceCache
/// </summary>
public class WebServiceCache : IWebServiceCache, ServiceCacheManager.ISetupRegistration
{
static WebServiceCache() { ServiceCacheManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="WebServiceCache"/> class.
/// </summary>
public WebServiceCache()
{
Cache = (HttpRuntime.Cache ?? HostingEnvironment.Cache);
Settings = new ServiceCacheSettings(new DefaultFileTouchableCacheItem(this, new DefaultTouchableCacheItem(this, null)));
}
Action<IServiceLocator, string> ServiceCacheManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceCacheManager.RegisterInstance<IWebServiceCache>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.-or- null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { throw new NotImplementedException(); }
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified name.
/// </summary>
public object this[string name]
{
get { return Get(null, name); }
set { Set(null, name, CacheItemPolicy.Default, value, ServiceCacheByDispatcher.Empty); }
}
/// <summary>
/// Adds the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The item policy.</param>
/// <param name="value">The value.</param>
/// <param name="dispatch">The dispatch.</param>
/// <returns></returns>
public object Add(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
{
if (itemPolicy == null)
throw new ArgumentNullException("itemPolicy");
var updateCallback = itemPolicy.UpdateCallback;
if (updateCallback != null)
updateCallback(name, value);
// item priority
WebCacheItemPriority cacheItemPriority;
switch (itemPolicy.Priority)
{
case CacheItemPriority.AboveNormal: cacheItemPriority = WebCacheItemPriority.AboveNormal; break;
case CacheItemPriority.BelowNormal: cacheItemPriority = WebCacheItemPriority.BelowNormal; break;
case CacheItemPriority.High: cacheItemPriority = WebCacheItemPriority.High; break;
case CacheItemPriority.Low: cacheItemPriority = WebCacheItemPriority.Low; break;
case CacheItemPriority.Normal: cacheItemPriority = WebCacheItemPriority.Normal; break;
case CacheItemPriority.NotRemovable: cacheItemPriority = WebCacheItemPriority.NotRemovable; break;
default: cacheItemPriority = WebCacheItemPriority.Default; break;
}
//
var removedCallback = (itemPolicy.RemovedCallback == null ? null : new WebCacheItemRemovedCallback((n, v, c) => { itemPolicy.RemovedCallback(n, v); }));
value = Cache.Add(name, value, GetCacheDependency(tag, itemPolicy.Dependency, dispatch), itemPolicy.AbsoluteExpiration, itemPolicy.SlidingExpiration, cacheItemPriority, removedCallback);
var registration = dispatch.Registration;
if (registration != null && registration.UseHeaders)
{
var headerPolicy = new WebCacheDependency(null, new[] { name });
var header = dispatch.Header;
header.Item = name;
Cache.Add(name + "#", header, headerPolicy, itemPolicy.AbsoluteExpiration, itemPolicy.SlidingExpiration, cacheItemPriority, null);
}
return value;
}
/// <summary>
/// Gets the item from cache associated with the key provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <returns>
/// The cached item.
/// </returns>
public object Get(object tag, string name) { return Cache.Get(name); }
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="registration">The registration.</param>
/// <param name="header">The header.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException"></exception>
public object Get(object tag, string name, IServiceCacheRegistration registration, out CacheItemHeader header)
{
if (registration == null)
throw new ArgumentNullException("registration");
header = (registration.UseHeaders ? (CacheItemHeader)Cache.Get(name + "#") : null);
return Cache.Get(name);
}
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
/// <returns></returns>
public object Get(object tag, IEnumerable<string> names)
{
if (names == null)
throw new ArgumentNullException("names");
return names.Select(name => new { name, value = Cache.Get(name) }).ToDictionary(x => x.name, x => x.value);
}
/// <summary>
/// Gets the specified registration.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="registration">The registration.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException"></exception>
public IEnumerable<CacheItemHeader> Get(object tag, IServiceCacheRegistration registration)
{
if (registration == null)
throw new ArgumentNullException("registration");
var registrationName = registration.AbsoluteName + "#";
CacheItemHeader value;
var e = Cache.GetEnumerator();
while (e.MoveNext())
{
var key = (e.Key as string);
if (key == null || !key.EndsWith(registrationName) || (value = (e.Value as CacheItemHeader)) == null)
continue;
yield return value;
}
}
/// <summary>
/// Tries the get.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool TryGet(object tag, string name, out object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Adds an object into cache based on the parameters provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The itemPolicy object.</param>
/// <param name="value">The value to store in cache.</param>
/// <param name="dispatch">The dispatch.</param>
/// <returns></returns>
public object Set(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
{
if (itemPolicy == null)
throw new ArgumentNullException("itemPolicy");
var updateCallback = itemPolicy.UpdateCallback;
if (updateCallback != null)
updateCallback(name, value);
// item priority
WebCacheItemPriority cacheItemPriority;
switch (itemPolicy.Priority)
{
case CacheItemPriority.AboveNormal: cacheItemPriority = WebCacheItemPriority.AboveNormal; break;
case CacheItemPriority.BelowNormal: cacheItemPriority = WebCacheItemPriority.BelowNormal; break;
case CacheItemPriority.High: cacheItemPriority = WebCacheItemPriority.High; break;
case CacheItemPriority.Low: cacheItemPriority = WebCacheItemPriority.Low; break;
case CacheItemPriority.Normal: cacheItemPriority = WebCacheItemPriority.Normal; break;
case CacheItemPriority.NotRemovable: cacheItemPriority = WebCacheItemPriority.NotRemovable; break;
default: cacheItemPriority = WebCacheItemPriority.Default; break;
}
//
var removedCallback = (itemPolicy.RemovedCallback == null ? null : new WebCacheItemRemovedCallback((n, v, c) => { itemPolicy.RemovedCallback(n, v); }));
Cache.Insert(name, value, GetCacheDependency(tag, itemPolicy.Dependency, dispatch), itemPolicy.AbsoluteExpiration, itemPolicy.SlidingExpiration, cacheItemPriority, removedCallback);
var registration = dispatch.Registration;
if (registration != null && registration.UseHeaders)
{
var headerPolicy = new WebCacheDependency(null, new[] { name });
var header = dispatch.Header;
header.Item = name;
Cache.Insert(name + "#", header, headerPolicy, itemPolicy.AbsoluteExpiration, itemPolicy.SlidingExpiration, cacheItemPriority, null);
}
return value;
}
/// <summary>
/// Removes from cache the item associated with the key provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="registration">The registration.</param>
/// <returns>
/// The item removed from the Cache. If the value in the key parameter is not found, returns null.
/// </returns>
public object Remove(object tag, string name, IServiceCacheRegistration registration) { if (registration != null && registration.UseHeaders) Cache.Remove(name + "#"); return Cache.Remove(name); }
/// <summary>
/// Settings
/// </summary>
public ServiceCacheSettings Settings { get; private set; }
#region TouchableCacheItem
/// <summary>
/// DefaultTouchableCacheItem
/// </summary>
public class DefaultTouchableCacheItem : ITouchableCacheItem
{
private WebServiceCache _parent;
private ITouchableCacheItem _base;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultTouchableCacheItem"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="base">The @base.</param>
public DefaultTouchableCacheItem(WebServiceCache parent, ITouchableCacheItem @base) { _parent = parent; _base = @base; }
/// <summary>
/// Touches the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
public void Touch(object tag, string[] names)
{
if (names == null || names.Length == 0)
return;
var cache = _parent.Cache;
foreach (var name in names)
cache.Insert(name, string.Empty, null, ServiceCache.InfiniteAbsoluteExpiration, ServiceCache.NoSlidingExpiration, WebCacheItemPriority.Normal, null);
if (_base != null)
_base.Touch(tag, names);
}
/// <summary>
/// Makes the dependency.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
/// <returns></returns>
public object MakeDependency(object tag, string[] names)
{
if (names == null || names.Length == 0)
return null;
var cache = _parent.Cache;
// ensure
foreach (var name in names)
cache.Add(name, string.Empty, null, ServiceCache.InfiniteAbsoluteExpiration, ServiceCache.NoSlidingExpiration, WebCacheItemPriority.Normal, null);
return (_base == null ? new WebCacheDependency(null, names) : new WebCacheDependency(null, names, _base.MakeDependency(tag, names) as WebCacheDependency));
}
}
/// <summary>
/// DefaultFileTouchableCacheItem
/// </summary>
public class DefaultFileTouchableCacheItem : ServiceCache.FileTouchableCacheItemBase
{
/// <summary>
/// Initializes a new instance of the <see cref="DefaultFileTouchableCacheItem"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="base">The @base.</param>
public DefaultFileTouchableCacheItem(WebServiceCache parent, ITouchableCacheItem @base)
: base(parent, @base) { }
/// <summary>
/// Makes the dependency internal.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
/// <param name="baseDependency">The base dependency.</param>
/// <returns></returns>
protected override object MakeDependencyInternal(object tag, string[] names, object baseDependency) { return new WebCacheDependency(names.Select(x => GetFilePathForName(x)).ToArray(), null, (System.Web.Caching.CacheDependency)baseDependency); }
// var touchablesDependency = (touchables.Count > 0 ? (WebCacheDependency)touchable.MakeDependency(tag, touchables.ToArray())(this, tag) : null);
// return (touchablesDependency == null ? new WebCacheDependency(null, cacheKeys.ToArray()) : new WebCacheDependency(null, cacheKeys.ToArray(), touchablesDependency));
}
#endregion
#region Domain-specific
/// <summary>
/// Gets the cache.
/// </summary>
public WebCache Cache { get; private set; }
#endregion
private WebCacheDependency GetCacheDependency(object tag, CacheItemDependency dependency, ServiceCacheByDispatcher dispatch)
{
object value;
if (dependency == null || (value = dependency(this, dispatch.Registration, tag, dispatch.Values)) == null)
return null;
//
var names = (value as string[]);
var touchable = Settings.Touchable;
return ((touchable != null && names != null ? touchable.MakeDependency(tag, names) : value) as WebCacheDependency);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Threading;
using Orleans.AzureUtils;
using Orleans.Runtime.Configuration;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Orleans.Logging;
namespace Orleans.Runtime.Host
{
/// <summary>
/// Wrapper class for an Orleans silo running in the current host process.
/// </summary>
public class AzureSilo
{
/// <summary>
/// Amount of time to pause before retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 5 seconds.
/// </summary>
public TimeSpan StartupRetryPause { get; set; }
/// <summary>
/// Number of times to retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 120 times.
/// </summary>
public int MaxRetries { get; set; }
/// <summary>
/// The name of the configuration key value for locating the DataConnectionString setting from the Azure configuration for this role.
/// Defaults to <c>DataConnectionString</c>
/// </summary>
public string DataConnectionConfigurationSettingName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansSiloEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansSiloEndpoint</c>
/// </summary>
public string SiloEndpointConfigurationKeyName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansProxyEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansProxyEndpoint</c>
/// </summary>
public string ProxyEndpointConfigurationKeyName { get; set; }
private SiloHost host;
private OrleansSiloInstanceManager siloInstanceManager;
private SiloInstanceTableEntry myEntry;
private readonly ILogger logger;
private readonly IServiceRuntimeWrapper serviceRuntimeWrapper;
//TODO: hook this up with SiloBuilder when SiloBuilder supports create AzureSilo
private static ILoggerFactory DefaultLoggerFactory = CreateDefaultLoggerFactory("AzureSilo.log");
private readonly ILoggerFactory loggerFactory = DefaultLoggerFactory;
public AzureSilo()
:this(new ServiceRuntimeWrapper(DefaultLoggerFactory), DefaultLoggerFactory)
{
}
/// <summary>
/// Constructor
/// </summary>
public AzureSilo(ILoggerFactory loggerFactory)
: this(new ServiceRuntimeWrapper(loggerFactory), loggerFactory)
{
}
public static ILoggerFactory CreateDefaultLoggerFactory(string filePath)
{
var factory = new LoggerFactory();
factory.AddProvider(new FileLoggerProvider(filePath));
if (ConsoleText.IsConsoleAvailable)
factory.AddConsole();
return factory;
}
internal AzureSilo(IServiceRuntimeWrapper serviceRuntimeWrapper, ILoggerFactory loggerFactory)
{
this.serviceRuntimeWrapper = serviceRuntimeWrapper;
DataConnectionConfigurationSettingName = AzureConstants.DataConnectionConfigurationSettingName;
SiloEndpointConfigurationKeyName = AzureConstants.SiloEndpointConfigurationKeyName;
ProxyEndpointConfigurationKeyName = AzureConstants.ProxyEndpointConfigurationKeyName;
StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds
MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes
this.loggerFactory = loggerFactory;
logger = loggerFactory.CreateLogger<AzureSilo>();
}
/// <summary>
/// Async method to validate specific cluster configuration
/// </summary>
/// <param name="config"></param>
/// <returns>Task object of boolean type for this async method </returns>
public async Task<bool> ValidateConfiguration(ClusterConfiguration config)
{
if (config.Globals.LivenessType == GlobalConfiguration.LivenessProviderType.AzureTable)
{
string deploymentId = config.Globals.DeploymentId ?? serviceRuntimeWrapper.DeploymentId;
string connectionString = config.Globals.DataConnectionString ??
serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
try
{
var manager = siloInstanceManager ?? await OrleansSiloInstanceManager.GetManager(deploymentId, connectionString, loggerFactory);
var instances = await manager.DumpSiloInstanceTable();
logger.Debug(instances);
}
catch (Exception exc)
{
var error = String.Format("Connecting to the storage table has failed with {0}", LogFormatter.PrintException(exc));
Trace.TraceError(error);
logger.Error(ErrorCode.AzureTable_34, error, exc);
return false;
}
}
return true;
}
/// <summary>
/// Default cluster configuration
/// </summary>
/// <returns>Default ClusterConfiguration </returns>
public static ClusterConfiguration DefaultConfiguration()
{
return DefaultConfiguration(new ServiceRuntimeWrapper(DefaultLoggerFactory));
}
internal static ClusterConfiguration DefaultConfiguration(IServiceRuntimeWrapper serviceRuntimeWrapper)
{
var config = new ClusterConfiguration();
config.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.AzureTable;
config.Globals.DeploymentId = serviceRuntimeWrapper.DeploymentId;
try
{
config.Globals.DataConnectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(AzureConstants.DataConnectionConfigurationSettingName);
}
catch (Exception exc)
{
if (exc.GetType().Name.Contains("RoleEnvironmentException"))
{
config.Globals.DataConnectionString = null;
}
else
{
throw;
}
}
return config;
}
#region Azure RoleEntryPoint methods
/// <summary>
/// Initialize this Orleans silo for execution. Config data will be read from silo config file as normal
/// </summary>
/// <param name="deploymentId">Azure DeploymentId this silo is running under. If null, defaults to the value from the configuration.</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start(string deploymentId = null, string connectionString = null)
{
return Start(null, deploymentId, connectionString);
}
/// <summary>
/// Initialize this Orleans silo for execution
/// </summary>
/// <param name="config">Use the specified config data.</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start(ClusterConfiguration config, string connectionString = null)
{
if (config == null)
throw new ArgumentNullException(nameof(config));
return Start(config, null, connectionString);
}
/// <summary>
/// Initialize this Orleans silo for execution with the specified Azure deploymentId
/// </summary>
/// <param name="config">If null, Config data will be read from silo config file as normal, otherwise use the specified config data.</param>
/// <param name="deploymentId">Azure DeploymentId this silo is running under</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> if the silo startup was successful</returns>
internal bool Start(ClusterConfiguration config, string deploymentId, string connectionString)
{
if (config != null && deploymentId != null)
throw new ArgumentException("Cannot use config and deploymentId on the same time");
// Program ident
Trace.TraceInformation("Starting {0} v{1}", this.GetType().FullName, RuntimeVersion.Current);
// Read endpoint info for this instance from Azure config
string instanceName = serviceRuntimeWrapper.InstanceName;
// Configure this Orleans silo instance
if (config == null)
{
host = new SiloHost(instanceName);
host.LoadOrleansConfig(); // Load config from file + Initializes logger configurations
}
else
{
host = new SiloHost(instanceName, config); // Use supplied config data + Initializes logger configurations
}
IPEndPoint myEndpoint = serviceRuntimeWrapper.GetIPEndpoint(SiloEndpointConfigurationKeyName);
IPEndPoint proxyEndpoint = serviceRuntimeWrapper.GetIPEndpoint(ProxyEndpointConfigurationKeyName);
host.SetSiloType(Silo.SiloType.Secondary);
int generation = SiloAddress.AllocateNewGeneration();
// Bootstrap this Orleans silo instance
// If deploymentId was not direclty provided, take the value in the config. If it is not
// in the config too, just take the DeploymentId from Azure
if (deploymentId == null)
deploymentId = string.IsNullOrWhiteSpace(host.Config.Globals.DeploymentId)
? serviceRuntimeWrapper.DeploymentId
: host.Config.Globals.DeploymentId;
myEntry = new SiloInstanceTableEntry
{
DeploymentId = deploymentId,
Address = myEndpoint.Address.ToString(),
Port = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),
Generation = generation.ToString(CultureInfo.InvariantCulture),
HostName = host.Config.GetOrCreateNodeConfigurationForSilo(host.Name).DNSHostName,
ProxyPort = (proxyEndpoint != null ? proxyEndpoint.Port : 0).ToString(CultureInfo.InvariantCulture),
RoleName = serviceRuntimeWrapper.RoleName,
SiloName = instanceName,
UpdateZone = serviceRuntimeWrapper.UpdateDomain.ToString(CultureInfo.InvariantCulture),
FaultZone = serviceRuntimeWrapper.FaultDomain.ToString(CultureInfo.InvariantCulture),
StartTime = LogFormatter.PrintDate(DateTime.UtcNow),
PartitionKey = deploymentId,
RowKey = myEndpoint.Address + "-" + myEndpoint.Port + "-" + generation
};
if (connectionString == null)
connectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
try
{
siloInstanceManager = OrleansSiloInstanceManager.GetManager(
deploymentId, connectionString, this.loggerFactory).WithTimeout(AzureTableDefaultPolicies.TableCreationTimeout).Result;
}
catch (Exception exc)
{
var error = String.Format("Failed to create OrleansSiloInstanceManager. This means CreateTableIfNotExist for silo instance table has failed with {0}",
LogFormatter.PrintException(exc));
Trace.TraceError(error);
logger.Error(ErrorCode.AzureTable_34, error, exc);
throw new OrleansException(error, exc);
}
// Always use Azure table for membership when running silo in Azure
host.SetSiloLivenessType(GlobalConfiguration.LivenessProviderType.AzureTable);
if (host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.NotSpecified ||
host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain)
{
host.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
}
host.SetExpectedClusterSize(serviceRuntimeWrapper.RoleInstanceCount);
siloInstanceManager.RegisterSiloInstance(myEntry);
// Initialize this Orleans silo instance
host.SetDeploymentId(deploymentId, connectionString);
host.SetSiloEndpoint(myEndpoint, generation);
host.SetProxyEndpoint(proxyEndpoint);
host.InitializeOrleansSilo();
return StartSilo();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown.
/// </summary>
public void Run()
{
RunImpl();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
public void Run(CancellationToken cancellationToken)
{
RunImpl(cancellationToken);
}
/// <summary>
/// Stop this Orleans silo executing.
/// </summary>
public void Stop()
{
logger.Info(ErrorCode.Runtime_Error_100290, "Stopping {0}", this.GetType().FullName);
serviceRuntimeWrapper.UnsubscribeFromStoppingNotification(this, HandleAzureRoleStopping);
host.ShutdownOrleansSilo();
logger.Info(ErrorCode.Runtime_Error_100291, "Orleans silo '{0}' shutdown.", host.Name);
}
#endregion
private bool StartSilo()
{
logger.Info(ErrorCode.Runtime_Error_100292, "Starting Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
bool ok = host.StartOrleansSilo();
if (ok)
logger.Info(ErrorCode.Runtime_Error_100293, "Successfully started Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
else
logger.Error(ErrorCode.Runtime_Error_100285, string.Format("Failed to start Orleans silo '{0}' as a {1} node.", host.Name, host.Type));
return ok;
}
private void HandleAzureRoleStopping(object sender, object e)
{
// Try to perform gracefull shutdown of Silo when we detect Azure role instance is being stopped
logger.Info(ErrorCode.SiloStopping, "HandleAzureRoleStopping - starting to shutdown silo");
host.ShutdownOrleansSilo();
}
/// <summary>
/// Run method helper.
/// </summary>
/// <remarks>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </remarks>
/// <param name="cancellationToken">Optional cancellation token.</param>
private void RunImpl(CancellationToken? cancellationToken = null)
{
logger.Info(ErrorCode.Runtime_Error_100289, "OrleansAzureHost entry point called");
// Hook up to receive notification of Azure role stopping events
serviceRuntimeWrapper.SubscribeForStoppingNotification(this, HandleAzureRoleStopping);
if (host.IsStarted)
{
if (cancellationToken.HasValue)
host.WaitForOrleansSiloShutdown(cancellationToken.Value);
else
host.WaitForOrleansSiloShutdown();
}
else
throw new Exception("Silo failed to start correctly - aborting");
}
}
}
| |
/*
* 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.
*/
// This file was generated automatically by the Snowball to Java compiler
using System;
using Among = SF.Snowball.Among;
using SnowballProgram = SF.Snowball.SnowballProgram;
namespace SF.Snowball.Ext
{
#pragma warning disable 162
/// <summary> Generated class implementing code defined by a snowball script.</summary>
public class DutchStemmer : SnowballProgram
{
public DutchStemmer()
{
InitBlock();
}
private void InitBlock()
{
a_0 = new Among[]{new Among("", - 1, 6, "", this), new Among("\u00E1", 0, 1, "", this), new Among("\u00E4", 0, 1, "", this), new Among("\u00E9", 0, 2, "", this), new Among("\u00EB", 0, 2, "", this), new Among("\u00ED", 0, 3, "", this), new Among("\u00EF", 0, 3, "", this), new Among("\u00F3", 0, 4, "", this), new Among("\u00F6", 0, 4, "", this), new Among("\u00FA", 0, 5, "", this), new Among("\u00FC", 0, 5, "", this)};
a_1 = new Among[]{new Among("", - 1, 3, "", this), new Among("I", 0, 2, "", this), new Among("Y", 0, 1, "", this)};
a_2 = new Among[]{new Among("dd", - 1, - 1, "", this), new Among("kk", - 1, - 1, "", this), new Among("tt", - 1, - 1, "", this)};
a_3 = new Among[]{new Among("ene", - 1, 2, "", this), new Among("se", - 1, 3, "", this), new Among("en", - 1, 2, "", this), new Among("heden", 2, 1, "", this), new Among("s", - 1, 3, "", this)};
a_4 = new Among[]{new Among("end", - 1, 1, "", this), new Among("ig", - 1, 2, "", this), new Among("ing", - 1, 1, "", this), new Among("lijk", - 1, 3, "", this), new Among("baar", - 1, 4, "", this), new Among("bar", - 1, 5, "", this)};
a_5 = new Among[]{new Among("aa", - 1, - 1, "", this), new Among("ee", - 1, - 1, "", this), new Among("oo", - 1, - 1, "", this), new Among("uu", - 1, - 1, "", this)};
}
private Among[] a_0;
private Among[] a_1;
private Among[] a_2;
private Among[] a_3;
private Among[] a_4;
private Among[] a_5;
private static readonly char[] g_v = new char[]{(char) (17), (char) (65), (char) (16), (char) (1), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (128)};
private static readonly char[] g_v_I = new char[]{(char) (1), (char) (0), (char) (0), (char) (17), (char) (65), (char) (16), (char) (1), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (128)};
private static readonly char[] g_v_j = new char[]{(char) (17), (char) (67), (char) (16), (char) (1), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (0), (char) (128)};
private int I_p2;
private int I_p1;
private bool B_e_found;
protected internal virtual void copy_from(DutchStemmer other)
{
I_p2 = other.I_p2;
I_p1 = other.I_p1;
B_e_found = other.B_e_found;
base.copy_from(other);
}
private bool r_prelude()
{
int among_var;
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
int v_6;
// (, line 41
// test, line 42
v_1 = cursor;
// repeat, line 42
while (true)
{
v_2 = cursor;
do
{
// (, line 42
// [, line 43
bra = cursor;
// substring, line 43
among_var = find_among(a_0, 11);
if (among_var == 0)
{
goto lab1_brk;
}
// ], line 43
ket = cursor;
switch (among_var)
{
case 0:
goto lab1_brk;
case 1:
// (, line 45
// <-, line 45
slice_from("a");
break;
case 2:
// (, line 47
// <-, line 47
slice_from("e");
break;
case 3:
// (, line 49
// <-, line 49
slice_from("i");
break;
case 4:
// (, line 51
// <-, line 51
slice_from("o");
break;
case 5:
// (, line 53
// <-, line 53
slice_from("u");
break;
case 6:
// (, line 54
// next, line 54
if (cursor >= limit)
{
goto lab1_brk;
}
cursor++;
break;
}
goto replab0;
}
while (false);
lab1_brk: ;
cursor = v_2;
goto replab0_brk;
replab0: ;
}
replab0_brk: ;
cursor = v_1;
// try, line 57
v_3 = cursor;
do
{
// (, line 57
// [, line 57
bra = cursor;
// literal, line 57
if (!(eq_s(1, "y")))
{
cursor = v_3;
goto lab2_brk;
}
// ], line 57
ket = cursor;
// <-, line 57
slice_from("Y");
}
while (false);
lab2_brk: ;
// repeat, line 58
while (true)
{
v_4 = cursor;
do
{
// goto, line 58
while (true)
{
v_5 = cursor;
do
{
// (, line 58
if (!(in_grouping(g_v, 97, 232)))
{
goto lab6_brk;
}
// [, line 59
bra = cursor;
// or, line 59
do
{
v_6 = cursor;
do
{
// (, line 59
// literal, line 59
if (!(eq_s(1, "i")))
{
goto lab8_brk;
}
// ], line 59
ket = cursor;
if (!(in_grouping(g_v, 97, 232)))
{
goto lab8_brk;
}
// <-, line 59
slice_from("I");
goto lab7_brk;
}
while (false);
lab8_brk: ;
cursor = v_6;
// (, line 60
// literal, line 60
if (!(eq_s(1, "y")))
{
goto lab6_brk;
}
// ], line 60
ket = cursor;
// <-, line 60
slice_from("Y");
}
while (false);
lab7_brk: ;
cursor = v_5;
goto golab5_brk;
}
while (false);
lab6_brk: ;
cursor = v_5;
if (cursor >= limit)
{
goto lab4_brk;
}
cursor++;
}
golab5_brk: ;
goto replab3;
}
while (false);
lab4_brk: ;
cursor = v_4;
goto replab3_brk;
replab3: ;
}
replab3_brk: ;
return true;
}
private bool r_mark_regions()
{
// (, line 64
I_p1 = limit;
I_p2 = limit;
// gopast, line 69
while (true)
{
do
{
if (!(in_grouping(g_v, 97, 232)))
{
goto lab3_brk;
}
goto golab0_brk;
}
while (false);
lab3_brk: ;
if (cursor >= limit)
{
return false;
}
cursor++;
}
golab0_brk: ;
// gopast, line 69
while (true)
{
do
{
if (!(out_grouping(g_v, 97, 232)))
{
goto lab3_brk;
}
goto golab2_brk;
}
while (false);
lab3_brk: ;
if (cursor >= limit)
{
return false;
}
cursor++;
}
golab2_brk: ;
// setmark p1, line 69
I_p1 = cursor;
// try, line 70
do
{
// (, line 70
if (!(I_p1 < 3))
{
goto lab5_brk;
}
I_p1 = 3;
}
while (false);
lab5_brk: ;
// gopast, line 71
while (true)
{
do
{
if (!(in_grouping(g_v, 97, 232)))
{
goto lab9_brk;
}
goto golab6_brk;
}
while (false);
lab9_brk: ;
if (cursor >= limit)
{
return false;
}
cursor++;
}
golab6_brk: ;
// gopast, line 71
while (true)
{
do
{
if (!(out_grouping(g_v, 97, 232)))
{
goto lab9_brk;
}
goto golab7_brk;
}
while (false);
lab9_brk: ;
if (cursor >= limit)
{
return false;
}
cursor++;
}
golab7_brk: ;
// setmark p2, line 71
I_p2 = cursor;
return true;
}
private bool r_postlude()
{
int among_var;
int v_1;
// repeat, line 75
while (true)
{
v_1 = cursor;
do
{
// (, line 75
// [, line 77
bra = cursor;
// substring, line 77
among_var = find_among(a_1, 3);
if (among_var == 0)
{
goto lab5_brk;
}
// ], line 77
ket = cursor;
switch (among_var)
{
case 0:
goto lab5_brk;
case 1:
// (, line 78
// <-, line 78
slice_from("y");
break;
case 2:
// (, line 79
// <-, line 79
slice_from("i");
break;
case 3:
// (, line 80
// next, line 80
if (cursor >= limit)
{
goto lab5_brk;
}
cursor++;
break;
}
goto replab1;
}
while (false);
lab5_brk: ;
cursor = v_1;
goto replab1_brk;
replab1: ;
}
replab1_brk: ;
return true;
}
private bool r_R1()
{
if (!(I_p1 <= cursor))
{
return false;
}
return true;
}
private bool r_R2()
{
if (!(I_p2 <= cursor))
{
return false;
}
return true;
}
private bool r_undouble()
{
int v_1;
// (, line 90
// test, line 91
v_1 = limit - cursor;
// among, line 91
if (find_among_b(a_2, 3) == 0)
{
return false;
}
cursor = limit - v_1;
// [, line 91
ket = cursor;
// next, line 91
if (cursor <= limit_backward)
{
return false;
}
cursor--;
// ], line 91
bra = cursor;
// delete, line 91
slice_del();
return true;
}
private bool r_e_ending()
{
int v_1;
// (, line 94
// unset e_found, line 95
B_e_found = false;
// [, line 96
ket = cursor;
// literal, line 96
if (!(eq_s_b(1, "e")))
{
return false;
}
// ], line 96
bra = cursor;
// call R1, line 96
if (!r_R1())
{
return false;
}
// test, line 96
v_1 = limit - cursor;
if (!(out_grouping_b(g_v, 97, 232)))
{
return false;
}
cursor = limit - v_1;
// delete, line 96
slice_del();
// set e_found, line 97
B_e_found = true;
// call undouble, line 98
if (!r_undouble())
{
return false;
}
return true;
}
private bool r_en_ending()
{
int v_1;
int v_2;
// (, line 101
// call R1, line 102
if (!r_R1())
{
return false;
}
// and, line 102
v_1 = limit - cursor;
if (!(out_grouping_b(g_v, 97, 232)))
{
return false;
}
cursor = limit - v_1;
// not, line 102
{
v_2 = limit - cursor;
do
{
// literal, line 102
if (!(eq_s_b(3, "gem")))
{
goto lab0_brk;
}
return false;
}
while (false);
lab0_brk: ;
cursor = limit - v_2;
}
// delete, line 102
slice_del();
// call undouble, line 103
if (!r_undouble())
{
return false;
}
return true;
}
private bool r_standard_suffix()
{
int among_var;
int v_1;
int v_2;
int v_3;
int v_4;
int v_5;
int v_6;
int v_7;
int v_8;
int v_9;
int v_10;
// (, line 106
// do, line 107
v_1 = limit - cursor;
do
{
// (, line 107
// [, line 108
ket = cursor;
// substring, line 108
among_var = find_among_b(a_3, 5);
if (among_var == 0)
{
goto lab0_brk;
}
// ], line 108
bra = cursor;
switch (among_var)
{
case 0:
goto lab0_brk;
case 1:
// (, line 110
// call R1, line 110
if (!r_R1())
{
goto lab0_brk;
}
// <-, line 110
slice_from("heid");
break;
case 2:
// (, line 113
// call en_ending, line 113
if (!r_en_ending())
{
goto lab0_brk;
}
break;
case 3:
// (, line 116
// call R1, line 116
if (!r_R1())
{
goto lab0_brk;
}
if (!(out_grouping_b(g_v_j, 97, 232)))
{
goto lab0_brk;
}
// delete, line 116
slice_del();
break;
}
}
while (false);
lab0_brk: ;
cursor = limit - v_1;
// do, line 120
v_2 = limit - cursor;
do
{
// call e_ending, line 120
if (!r_e_ending())
{
goto lab1_brk;
}
}
while (false);
lab1_brk: ;
cursor = limit - v_2;
// do, line 122
v_3 = limit - cursor;
do
{
// (, line 122
// [, line 122
ket = cursor;
// literal, line 122
if (!(eq_s_b(4, "heid")))
{
goto lab2_brk;
}
// ], line 122
bra = cursor;
// call R2, line 122
if (!r_R2())
{
goto lab2_brk;
}
// not, line 122
{
v_4 = limit - cursor;
do
{
// literal, line 122
if (!(eq_s_b(1, "c")))
{
goto lab3_brk;
}
goto lab2_brk;
}
while (false);
lab3_brk: ;
cursor = limit - v_4;
}
// delete, line 122
slice_del();
// [, line 123
ket = cursor;
// literal, line 123
if (!(eq_s_b(2, "en")))
{
goto lab2_brk;
}
// ], line 123
bra = cursor;
// call en_ending, line 123
if (!r_en_ending())
{
goto lab2_brk;
}
}
while (false);
lab2_brk: ;
cursor = limit - v_3;
// do, line 126
v_5 = limit - cursor;
do
{
// (, line 126
// [, line 127
ket = cursor;
// substring, line 127
among_var = find_among_b(a_4, 6);
if (among_var == 0)
{
goto lab4_brk;
}
// ], line 127
bra = cursor;
switch (among_var)
{
case 0:
goto lab4_brk;
case 1:
// (, line 129
// call R2, line 129
if (!r_R2())
{
goto lab4_brk;
}
// delete, line 129
slice_del();
// or, line 130
do
{
v_6 = limit - cursor;
do
{
// (, line 130
// [, line 130
ket = cursor;
// literal, line 130
if (!(eq_s_b(2, "ig")))
{
goto lab6_brk;
}
// ], line 130
bra = cursor;
// call R2, line 130
if (!r_R2())
{
goto lab6_brk;
}
// not, line 130
{
v_7 = limit - cursor;
do
{
// literal, line 130
if (!(eq_s_b(1, "e")))
{
goto lab7_brk;
}
goto lab6_brk;
}
while (false);
lab7_brk: ;
cursor = limit - v_7;
}
// delete, line 130
slice_del();
goto lab5_brk;
}
while (false);
lab6_brk: ;
cursor = limit - v_6;
// call undouble, line 130
if (!r_undouble())
{
goto lab4_brk;
}
}
while (false);
lab5_brk: ;
break;
case 2:
// (, line 133
// call R2, line 133
if (!r_R2())
{
goto lab4_brk;
}
// not, line 133
{
v_8 = limit - cursor;
do
{
// literal, line 133
if (!(eq_s_b(1, "e")))
{
goto lab8_brk;
}
goto lab4_brk;
}
while (false);
lab8_brk: ;
cursor = limit - v_8;
}
// delete, line 133
slice_del();
break;
case 3:
// (, line 136
// call R2, line 136
if (!r_R2())
{
goto lab4_brk;
}
// delete, line 136
slice_del();
// call e_ending, line 136
if (!r_e_ending())
{
goto lab4_brk;
}
break;
case 4:
// (, line 139
// call R2, line 139
if (!r_R2())
{
goto lab4_brk;
}
// delete, line 139
slice_del();
break;
case 5:
// (, line 142
// call R2, line 142
if (!r_R2())
{
goto lab4_brk;
}
// Boolean test e_found, line 142
if (!(B_e_found))
{
goto lab4_brk;
}
// delete, line 142
slice_del();
break;
}
}
while (false);
lab4_brk: ;
cursor = limit - v_5;
// do, line 146
v_9 = limit - cursor;
do
{
// (, line 146
if (!(out_grouping_b(g_v_I, 73, 232)))
{
goto lab9_brk;
}
// test, line 148
v_10 = limit - cursor;
// (, line 148
// among, line 149
if (find_among_b(a_5, 4) == 0)
{
goto lab9_brk;
}
if (!(out_grouping_b(g_v, 97, 232)))
{
goto lab9_brk;
}
cursor = limit - v_10;
// [, line 152
ket = cursor;
// next, line 152
if (cursor <= limit_backward)
{
goto lab9_brk;
}
cursor--;
// ], line 152
bra = cursor;
// delete, line 152
slice_del();
}
while (false);
lab9_brk: ;
cursor = limit - v_9;
return true;
}
public override bool Stem()
{
int v_1;
int v_2;
int v_3;
int v_4;
// (, line 157
// do, line 159
v_1 = cursor;
do
{
// call prelude, line 159
if (!r_prelude())
{
goto lab0_brk;
}
}
while (false);
lab0_brk: ;
cursor = v_1;
// do, line 160
v_2 = cursor;
do
{
// call mark_regions, line 160
if (!r_mark_regions())
{
goto lab1_brk;
}
}
while (false);
lab1_brk: ;
cursor = v_2;
// backwards, line 161
limit_backward = cursor; cursor = limit;
// do, line 162
v_3 = limit - cursor;
do
{
// call standard_suffix, line 162
if (!r_standard_suffix())
{
goto lab2_brk;
}
}
while (false);
lab2_brk: ;
cursor = limit - v_3;
cursor = limit_backward; // do, line 163
v_4 = cursor;
do
{
// call postlude, line 163
if (!r_postlude())
{
goto lab3_brk;
}
}
while (false);
lab3_brk: ;
cursor = v_4;
return true;
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.ComponentModel;
namespace ATABBI.TexE.Customization
{
internal class InertButton : Button
{
private enum RepeatClickStatus
{
Disabled,
Started,
Repeating,
Stopped
}
private class RepeatClickEventArgs : EventArgs
{
private static RepeatClickEventArgs _empty;
static RepeatClickEventArgs()
{
_empty = new RepeatClickEventArgs();
}
public new static RepeatClickEventArgs Empty
{
get { return _empty; }
}
}
private IContainer components = new Container();
private int m_borderWidth = 1;
private bool m_mouseOver = false;
private bool m_mouseCapture = false;
private bool m_isPopup = false;
private Image m_imageEnabled = null;
private Image m_imageDisabled = null;
private int m_imageIndexEnabled = -1;
private int m_imageIndexDisabled = -1;
private bool m_monochrom = true;
private ToolTip m_toolTip = null;
private string m_toolTipText = "";
private Color m_borderColor = Color.Empty;
public InertButton()
{
InternalConstruct(null, null);
}
public InertButton(Image imageEnabled)
{
InternalConstruct(imageEnabled, null);
}
public InertButton(Image imageEnabled, Image imageDisabled)
{
InternalConstruct(imageEnabled, imageDisabled);
}
private void InternalConstruct(Image imageEnabled, Image imageDisabled)
{
// Remember parameters
ImageEnabled = imageEnabled;
ImageDisabled = imageDisabled;
// Prevent drawing flicker by blitting from memory in WM_PAINT
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
// Prevent base class from trying to generate double click events and
// so testing clicks against the double click time and rectangle. Getting
// rid of this allows the user to press then release button very quickly.
//SetStyle(ControlStyles.StandardDoubleClick, false);
// Should not be allowed to select this control
SetStyle(ControlStyles.Selectable, false);
m_timer = new Timer();
m_timer.Enabled = false;
m_timer.Tick += new EventHandler(Timer_Tick);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
public Color BorderColor
{
get { return m_borderColor; }
set
{
if (m_borderColor != value)
{
m_borderColor = value;
Invalidate();
}
}
}
private bool ShouldSerializeBorderColor()
{
return (m_borderColor != Color.Empty);
}
public int BorderWidth
{
get { return m_borderWidth; }
set
{
if (value < 1)
value = 1;
if (m_borderWidth != value)
{
m_borderWidth = value;
Invalidate();
}
}
}
public Image ImageEnabled
{
get
{
if (m_imageEnabled != null)
return m_imageEnabled;
try
{
if (ImageList == null || ImageIndexEnabled == -1)
return null;
else
return ImageList.Images[m_imageIndexEnabled];
}
catch
{
return null;
}
}
set
{
if (m_imageEnabled != value)
{
m_imageEnabled = value;
Invalidate();
}
}
}
private bool ShouldSerializeImageEnabled()
{
return (m_imageEnabled != null);
}
public Image ImageDisabled
{
get
{
if (m_imageDisabled != null)
return m_imageDisabled;
try
{
if (ImageList == null || ImageIndexDisabled == -1)
return null;
else
return ImageList.Images[m_imageIndexDisabled];
}
catch
{
return null;
}
}
set
{
if (m_imageDisabled != value)
{
m_imageDisabled = value;
Invalidate();
}
}
}
public int ImageIndexEnabled
{
get { return m_imageIndexEnabled; }
set
{
if (m_imageIndexEnabled != value)
{
m_imageIndexEnabled = value;
Invalidate();
}
}
}
public int ImageIndexDisabled
{
get { return m_imageIndexDisabled; }
set
{
if (m_imageIndexDisabled != value)
{
m_imageIndexDisabled = value;
Invalidate();
}
}
}
public bool IsPopup
{
get { return m_isPopup; }
set
{
if (m_isPopup != value)
{
m_isPopup = value;
Invalidate();
}
}
}
public bool Monochrome
{
get { return m_monochrom; }
set
{
if (value != m_monochrom)
{
m_monochrom = value;
Invalidate();
}
}
}
public bool RepeatClick
{
get { return (ClickStatus != RepeatClickStatus.Disabled); }
set { ClickStatus = RepeatClickStatus.Stopped; }
}
private RepeatClickStatus m_clickStatus = RepeatClickStatus.Disabled;
private RepeatClickStatus ClickStatus
{
get { return m_clickStatus; }
set
{
if (m_clickStatus == value)
return;
m_clickStatus = value;
if (ClickStatus == RepeatClickStatus.Started)
{
Timer.Interval = RepeatClickDelay;
Timer.Enabled = true;
}
else if (ClickStatus == RepeatClickStatus.Repeating)
Timer.Interval = RepeatClickInterval;
else
Timer.Enabled = false;
}
}
private int m_repeatClickDelay = 500;
public int RepeatClickDelay
{
get { return m_repeatClickDelay; }
set { m_repeatClickDelay = value; }
}
private int m_repeatClickInterval = 100;
public int RepeatClickInterval
{
get { return m_repeatClickInterval; }
set { m_repeatClickInterval = value; }
}
private Timer m_timer;
private Timer Timer
{
get { return m_timer; }
}
public string ToolTipText
{
get { return m_toolTipText; }
set
{
if (m_toolTipText != value)
{
if (m_toolTip == null)
m_toolTip = new ToolTip(this.components);
m_toolTipText = value;
m_toolTip.SetToolTip(this, value);
}
}
}
private void Timer_Tick(object sender, EventArgs e)
{
if (m_mouseCapture && m_mouseOver)
OnClick(RepeatClickEventArgs.Empty);
if (ClickStatus == RepeatClickStatus.Started)
ClickStatus = RepeatClickStatus.Repeating;
}
/// <exclude/>
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button != MouseButtons.Left)
return;
if (m_mouseCapture == false || m_mouseOver == false)
{
m_mouseCapture = true;
m_mouseOver = true;
//Redraw to show button state
Invalidate();
}
if (RepeatClick)
{
OnClick(RepeatClickEventArgs.Empty);
ClickStatus = RepeatClickStatus.Started;
}
}
/// <exclude/>
protected override void OnClick(EventArgs e)
{
if (RepeatClick && !(e is RepeatClickEventArgs))
return;
base.OnClick (e);
}
/// <exclude/>
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button != MouseButtons.Left)
return;
if (m_mouseOver == true || m_mouseCapture == true)
{
m_mouseOver = false;
m_mouseCapture = false;
// Redraw to show button state
Invalidate();
}
if (RepeatClick)
ClickStatus = RepeatClickStatus.Stopped;
}
/// <exclude/>
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
// Is mouse point inside our client rectangle
bool over = this.ClientRectangle.Contains(new Point(e.X, e.Y));
// If entering the button area or leaving the button area...
if (over != m_mouseOver)
{
// Update state
m_mouseOver = over;
// Redraw to show button state
Invalidate();
}
}
/// <exclude/>
protected override void OnMouseEnter(EventArgs e)
{
// Update state to reflect mouse over the button area
if (!m_mouseOver)
{
m_mouseOver = true;
// Redraw to show button state
Invalidate();
}
base.OnMouseEnter(e);
}
/// <exclude/>
protected override void OnMouseLeave(EventArgs e)
{
// Update state to reflect mouse not over the button area
if (m_mouseOver)
{
m_mouseOver = false;
// Redraw to show button state
Invalidate();
}
base.OnMouseLeave(e);
}
/// <exclude/>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawBackground(e.Graphics);
DrawImage(e.Graphics);
DrawText(e.Graphics);
DrawBorder(e.Graphics);
}
private void DrawBackground(Graphics g)
{
using (SolidBrush brush = new SolidBrush(BackColor))
{
g.FillRectangle(brush, ClientRectangle);
}
}
private void DrawImage(Graphics g)
{
Image image = this.Enabled ? ImageEnabled : ((ImageDisabled != null) ? ImageDisabled : ImageEnabled);
ImageAttributes imageAttr = null;
if (null == image)
return;
if (m_monochrom)
{
imageAttr = new ImageAttributes();
// transform the monochrom image
// white -> BackColor
// black -> ForeColor
ColorMap[] colorMap = new ColorMap[2];
colorMap[0] = new ColorMap();
colorMap[0].OldColor = Color.White;
colorMap[0].NewColor = this.BackColor;
colorMap[1] = new ColorMap();
colorMap[1].OldColor = Color.Black;
colorMap[1].NewColor = this.ForeColor;
imageAttr.SetRemapTable(colorMap);
}
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
if ((!Enabled) && (null == ImageDisabled))
{
using (Bitmap bitmapMono = new Bitmap(image, ClientRectangle.Size))
{
if (imageAttr != null)
{
using (Graphics gMono = Graphics.FromImage(bitmapMono))
{
gMono.DrawImage(image, new Point[3] { new Point(0, 0), new Point(image.Width - 1, 0), new Point(0, image.Height - 1) }, rect, GraphicsUnit.Pixel, imageAttr);
}
}
ControlPaint.DrawImageDisabled(g, bitmapMono, 0, 0, this.BackColor);
}
}
else
{
// Three points provided are upper-left, upper-right and
// lower-left of the destination parallelogram.
Point[] pts = new Point[3];
pts[0].X = (Enabled && m_mouseOver && m_mouseCapture) ? 1 : 0;
pts[0].Y = (Enabled && m_mouseOver && m_mouseCapture) ? 1 : 0;
pts[1].X = pts[0].X + ClientRectangle.Width;
pts[1].Y = pts[0].Y;
pts[2].X = pts[0].X;
pts[2].Y = pts[1].Y + ClientRectangle.Height;
if (imageAttr == null)
g.DrawImage(image, pts, rect, GraphicsUnit.Pixel);
else
g.DrawImage(image, pts, rect, GraphicsUnit.Pixel, imageAttr);
}
}
private void DrawText(Graphics g)
{
if (Text == string.Empty)
return;
Rectangle rect = ClientRectangle;
rect.X += BorderWidth;
rect.Y += BorderWidth;
rect.Width -= 2 * BorderWidth;
rect.Height -= 2 * BorderWidth;
StringFormat stringFormat = new StringFormat();
if (TextAlign == ContentAlignment.TopLeft)
{
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Near;
}
else if (TextAlign == ContentAlignment.TopCenter)
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Near;
}
else if (TextAlign == ContentAlignment.TopRight)
{
stringFormat.Alignment = StringAlignment.Far;
stringFormat.LineAlignment = StringAlignment.Near;
}
else if (TextAlign == ContentAlignment.MiddleLeft)
{
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Center;
}
else if (TextAlign == ContentAlignment.MiddleCenter)
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
}
else if (TextAlign == ContentAlignment.MiddleRight)
{
stringFormat.Alignment = StringAlignment.Far;
stringFormat.LineAlignment = StringAlignment.Center;
}
else if (TextAlign == ContentAlignment.BottomLeft)
{
stringFormat.Alignment = StringAlignment.Near;
stringFormat.LineAlignment = StringAlignment.Far;
}
else if (TextAlign == ContentAlignment.BottomCenter)
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Far;
}
else if (TextAlign == ContentAlignment.BottomRight)
{
stringFormat.Alignment = StringAlignment.Far;
stringFormat.LineAlignment = StringAlignment.Far;
}
using (Brush brush = new SolidBrush(ForeColor))
{
g.DrawString(Text, Font, brush, rect, stringFormat);
}
}
private void DrawBorder(Graphics g)
{
ButtonBorderStyle bs;
// Decide on the type of border to draw around image
if (!this.Enabled)
bs = IsPopup ? ButtonBorderStyle.Outset : ButtonBorderStyle.Solid;
else if (m_mouseOver && m_mouseCapture)
bs = ButtonBorderStyle.Inset;
else if (IsPopup || m_mouseOver)
bs = ButtonBorderStyle.Outset;
else
bs = ButtonBorderStyle.Solid;
Color colorLeftTop;
Color colorRightBottom;
if (bs == ButtonBorderStyle.Solid)
{
colorLeftTop = this.BackColor;
colorRightBottom = this.BackColor;
}
else if (bs == ButtonBorderStyle.Outset)
{
colorLeftTop = m_borderColor.IsEmpty ? this.BackColor : m_borderColor;
colorRightBottom = this.BackColor;
}
else
{
colorLeftTop = this.BackColor;
colorRightBottom = m_borderColor.IsEmpty ? this.BackColor : m_borderColor;
}
ControlPaint.DrawBorder(g, this.ClientRectangle,
colorLeftTop, m_borderWidth, bs,
colorLeftTop, m_borderWidth, bs,
colorRightBottom, m_borderWidth, bs,
colorRightBottom, m_borderWidth, bs);
}
/// <exclude/>
protected override void OnEnabledChanged(EventArgs e)
{
base.OnEnabledChanged(e);
if (Enabled == false)
{
m_mouseOver = false;
m_mouseCapture = false;
if (RepeatClick && ClickStatus != RepeatClickStatus.Stopped)
ClickStatus = RepeatClickStatus.Stopped;
}
Invalidate();
}
}
}
| |
using System;
using System.Windows.Input;
using Xunit;
using Prism.Commands;
using System.Threading;
using Xunit.Sdk;
namespace Prism.Tests.Mvvm
{
public class CompositeCommandFixture
{
[Fact]
public void RegisterACommandShouldRaiseCanExecuteEvent()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommand = new TestCommand();
multiCommand.RegisterCommand(new TestCommand());
Assert.True(multiCommand.CanExecuteChangedRaised);
}
[Fact]
public void ShouldDelegateExecuteToSingleRegistrant()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommand = new TestCommand();
multiCommand.RegisterCommand(testCommand);
Assert.False(testCommand.ExecuteCalled);
multiCommand.Execute(null);
Assert.True(testCommand.ExecuteCalled);
}
[Fact]
public void ShouldDelegateExecuteToMultipleRegistrants()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand();
TestCommand testCommandTwo = new TestCommand();
multiCommand.RegisterCommand(testCommandOne);
multiCommand.RegisterCommand(testCommandTwo);
Assert.False(testCommandOne.ExecuteCalled);
Assert.False(testCommandTwo.ExecuteCalled);
multiCommand.Execute(null);
Assert.True(testCommandOne.ExecuteCalled);
Assert.True(testCommandTwo.ExecuteCalled);
}
[Fact]
public void ShouldDelegateCanExecuteToSingleRegistrant()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommand = new TestCommand();
multiCommand.RegisterCommand(testCommand);
Assert.False(testCommand.CanExecuteCalled);
multiCommand.CanExecute(null);
Assert.True(testCommand.CanExecuteCalled);
}
[Fact]
public void ShouldDelegateCanExecuteToMultipleRegistrants()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand();
TestCommand testCommandTwo = new TestCommand();
multiCommand.RegisterCommand(testCommandOne);
multiCommand.RegisterCommand(testCommandTwo);
Assert.False(testCommandOne.CanExecuteCalled);
Assert.False(testCommandTwo.CanExecuteCalled);
multiCommand.CanExecute(null);
Assert.True(testCommandOne.CanExecuteCalled);
Assert.True(testCommandTwo.CanExecuteCalled);
}
[Fact]
public void CanExecuteShouldReturnTrueIfAllRegistrantsTrue()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
TestCommand testCommandTwo = new TestCommand() { CanExecuteValue = true };
multiCommand.RegisterCommand(testCommandOne);
multiCommand.RegisterCommand(testCommandTwo);
Assert.True(multiCommand.CanExecute(null));
}
[Fact]
public void CanExecuteShouldReturnFalseIfASingleRegistrantsFalse()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
TestCommand testCommandTwo = new TestCommand() { CanExecuteValue = false };
multiCommand.RegisterCommand(testCommandOne);
multiCommand.RegisterCommand(testCommandTwo);
Assert.False(multiCommand.CanExecute(null));
}
[Fact]
public void ShouldReraiseCanExecuteChangedEvent()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
Assert.False(multiCommand.CanExecuteChangedRaised);
multiCommand.RegisterCommand(testCommandOne);
multiCommand.CanExecuteChangedRaised = false;
testCommandOne.FireCanExecuteChanged();
Assert.True(multiCommand.CanExecuteChangedRaised);
}
[Fact]
public void ShouldReraiseCanExecuteChangedEventAfterCollect()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
Assert.False(multiCommand.CanExecuteChangedRaised);
multiCommand.RegisterCommand(testCommandOne);
multiCommand.CanExecuteChangedRaised = false;
GC.Collect();
testCommandOne.FireCanExecuteChanged();
Assert.True(multiCommand.CanExecuteChangedRaised);
}
[Fact]
public void ShouldReraiseDelegateCommandCanExecuteChangedEventAfterCollect()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
DelegateCommand<object> delegateCommand = new DelegateCommand<object>(delegate { });
Assert.False(multiCommand.CanExecuteChangedRaised);
multiCommand.RegisterCommand(delegateCommand);
multiCommand.CanExecuteChangedRaised = false;
GC.Collect();
delegateCommand.RaiseCanExecuteChanged();
Assert.True(multiCommand.CanExecuteChangedRaised);
}
[Fact]
public void UnregisteringCommandWithNullThrows()
{
Assert.Throws<ArgumentNullException>(() =>
{
var compositeCommand = new CompositeCommand();
compositeCommand.UnregisterCommand(null);
});
}
[Fact]
public void UnregisterCommandRemovesFromExecuteDelegation()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
multiCommand.RegisterCommand(testCommandOne);
multiCommand.UnregisterCommand(testCommandOne);
Assert.False(testCommandOne.ExecuteCalled);
multiCommand.Execute(null);
Assert.False(testCommandOne.ExecuteCalled);
}
[Fact]
public void UnregisterCommandShouldRaiseCanExecuteEvent()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand();
multiCommand.RegisterCommand(testCommandOne);
multiCommand.CanExecuteChangedRaised = false;
multiCommand.UnregisterCommand(testCommandOne);
Assert.True(multiCommand.CanExecuteChangedRaised);
}
[Fact]
public void ExecuteDoesNotThrowWhenAnExecuteCommandModifiesTheCommandsCollection()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
SelfUnregisterableCommand commandOne = new SelfUnregisterableCommand(multiCommand);
SelfUnregisterableCommand commandTwo = new SelfUnregisterableCommand(multiCommand);
multiCommand.RegisterCommand(commandOne);
multiCommand.RegisterCommand(commandTwo);
multiCommand.Execute(null);
Assert.True(commandOne.ExecutedCalled);
Assert.True(commandTwo.ExecutedCalled);
}
[Fact]
public void UnregisterCommandDisconnectsCanExecuteChangedDelegate()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true };
multiCommand.RegisterCommand(testCommandOne);
multiCommand.UnregisterCommand(testCommandOne);
multiCommand.CanExecuteChangedRaised = false;
testCommandOne.FireCanExecuteChanged();
Assert.False(multiCommand.CanExecuteChangedRaised);
}
[Fact]
public void UnregisterCommandDisconnectsIsActiveChangedDelegate()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand commandOne = new MockActiveAwareCommand() { IsActive = true, IsValid = true };
MockActiveAwareCommand commandTwo = new MockActiveAwareCommand() { IsActive = false, IsValid = false };
activeAwareCommand.RegisterCommand(commandOne);
activeAwareCommand.RegisterCommand(commandTwo);
Assert.True(activeAwareCommand.CanExecute(null));
activeAwareCommand.UnregisterCommand(commandOne);
Assert.False(activeAwareCommand.CanExecute(null));
}
[Fact]
public void ShouldBubbleException()
{
Assert.Throws<DivideByZeroException>(() =>
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
BadDivisionCommand testCommand = new BadDivisionCommand();
multiCommand.RegisterCommand(testCommand);
multiCommand.Execute(null);
});
}
[Fact]
public void CanExecuteShouldReturnFalseWithNoCommandsRegistered()
{
TestableCompositeCommand multiCommand = new TestableCompositeCommand();
Assert.False(multiCommand.CanExecute(null));
}
[Fact]
public void MultiDispatchCommandExecutesActiveRegisteredCommands()
{
CompositeCommand activeAwareCommand = new CompositeCommand();
MockActiveAwareCommand command = new MockActiveAwareCommand();
command.IsActive = true;
activeAwareCommand.RegisterCommand(command);
activeAwareCommand.Execute(null);
Assert.True(command.WasExecuted);
}
[Fact]
public void MultiDispatchCommandDoesNotExecutesInactiveRegisteredCommands()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand command = new MockActiveAwareCommand();
command.IsActive = false;
activeAwareCommand.RegisterCommand(command);
activeAwareCommand.Execute(null);
Assert.False(command.WasExecuted);
}
[Fact]
public void DispatchCommandDoesNotIncludeInactiveRegisteredCommandInVoting()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand command = new MockActiveAwareCommand();
activeAwareCommand.RegisterCommand(command);
command.IsValid = true;
command.IsActive = false;
Assert.False(activeAwareCommand.CanExecute(null), "Registered Click is inactive so should not participate in CanExecute vote");
command.IsActive = true;
Assert.True(activeAwareCommand.CanExecute(null));
command.IsValid = false;
Assert.False(activeAwareCommand.CanExecute(null));
}
[Fact]
public void DispatchCommandShouldIgnoreInactiveCommandsInCanExecuteVote()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand commandOne = new MockActiveAwareCommand() { IsActive = false, IsValid = false };
MockActiveAwareCommand commandTwo = new MockActiveAwareCommand() { IsActive = true, IsValid = true };
activeAwareCommand.RegisterCommand(commandOne);
activeAwareCommand.RegisterCommand(commandTwo);
Assert.True(activeAwareCommand.CanExecute(null));
}
[Fact]
public void ActivityCausesActiveAwareCommandToRequeryCanExecute()
{
CompositeCommand activeAwareCommand = new CompositeCommand(true);
MockActiveAwareCommand command = new MockActiveAwareCommand();
activeAwareCommand.RegisterCommand(command);
command.IsActive = true;
bool globalCanExecuteChangeFired = false;
activeAwareCommand.CanExecuteChanged += delegate
{
globalCanExecuteChangeFired = true;
};
Assert.False(globalCanExecuteChangeFired);
command.IsActive = false;
Assert.True(globalCanExecuteChangeFired);
}
[Fact]
public void ShouldNotMonitorActivityIfUseActiveMonitoringFalse()
{
var mockCommand = new MockActiveAwareCommand();
mockCommand.IsValid = true;
mockCommand.IsActive = true;
var nonActiveAwareCompositeCommand = new CompositeCommand(false);
bool canExecuteChangedRaised = false;
nonActiveAwareCompositeCommand.RegisterCommand(mockCommand);
nonActiveAwareCompositeCommand.CanExecuteChanged += delegate
{
canExecuteChangedRaised = true;
};
mockCommand.IsActive = false;
Assert.False(canExecuteChangedRaised);
nonActiveAwareCompositeCommand.Execute(null);
Assert.True(mockCommand.WasExecuted);
}
[Fact]
public void ShouldRemoveCanExecuteChangedHandler()
{
bool canExecuteChangedRaised = false;
var compositeCommand = new CompositeCommand();
var commmand = new DelegateCommand(() => { });
compositeCommand.RegisterCommand(commmand);
EventHandler handler = (s, e) => canExecuteChangedRaised = true;
compositeCommand.CanExecuteChanged += handler;
commmand.RaiseCanExecuteChanged();
Assert.True(canExecuteChangedRaised);
canExecuteChangedRaised = false;
compositeCommand.CanExecuteChanged -= handler;
commmand.RaiseCanExecuteChanged();
Assert.False(canExecuteChangedRaised);
}
[Fact]
public void ShouldIgnoreChangesToIsActiveDuringExecution()
{
var firstCommand = new MockActiveAwareCommand { IsActive = true };
var secondCommand = new MockActiveAwareCommand { IsActive = true };
// During execution set the second command to inactive, this should not affect the currently
// executed selection.
firstCommand.ExecuteAction += new Action<object>((object parameter) => secondCommand.IsActive = false);
var compositeCommand = new CompositeCommand(true);
compositeCommand.RegisterCommand(firstCommand);
compositeCommand.RegisterCommand(secondCommand);
compositeCommand.Execute(null);
Assert.True(secondCommand.WasExecuted);
}
[Fact]
public void RegisteringCommandInItselfThrows()
{
Assert.Throws<ArgumentException>(() =>
{
var compositeCommand = new CompositeCommand();
compositeCommand.RegisterCommand(compositeCommand);
});
}
[Fact]
public void RegisteringCommandWithNullThrows()
{
Assert.Throws<ArgumentNullException>(() =>
{
var compositeCommand = new CompositeCommand();
compositeCommand.RegisterCommand(null);
});
}
[Fact]
public void RegisteringCommandTwiceThrows()
{
Assert.Throws<InvalidOperationException>(() =>
{
var compositeCommand = new CompositeCommand();
var duplicateCommand = new TestCommand();
compositeCommand.RegisterCommand(duplicateCommand);
compositeCommand.RegisterCommand(duplicateCommand);
});
}
[Fact]
public void ShouldGetRegisteredCommands()
{
var firstCommand = new TestCommand();
var secondCommand = new TestCommand();
var compositeCommand = new CompositeCommand();
compositeCommand.RegisterCommand(firstCommand);
compositeCommand.RegisterCommand(secondCommand);
var commands = compositeCommand.RegisteredCommands;
Assert.True(commands.Count > 0);
}
}
internal class MockActiveAwareCommand : IActiveAware, ICommand
{
private bool _isActive;
public Action<object> ExecuteAction;
#region IActiveAware Members
public bool IsActive
{
get { return _isActive; }
set
{
if (_isActive != value)
{
_isActive = value;
OnActiveChanged(this, EventArgs.Empty);
}
}
}
public event EventHandler IsActiveChanged = delegate { };
#endregion
virtual protected void OnActiveChanged(object sender, EventArgs e)
{
IsActiveChanged(sender, e);
}
public bool WasExecuted { get; set; }
public bool IsValid { get; set; }
#region ICommand Members
public bool CanExecute(object parameter)
{
return IsValid;
}
public event EventHandler CanExecuteChanged = delegate { };
public void Execute(object parameter)
{
WasExecuted = true;
if (ExecuteAction != null)
ExecuteAction(parameter);
}
#endregion
}
internal class TestableCompositeCommand : CompositeCommand
{
public bool CanExecuteChangedRaised;
private EventHandler handler;
public TestableCompositeCommand()
{
this.handler = ((sender, e) => CanExecuteChangedRaised = true);
CanExecuteChanged += this.handler;
}
}
internal class TestCommand : ICommand
{
public bool CanExecuteCalled { get; set; }
public bool ExecuteCalled { get; set; }
public int ExecuteCallCount { get; set; }
public bool CanExecuteValue = true;
public void FireCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
#region ICommand Members
public bool CanExecute(object parameter)
{
CanExecuteCalled = true;
return CanExecuteValue;
}
public event EventHandler CanExecuteChanged = delegate { };
public void Execute(object parameter)
{
ExecuteCalled = true;
ExecuteCallCount += 1;
}
#endregion
}
internal class BadDivisionCommand : ICommand
{
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged = delegate { };
public void Execute(object parameter)
{
throw new DivideByZeroException("Test Divide By Zero");
}
#endregion
}
internal class SelfUnregisterableCommand : ICommand
{
public CompositeCommand Command;
public bool ExecutedCalled = false;
public SelfUnregisterableCommand(CompositeCommand command)
{
Command = command;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
throw new NotImplementedException();
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
Command.UnregisterCommand(this);
ExecutedCalled = true;
}
#endregion
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Creditor Purchasing Card Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KCPCDataSet : EduHubDataSet<KCPC>
{
/// <inheritdoc />
public override string Name { get { return "KCPC"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KCPCDataSet(EduHubContext Context)
: base(Context)
{
Index_CAMPUS = new Lazy<NullDictionary<int?, IReadOnlyList<KCPC>>>(() => this.ToGroupedNullDictionary(i => i.CAMPUS));
Index_STAFF = new Lazy<NullDictionary<string, IReadOnlyList<KCPC>>>(() => this.ToGroupedNullDictionary(i => i.STAFF));
Index_TID = new Lazy<Dictionary<int, KCPC>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KCPC" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KCPC" /> fields for each CSV column header</returns>
internal override Action<KCPC, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KCPC, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "STAFF":
mapper[i] = (e, v) => e.STAFF = v;
break;
case "CARDHOLDER_NAME":
mapper[i] = (e, v) => e.CARDHOLDER_NAME = v;
break;
case "CARD_NO":
mapper[i] = (e, v) => e.CARD_NO = v;
break;
case "STAFF_POSITION":
mapper[i] = (e, v) => e.STAFF_POSITION = v;
break;
case "ISSUE_DATE":
mapper[i] = (e, v) => e.ISSUE_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "EXPIRY_MONTH":
mapper[i] = (e, v) => e.EXPIRY_MONTH = v == null ? (short?)null : short.Parse(v);
break;
case "EXPIRY_YEAR":
mapper[i] = (e, v) => e.EXPIRY_YEAR = v == null ? (short?)null : short.Parse(v);
break;
case "CAMPUS":
mapper[i] = (e, v) => e.CAMPUS = v == null ? (int?)null : int.Parse(v);
break;
case "UNDERTAKING_CARDHOLDER":
mapper[i] = (e, v) => e.UNDERTAKING_CARDHOLDER = v;
break;
case "CARD_LIMIT":
mapper[i] = (e, v) => e.CARD_LIMIT = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CHANGE_LIMIT":
mapper[i] = (e, v) => e.CHANGE_LIMIT = v;
break;
case "CANCELLATION_DATE":
mapper[i] = (e, v) => e.CANCELLATION_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "ACTIVE":
mapper[i] = (e, v) => e.ACTIVE = v;
break;
case "PROCESSED":
mapper[i] = (e, v) => e.PROCESSED = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KCPC" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KCPC" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KCPC" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KCPC}"/> of entities</returns>
internal override IEnumerable<KCPC> ApplyDeltaEntities(IEnumerable<KCPC> Entities, List<KCPC> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.TID;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.TID.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<int?, IReadOnlyList<KCPC>>> Index_CAMPUS;
private Lazy<NullDictionary<string, IReadOnlyList<KCPC>>> Index_STAFF;
private Lazy<Dictionary<int, KCPC>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find KCPC by CAMPUS field
/// </summary>
/// <param name="CAMPUS">CAMPUS value used to find KCPC</param>
/// <returns>List of related KCPC entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KCPC> FindByCAMPUS(int? CAMPUS)
{
return Index_CAMPUS.Value[CAMPUS];
}
/// <summary>
/// Attempt to find KCPC by CAMPUS field
/// </summary>
/// <param name="CAMPUS">CAMPUS value used to find KCPC</param>
/// <param name="Value">List of related KCPC entities</param>
/// <returns>True if the list of related KCPC entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByCAMPUS(int? CAMPUS, out IReadOnlyList<KCPC> Value)
{
return Index_CAMPUS.Value.TryGetValue(CAMPUS, out Value);
}
/// <summary>
/// Attempt to find KCPC by CAMPUS field
/// </summary>
/// <param name="CAMPUS">CAMPUS value used to find KCPC</param>
/// <returns>List of related KCPC entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KCPC> TryFindByCAMPUS(int? CAMPUS)
{
IReadOnlyList<KCPC> value;
if (Index_CAMPUS.Value.TryGetValue(CAMPUS, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find KCPC by STAFF field
/// </summary>
/// <param name="STAFF">STAFF value used to find KCPC</param>
/// <returns>List of related KCPC entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KCPC> FindBySTAFF(string STAFF)
{
return Index_STAFF.Value[STAFF];
}
/// <summary>
/// Attempt to find KCPC by STAFF field
/// </summary>
/// <param name="STAFF">STAFF value used to find KCPC</param>
/// <param name="Value">List of related KCPC entities</param>
/// <returns>True if the list of related KCPC entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySTAFF(string STAFF, out IReadOnlyList<KCPC> Value)
{
return Index_STAFF.Value.TryGetValue(STAFF, out Value);
}
/// <summary>
/// Attempt to find KCPC by STAFF field
/// </summary>
/// <param name="STAFF">STAFF value used to find KCPC</param>
/// <returns>List of related KCPC entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KCPC> TryFindBySTAFF(string STAFF)
{
IReadOnlyList<KCPC> value;
if (Index_STAFF.Value.TryGetValue(STAFF, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find KCPC by TID field
/// </summary>
/// <param name="TID">TID value used to find KCPC</param>
/// <returns>Related KCPC entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KCPC FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find KCPC by TID field
/// </summary>
/// <param name="TID">TID value used to find KCPC</param>
/// <param name="Value">Related KCPC entity</param>
/// <returns>True if the related KCPC entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out KCPC Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find KCPC by TID field
/// </summary>
/// <param name="TID">TID value used to find KCPC</param>
/// <returns>Related KCPC entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KCPC TryFindByTID(int TID)
{
KCPC value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KCPC table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KCPC]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KCPC](
[TID] int IDENTITY NOT NULL,
[STAFF] varchar(4) NULL,
[CARDHOLDER_NAME] varchar(30) NULL,
[CARD_NO] varchar(4) NULL,
[STAFF_POSITION] varchar(10) NULL,
[ISSUE_DATE] datetime NULL,
[EXPIRY_MONTH] smallint NULL,
[EXPIRY_YEAR] smallint NULL,
[CAMPUS] int NULL,
[UNDERTAKING_CARDHOLDER] varchar(3) NULL,
[CARD_LIMIT] money NULL,
[CHANGE_LIMIT] varchar(MAX) NULL,
[CANCELLATION_DATE] datetime NULL,
[ACTIVE] varchar(1) NULL,
[PROCESSED] varchar(1) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KCPC_Index_TID] PRIMARY KEY CLUSTERED (
[TID] ASC
)
);
CREATE NONCLUSTERED INDEX [KCPC_Index_CAMPUS] ON [dbo].[KCPC]
(
[CAMPUS] ASC
);
CREATE NONCLUSTERED INDEX [KCPC_Index_STAFF] ON [dbo].[KCPC]
(
[STAFF] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCPC]') AND name = N'KCPC_Index_CAMPUS')
ALTER INDEX [KCPC_Index_CAMPUS] ON [dbo].[KCPC] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCPC]') AND name = N'KCPC_Index_STAFF')
ALTER INDEX [KCPC_Index_STAFF] ON [dbo].[KCPC] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCPC]') AND name = N'KCPC_Index_CAMPUS')
ALTER INDEX [KCPC_Index_CAMPUS] ON [dbo].[KCPC] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCPC]') AND name = N'KCPC_Index_STAFF')
ALTER INDEX [KCPC_Index_STAFF] ON [dbo].[KCPC] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KCPC"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KCPC"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KCPC> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[KCPC] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KCPC data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KCPC data set</returns>
public override EduHubDataSetDataReader<KCPC> GetDataSetDataReader()
{
return new KCPCDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KCPC data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KCPC data set</returns>
public override EduHubDataSetDataReader<KCPC> GetDataSetDataReader(List<KCPC> Entities)
{
return new KCPCDataReader(new EduHubDataSetLoadedReader<KCPC>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KCPCDataReader : EduHubDataSetDataReader<KCPC>
{
public KCPCDataReader(IEduHubDataSetReader<KCPC> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 18; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // STAFF
return Current.STAFF;
case 2: // CARDHOLDER_NAME
return Current.CARDHOLDER_NAME;
case 3: // CARD_NO
return Current.CARD_NO;
case 4: // STAFF_POSITION
return Current.STAFF_POSITION;
case 5: // ISSUE_DATE
return Current.ISSUE_DATE;
case 6: // EXPIRY_MONTH
return Current.EXPIRY_MONTH;
case 7: // EXPIRY_YEAR
return Current.EXPIRY_YEAR;
case 8: // CAMPUS
return Current.CAMPUS;
case 9: // UNDERTAKING_CARDHOLDER
return Current.UNDERTAKING_CARDHOLDER;
case 10: // CARD_LIMIT
return Current.CARD_LIMIT;
case 11: // CHANGE_LIMIT
return Current.CHANGE_LIMIT;
case 12: // CANCELLATION_DATE
return Current.CANCELLATION_DATE;
case 13: // ACTIVE
return Current.ACTIVE;
case 14: // PROCESSED
return Current.PROCESSED;
case 15: // LW_DATE
return Current.LW_DATE;
case 16: // LW_TIME
return Current.LW_TIME;
case 17: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // STAFF
return Current.STAFF == null;
case 2: // CARDHOLDER_NAME
return Current.CARDHOLDER_NAME == null;
case 3: // CARD_NO
return Current.CARD_NO == null;
case 4: // STAFF_POSITION
return Current.STAFF_POSITION == null;
case 5: // ISSUE_DATE
return Current.ISSUE_DATE == null;
case 6: // EXPIRY_MONTH
return Current.EXPIRY_MONTH == null;
case 7: // EXPIRY_YEAR
return Current.EXPIRY_YEAR == null;
case 8: // CAMPUS
return Current.CAMPUS == null;
case 9: // UNDERTAKING_CARDHOLDER
return Current.UNDERTAKING_CARDHOLDER == null;
case 10: // CARD_LIMIT
return Current.CARD_LIMIT == null;
case 11: // CHANGE_LIMIT
return Current.CHANGE_LIMIT == null;
case 12: // CANCELLATION_DATE
return Current.CANCELLATION_DATE == null;
case 13: // ACTIVE
return Current.ACTIVE == null;
case 14: // PROCESSED
return Current.PROCESSED == null;
case 15: // LW_DATE
return Current.LW_DATE == null;
case 16: // LW_TIME
return Current.LW_TIME == null;
case 17: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // STAFF
return "STAFF";
case 2: // CARDHOLDER_NAME
return "CARDHOLDER_NAME";
case 3: // CARD_NO
return "CARD_NO";
case 4: // STAFF_POSITION
return "STAFF_POSITION";
case 5: // ISSUE_DATE
return "ISSUE_DATE";
case 6: // EXPIRY_MONTH
return "EXPIRY_MONTH";
case 7: // EXPIRY_YEAR
return "EXPIRY_YEAR";
case 8: // CAMPUS
return "CAMPUS";
case 9: // UNDERTAKING_CARDHOLDER
return "UNDERTAKING_CARDHOLDER";
case 10: // CARD_LIMIT
return "CARD_LIMIT";
case 11: // CHANGE_LIMIT
return "CHANGE_LIMIT";
case 12: // CANCELLATION_DATE
return "CANCELLATION_DATE";
case 13: // ACTIVE
return "ACTIVE";
case 14: // PROCESSED
return "PROCESSED";
case 15: // LW_DATE
return "LW_DATE";
case 16: // LW_TIME
return "LW_TIME";
case 17: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "STAFF":
return 1;
case "CARDHOLDER_NAME":
return 2;
case "CARD_NO":
return 3;
case "STAFF_POSITION":
return 4;
case "ISSUE_DATE":
return 5;
case "EXPIRY_MONTH":
return 6;
case "EXPIRY_YEAR":
return 7;
case "CAMPUS":
return 8;
case "UNDERTAKING_CARDHOLDER":
return 9;
case "CARD_LIMIT":
return 10;
case "CHANGE_LIMIT":
return 11;
case "CANCELLATION_DATE":
return 12;
case "ACTIVE":
return 13;
case "PROCESSED":
return 14;
case "LW_DATE":
return 15;
case "LW_TIME":
return 16;
case "LW_USER":
return 17;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
public partial class Loop2000A : LoopEntity{
public HlCollection InformationSourceLevel {get;set;}
public Loop2000A(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
InformationSourceLevel = new HlCollection(this, nameof(InformationSourceLevel));
SegmentCollections.Add(InformationSourceLevel);
}
}
public partial class Loop2100A : LoopEntity{
public Nm1Collection PayerName {get;set;}
public Loop2100A(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
PayerName = new Nm1Collection(this, nameof(PayerName));
SegmentCollections.Add(PayerName);
}
}
public partial class Loop2000B : LoopEntity{
public HlCollection InformationReceiverLevel {get;set;}
public Loop2000B(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
InformationReceiverLevel = new HlCollection(this, nameof(InformationReceiverLevel));
SegmentCollections.Add(InformationReceiverLevel);
}
}
public partial class Loop2100B : LoopEntity{
public Nm1Collection InformationReceiverName {get;set;}
public Loop2000CCollection ServiceProviderLevelLoop {get;set;}
public Loop2100CCollection ProviderNameLoop {get;set;}
public Loop2100B(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
InformationReceiverName = new Nm1Collection(this, nameof(InformationReceiverName));
SegmentCollections.Add(InformationReceiverName);
ServiceProviderLevelLoop = new Loop2000CCollection("Loop2000C", nameof(ServiceProviderLevelLoop), OwningDoc, parent, parent);
ChildLoopCollections.Add(ServiceProviderLevelLoop);
ProviderNameLoop = new Loop2100CCollection("Loop2100C", nameof(ProviderNameLoop), OwningDoc, parent, parent);
ChildLoopCollections.Add(ProviderNameLoop);
}
}
public partial class Loop2000C : LoopEntity{
public HlCollection ServiceProviderLevel {get;set;}
public Loop2000C(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
ServiceProviderLevel = new HlCollection(this, nameof(ServiceProviderLevel));
SegmentCollections.Add(ServiceProviderLevel);
}
}
public partial class Loop2100C : LoopEntity{
public Nm1Collection ProviderName {get;set;}
public Loop2000DCollection SubscriberLevelLoop {get;set;}
public Loop2100DCollection SubscriberNameLoop {get;set;}
public Loop2100C(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
ProviderName = new Nm1Collection(this, nameof(ProviderName));
SegmentCollections.Add(ProviderName);
SubscriberLevelLoop = new Loop2000DCollection("Loop2000D", nameof(SubscriberLevelLoop), OwningDoc, parent, parent);
ChildLoopCollections.Add(SubscriberLevelLoop);
SubscriberNameLoop = new Loop2100DCollection("Loop2100D", nameof(SubscriberNameLoop), OwningDoc, parent, parent);
ChildLoopCollections.Add(SubscriberNameLoop);
}
}
public partial class Loop2000D : LoopEntity{
public HlCollection SubscriberLevel {get;set;}
public DmgCollection SubscriberDemographicInformation {get;set;}
public Loop2000D(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
SubscriberLevel = new HlCollection(this, nameof(SubscriberLevel));
SegmentCollections.Add(SubscriberLevel);
SubscriberDemographicInformation = new DmgCollection(this, nameof(SubscriberDemographicInformation));
SegmentCollections.Add(SubscriberDemographicInformation);
}
}
public partial class Loop2100D : LoopEntity{
public Nm1Collection SubscriberName {get;set;}
public Loop2200DCollection ClaimStatusTrackingNumberLoop {get;set;}
public Loop2100D(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
SubscriberName = new Nm1Collection(this, nameof(SubscriberName));
SegmentCollections.Add(SubscriberName);
ClaimStatusTrackingNumberLoop = new Loop2200DCollection("Loop2200D", nameof(ClaimStatusTrackingNumberLoop), OwningDoc, parent, parent);
ChildLoopCollections.Add(ClaimStatusTrackingNumberLoop);
}
}
public partial class Loop2200D : LoopEntity{
public TrnCollection ClaimStatusTrackingNumber {get;set;}
public RefCollection PayerClaimControlNumber {get;set;}
public RefCollection InstitutionalBillTypeIdentification {get;set;}
public RefCollection ApplicationOrLocationSystemIdentifier {get;set;}
public RefCollection GroupNumber {get;set;}
public RefCollection PatientControlNumber {get;set;}
public RefCollection PharmacyPrescriptionNumber {get;set;}
public RefCollection ClaimIdentificationNumberForClearinghousesAnd {get;set;}
public AmtCollection ClaimSubmittedCharges {get;set;}
public DtpCollection ClaimServiceDate {get;set;}
public Loop2210DCollection ServiceLineInformationLoop {get;set;}
public Loop2000ECollection DependentLevelLoop {get;set;}
public Loop2100ECollection DependentNameLoop {get;set;}
public Loop2200ECollection ClaimStatusTrackingNumberLoop {get;set;}
public Loop2200D(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
ClaimStatusTrackingNumber = new TrnCollection(this, nameof(ClaimStatusTrackingNumber));
SegmentCollections.Add(ClaimStatusTrackingNumber);
PayerClaimControlNumber = new RefCollection(this, nameof(PayerClaimControlNumber));
SegmentCollections.Add(PayerClaimControlNumber);
InstitutionalBillTypeIdentification = new RefCollection(this, nameof(InstitutionalBillTypeIdentification));
SegmentCollections.Add(InstitutionalBillTypeIdentification);
ApplicationOrLocationSystemIdentifier = new RefCollection(this, nameof(ApplicationOrLocationSystemIdentifier));
SegmentCollections.Add(ApplicationOrLocationSystemIdentifier);
GroupNumber = new RefCollection(this, nameof(GroupNumber));
SegmentCollections.Add(GroupNumber);
PatientControlNumber = new RefCollection(this, nameof(PatientControlNumber));
SegmentCollections.Add(PatientControlNumber);
PharmacyPrescriptionNumber = new RefCollection(this, nameof(PharmacyPrescriptionNumber));
SegmentCollections.Add(PharmacyPrescriptionNumber);
ClaimIdentificationNumberForClearinghousesAnd = new RefCollection(this, nameof(ClaimIdentificationNumberForClearinghousesAnd));
SegmentCollections.Add(ClaimIdentificationNumberForClearinghousesAnd);
ClaimSubmittedCharges = new AmtCollection(this, nameof(ClaimSubmittedCharges));
SegmentCollections.Add(ClaimSubmittedCharges);
ClaimServiceDate = new DtpCollection(this, nameof(ClaimServiceDate));
SegmentCollections.Add(ClaimServiceDate);
ServiceLineInformationLoop = new Loop2210DCollection("Loop2210D", nameof(ServiceLineInformationLoop), OwningDoc, parent, parent);
ChildLoopCollections.Add(ServiceLineInformationLoop);
DependentLevelLoop = new Loop2000ECollection("Loop2000E", nameof(DependentLevelLoop), OwningDoc, parent, parent);
ChildLoopCollections.Add(DependentLevelLoop);
DependentNameLoop = new Loop2100ECollection("Loop2100E", nameof(DependentNameLoop), OwningDoc, parent, parent);
ChildLoopCollections.Add(DependentNameLoop);
ClaimStatusTrackingNumberLoop = new Loop2200ECollection("Loop2200E", nameof(ClaimStatusTrackingNumberLoop), OwningDoc, parent, parent);
ChildLoopCollections.Add(ClaimStatusTrackingNumberLoop);
}
}
public partial class Loop2210D : LoopEntity{
public SvcCollection ServiceLineInformation {get;set;}
public RefCollection ServiceLineItemIdentification {get;set;}
public DtpCollection ServiceLineDate {get;set;}
public Loop2210D(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
ServiceLineInformation = new SvcCollection(this, nameof(ServiceLineInformation));
SegmentCollections.Add(ServiceLineInformation);
ServiceLineItemIdentification = new RefCollection(this, nameof(ServiceLineItemIdentification));
SegmentCollections.Add(ServiceLineItemIdentification);
ServiceLineDate = new DtpCollection(this, nameof(ServiceLineDate));
SegmentCollections.Add(ServiceLineDate);
}
}
public partial class Loop2000E : LoopEntity{
public HlCollection DependentLevel {get;set;}
public DmgCollection DependentDemographicInformation {get;set;}
public Loop2000E(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
DependentLevel = new HlCollection(this, nameof(DependentLevel));
SegmentCollections.Add(DependentLevel);
DependentDemographicInformation = new DmgCollection(this, nameof(DependentDemographicInformation));
SegmentCollections.Add(DependentDemographicInformation);
}
}
public partial class Loop2100E : LoopEntity{
public Nm1Collection DependentName {get;set;}
public Loop2100E(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
DependentName = new Nm1Collection(this, nameof(DependentName));
SegmentCollections.Add(DependentName);
}
}
public partial class Loop2200E : LoopEntity{
public TrnCollection ClaimStatusTrackingNumber {get;set;}
public RefCollection PayerClaimControlNumber {get;set;}
public RefCollection InstitutionalBillTypeIdentification {get;set;}
public RefCollection ApplicationOrLocationSystemIdentifier {get;set;}
public RefCollection GroupNumber {get;set;}
public RefCollection PatientControlNumber {get;set;}
public RefCollection PharmacyPrescriptionNumber {get;set;}
public RefCollection ClaimIdentificationNumberForClearinghousesAnd {get;set;}
public AmtCollection ClaimSubmittedCharges {get;set;}
public DtpCollection ClaimServiceDate {get;set;}
public Loop2210ECollection ServiceLineInformationLoop {get;set;}
public Loop2200E(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
ClaimStatusTrackingNumber = new TrnCollection(this, nameof(ClaimStatusTrackingNumber));
SegmentCollections.Add(ClaimStatusTrackingNumber);
PayerClaimControlNumber = new RefCollection(this, nameof(PayerClaimControlNumber));
SegmentCollections.Add(PayerClaimControlNumber);
InstitutionalBillTypeIdentification = new RefCollection(this, nameof(InstitutionalBillTypeIdentification));
SegmentCollections.Add(InstitutionalBillTypeIdentification);
ApplicationOrLocationSystemIdentifier = new RefCollection(this, nameof(ApplicationOrLocationSystemIdentifier));
SegmentCollections.Add(ApplicationOrLocationSystemIdentifier);
GroupNumber = new RefCollection(this, nameof(GroupNumber));
SegmentCollections.Add(GroupNumber);
PatientControlNumber = new RefCollection(this, nameof(PatientControlNumber));
SegmentCollections.Add(PatientControlNumber);
PharmacyPrescriptionNumber = new RefCollection(this, nameof(PharmacyPrescriptionNumber));
SegmentCollections.Add(PharmacyPrescriptionNumber);
ClaimIdentificationNumberForClearinghousesAnd = new RefCollection(this, nameof(ClaimIdentificationNumberForClearinghousesAnd));
SegmentCollections.Add(ClaimIdentificationNumberForClearinghousesAnd);
ClaimSubmittedCharges = new AmtCollection(this, nameof(ClaimSubmittedCharges));
SegmentCollections.Add(ClaimSubmittedCharges);
ClaimServiceDate = new DtpCollection(this, nameof(ClaimServiceDate));
SegmentCollections.Add(ClaimServiceDate);
ServiceLineInformationLoop = new Loop2210ECollection("Loop2210E", nameof(ServiceLineInformationLoop), OwningDoc, parent, parent);
ChildLoopCollections.Add(ServiceLineInformationLoop);
}
}
public partial class Loop2210E : LoopEntity{
public SvcCollection ServiceLineInformation {get;set;}
public RefCollection ServiceLineItemIdentification {get;set;}
public DtpCollection ServiceLineDate {get;set;}
public TableCollection TransactionSetTrailer {get;set;}
public Loop2210E(X12Doc owningDoc, LoopEntity prev, LoopCollection parent):base(owningDoc, prev, parent){
ServiceLineInformation = new SvcCollection(this, nameof(ServiceLineInformation));
SegmentCollections.Add(ServiceLineInformation);
ServiceLineItemIdentification = new RefCollection(this, nameof(ServiceLineItemIdentification));
SegmentCollections.Add(ServiceLineItemIdentification);
ServiceLineDate = new DtpCollection(this, nameof(ServiceLineDate));
SegmentCollections.Add(ServiceLineDate);
TransactionSetTrailer = new TableCollection(this, nameof(TransactionSetTrailer));
SegmentCollections.Add(TransactionSetTrailer);
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace Crispy.Parsing
{
/// <summary>
/// A lexical scanner. Takes text and turns it into tokens.
/// </summary>
public class Tokenizer
{
private static readonly Dictionary<string, TokenType> Keywords = new Dictionary<string, TokenType>
{
{"if", TokenType.KeywordIf},
{"then", TokenType.KeywordThen},
{"else", TokenType.KeywordElse},
{"elseif", TokenType.KeywordElseIf},
{"endif", TokenType.KeywordEnd},
{"end", TokenType.KeywordEnd},
{"var", TokenType.KeywordVar},
{"or", TokenType.DoubleBar},
{"and", TokenType.DoubleAmphersand},
{"eq", TokenType.DoubleEqual},
{"true", TokenType.KeywordTrue},
{"false", TokenType.KeywordFalse},
{"function", TokenType.KeywordFunction},
{"defun", TokenType.KeywordFunction},
{"lambda", TokenType.KeywordLambda},
{"return", TokenType.KeywordReturn},
{"break", TokenType.KeywordBreak},
{"loop", TokenType.KeywordLoop},
{"import", TokenType.KeywordImport},
{"as", TokenType.KeywordAs},
{"new", TokenType.KeywordNew}
};
private static readonly Dictionary<string, TokenType> Operators = new Dictionary<string, TokenType>
{
{"!", TokenType.Exclamation},
{"!=", TokenType.ExclamationEqual},
{"%", TokenType.Percent},
{"&", TokenType.Amphersand},
{"&&", TokenType.DoubleAmphersand},
{"(", TokenType.OpenParen},
{")", TokenType.CloseParen},
{"*", TokenType.Asterisk},
{"**", TokenType.Caret},
{"+", TokenType.Plus},
{"^", TokenType.Caret},
{"^^", TokenType.DoubleCaret},
{",", TokenType.Comma},
{"-", TokenType.Minus},
{".", TokenType.Dot},
{"/", TokenType.Slash},
{":", TokenType.Colon},
{"~", TokenType.Tilde},
{"<", TokenType.LessThan},
{"<=", TokenType.LessThanOrEqual},
{"<>", TokenType.LessThanOrGreater},
{"<<", TokenType.LeftShift},
{"=", TokenType.Equal},
{"==", TokenType.DoubleEqual},
{">", TokenType.GreaterThan},
{">=", TokenType.GreaterThanOrEqual},
{">>", TokenType.RightShift},
{"?", TokenType.Question},
{";", TokenType.SemiColon},
{"|", TokenType.Bar},
{"||", TokenType.DoubleBar},
{"{", TokenType.KeywordThen},
{"}", TokenType.KeywordEnd},
{"[", TokenType.OpenBracket},
{"]", TokenType.CloseBracket}
};
private static readonly string SingleOps = MakeSingleOps();
private static readonly string PrefixOps = MakePrefixOps();
private static readonly string SuffixOps = MakeSuffixOps();
private readonly PositionalTextReader _reader;
private char _currentChar;
/// <summary>
/// Creates a positional text reader from
/// a TextReader
/// </summary>
/// <param name="text">Text to be read</param>
public Tokenizer(TextReader text)
{
_reader = new PositionalTextReader(text, text.GetType().Name);
NextChar();
}
private int CurrentReaderValue { get; set; }
public bool EndOfFile
{
get { return CurrentReaderValue == -1; }
}
/// <summary>
/// Get the next token from the parse string.
/// </summary>
/// <returns></returns>
public Token NextToken()
{
IgnoreWhiteSpace();
if (IsComment())
{
SkipComment();
return NextToken();
}
if (IsIdentifier())
{
return MakeIdentifier();
}
if (IsNumber())
{
return MakeNumber();
}
if (IsString())
{
return MakeString();
}
if (IsCombinedOperator())
{
return MakeCombinedOperator();
}
if (IsOperator())
{
return MakeOperator();
}
if (CurrentReaderValue == -1)
{
return MakeToken(TokenType.End, "");
}
throw TokenizerException(string.Format("Could not parse character: {0}", _currentChar));
}
private void IgnoreWhiteSpace()
{
while (char.IsWhiteSpace(_currentChar))
NextChar();
}
private bool IsIdentifier()
{
return char.IsLetter(_currentChar) || _currentChar == '@' || _currentChar == '_';
}
private Token MakeIdentifier()
{
var identifierStr = new StringBuilder();
do
{
identifierStr.Append(_currentChar);
NextChar();
} while (Char.IsLetterOrDigit(_currentChar) || _currentChar == '_');
string ident = identifierStr.ToString();
if (Keywords.ContainsKey(ident))
{
return MakeToken(Keywords[ident], ident);
}
return MakeToken(TokenType.Identifier, ident);
}
private bool IsString()
{
return _currentChar == '"' || _currentChar == '\'';
}
private Token MakeString()
{
var str = new StringBuilder();
char quote = _currentChar;
NextChar();
while ((_currentChar != quote) && CurrentReaderValue != -1)
{
str.Append(_currentChar);
NextChar();
}
if (_currentChar != quote)
{
throw TokenizerException("Quoted string was not terminated");
}
NextChar();
return MakeToken(TokenType.StringLiteral, str.ToString());
}
private bool IsNumber()
{
return char.IsNumber(_currentChar);
}
/// <summary>
/// A number is a number.
///
/// Well...
///
/// except when it is an integer.
///
/// or an Int32... or Int64
///
/// Int16?
///
/// Oh - and double. Or a float, which is like a small
/// double? Could be a decimal. BigNum too.
///
/// Don't start with long.
///
/// This is C#, which sounds like C, but it isn't really C at all. So
/// a char is not an int that gets converted to a long. Not sure.
///
/// These are just bytes of data.
///
/// Anyways, we use doubles, which are 64 bit floats.
///
/// And we use Int32, which is a 32 bit integer.
///
/// We used to just use Double, until I tried to do:
///
/// a[0]
///
/// with a Double and you can only use Int(32|64) for an array index.
/// (it would be kind of cool to be able to do a[3.14], but I think that I am
/// the only one who probably thinks that)
///
/// Int32's and Doubles don't convert well. Can't just do an Expression.Convert. .NET
/// complains because .NET is silly sometimes. Or maybe it is the right thing to do,
/// because Anders Hejlsberg is a genius.
/// </summary>
/// <returns>The number.</returns>
private Token MakeNumber()
{
var numberStr = new StringBuilder();
var numberType = TokenType.NumberInteger;
do
{
numberStr.Append(_currentChar);
NextChar();
} while (Char.IsDigit(_currentChar));
if (_currentChar == '.')
{
numberType = TokenType.NumberFloat;
numberStr.Append(_currentChar);
NextChar();
do
{
numberStr.Append(_currentChar);
NextChar();
} while (Char.IsDigit(_currentChar));
}
if (_currentChar == 'E' || _currentChar == 'e')
{
numberType = TokenType.NumberFloat;
numberStr.Append(_currentChar);
NextChar();
if (_currentChar == '+' || _currentChar == '-')
{
numberStr.Append(_currentChar);
NextChar();
}
do
{
numberStr.Append(_currentChar);
NextChar();
} while (Char.IsDigit(_currentChar));
}
if (_currentChar == 'F' || _currentChar == 'f')
{
numberType = TokenType.NumberFloat;
numberStr.Append(_currentChar);
NextChar();
}
return MakeToken(numberType, numberStr.ToString());
}
private bool IsComment()
{
var nextChar = (char)_reader.Peek();
return _currentChar == '/' && nextChar == '/';
}
private void SkipComment()
{
NextChar();
for (; ; )
{
if (_currentChar == '\n' || _currentChar == '\r')
break;
NextChar();
}
NextChar();
}
private bool IsCombinedOperator()
{
return PrefixOps.IndexOf(_currentChar) >= 0 &&
SuffixOps.IndexOf((char)_reader.Peek()) >= 0;
}
private Token MakeCombinedOperator()
{
var str = new StringBuilder();
str.Append(_currentChar);
NextChar();
while (true)
{
if (SuffixOps.IndexOf(_currentChar) < 0)
{
break;
}
str.Append(_currentChar);
NextChar();
}
return MakeToken(Operators[str.ToString()], str.ToString());
}
private bool IsOperator()
{
return SingleOps.IndexOf(_currentChar) >= 0;
}
private Token MakeOperator()
{
Token t = MakeToken(Operators[_currentChar.ToString(CultureInfo.InvariantCulture)],
_currentChar.ToString(CultureInfo.InvariantCulture));
NextChar();
return t;
}
private void NextChar()
{
CurrentReaderValue = _reader.Read();
_currentChar = (char)CurrentReaderValue;
}
public char CurrentChar
{
get { return _currentChar; }
}
private Token MakeToken(TokenType type, string value = null)
{
string tokenValue = value ?? _currentChar.ToString(CultureInfo.InvariantCulture);
return new Token(type, tokenValue, _reader.LineNumber, _reader.ColumnNumber);
}
private TokenizerException TokenizerException(string msg)
{
return new TokenizerException(msg, _reader);
}
private static string MakeSingleOps()
{
var str = new StringBuilder();
foreach (var op in Operators)
{
if (op.Key.Length == 1)
{
str.Append(op.Key);
}
}
return str.ToString();
}
private static string MakePrefixOps()
{
var str = new StringBuilder();
foreach (var op in Operators)
{
if (op.Key.Length == 2)
{
str.Append(op.Key[0]);
}
}
return str.ToString();
}
private static string MakeSuffixOps()
{
var str = new StringBuilder();
foreach (var op in Operators)
{
if (op.Key.Length == 2)
{
str.Append(op.Key[1]);
}
}
return str.ToString();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Summarizes the state of a compute node.
/// </summary>
public partial class ComputeNode : IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<string> AffinityIdProperty;
public readonly PropertyAccessor<DateTime?> AllocationTimeProperty;
public readonly PropertyAccessor<IReadOnlyList<CertificateReference>> CertificateReferencesProperty;
public readonly PropertyAccessor<ComputeNodeEndpointConfiguration> EndpointConfigurationProperty;
public readonly PropertyAccessor<IReadOnlyList<ComputeNodeError>> ErrorsProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<string> IPAddressProperty;
public readonly PropertyAccessor<bool?> IsDedicatedProperty;
public readonly PropertyAccessor<DateTime?> LastBootTimeProperty;
public readonly PropertyAccessor<IReadOnlyList<TaskInformation>> RecentTasksProperty;
public readonly PropertyAccessor<int?> RunningTasksCountProperty;
public readonly PropertyAccessor<Common.SchedulingState?> SchedulingStateProperty;
public readonly PropertyAccessor<StartTask> StartTaskProperty;
public readonly PropertyAccessor<StartTaskInformation> StartTaskInformationProperty;
public readonly PropertyAccessor<Common.ComputeNodeState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<int?> TotalTasksRunProperty;
public readonly PropertyAccessor<int?> TotalTasksSucceededProperty;
public readonly PropertyAccessor<string> UrlProperty;
public readonly PropertyAccessor<string> VirtualMachineSizeProperty;
public PropertyContainer(Models.ComputeNode protocolObject) : base(BindingState.Bound)
{
this.AffinityIdProperty = this.CreatePropertyAccessor(
protocolObject.AffinityId,
nameof(AffinityId),
BindingAccess.Read);
this.AllocationTimeProperty = this.CreatePropertyAccessor(
protocolObject.AllocationTime,
nameof(AllocationTime),
BindingAccess.Read);
this.CertificateReferencesProperty = this.CreatePropertyAccessor(
CertificateReference.ConvertFromProtocolCollectionReadOnly(protocolObject.CertificateReferences),
nameof(CertificateReferences),
BindingAccess.Read);
this.EndpointConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.EndpointConfiguration, o => new ComputeNodeEndpointConfiguration(o).Freeze()),
nameof(EndpointConfiguration),
BindingAccess.Read);
this.ErrorsProperty = this.CreatePropertyAccessor(
ComputeNodeError.ConvertFromProtocolCollectionReadOnly(protocolObject.Errors),
nameof(Errors),
BindingAccess.Read);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
nameof(Id),
BindingAccess.Read);
this.IPAddressProperty = this.CreatePropertyAccessor(
protocolObject.IpAddress,
nameof(IPAddress),
BindingAccess.Read);
this.IsDedicatedProperty = this.CreatePropertyAccessor(
protocolObject.IsDedicated,
nameof(IsDedicated),
BindingAccess.Read);
this.LastBootTimeProperty = this.CreatePropertyAccessor(
protocolObject.LastBootTime,
nameof(LastBootTime),
BindingAccess.Read);
this.RecentTasksProperty = this.CreatePropertyAccessor(
TaskInformation.ConvertFromProtocolCollectionReadOnly(protocolObject.RecentTasks),
nameof(RecentTasks),
BindingAccess.Read);
this.RunningTasksCountProperty = this.CreatePropertyAccessor(
protocolObject.RunningTasksCount,
nameof(RunningTasksCount),
BindingAccess.Read);
this.SchedulingStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.SchedulingState, Common.SchedulingState>(protocolObject.SchedulingState),
nameof(SchedulingState),
BindingAccess.Read);
this.StartTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o).Freeze()),
nameof(StartTask),
BindingAccess.Read);
this.StartTaskInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTaskInfo, o => new StartTaskInformation(o).Freeze()),
nameof(StartTaskInformation),
BindingAccess.Read);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.ComputeNodeState, Common.ComputeNodeState>(protocolObject.State),
nameof(State),
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
nameof(StateTransitionTime),
BindingAccess.Read);
this.TotalTasksRunProperty = this.CreatePropertyAccessor(
protocolObject.TotalTasksRun,
nameof(TotalTasksRun),
BindingAccess.Read);
this.TotalTasksSucceededProperty = this.CreatePropertyAccessor(
protocolObject.TotalTasksSucceeded,
nameof(TotalTasksSucceeded),
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
nameof(Url),
BindingAccess.Read);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor(
protocolObject.VmSize,
nameof(VirtualMachineSize),
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
private readonly string parentPoolId;
internal string ParentPoolId
{
get
{
return this.parentPoolId;
}
}
#region Constructors
internal ComputeNode(
BatchClient parentBatchClient,
string parentPoolId,
Models.ComputeNode protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentPoolId = parentPoolId;
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="ComputeNode"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region ComputeNode
/// <summary>
/// Gets an opaque string that contains information about the location of the compute node.
/// </summary>
public string AffinityId
{
get { return this.propertyContainer.AffinityIdProperty.Value; }
}
/// <summary>
/// Gets the time at which this compute node was allocated to the pool.
/// </summary>
public DateTime? AllocationTime
{
get { return this.propertyContainer.AllocationTimeProperty.Value; }
}
/// <summary>
/// Gets the list of certificates installed on this compute node.
/// </summary>
public IReadOnlyList<CertificateReference> CertificateReferences
{
get { return this.propertyContainer.CertificateReferencesProperty.Value; }
}
/// <summary>
/// Gets the endpoint configuration for the compute node.
/// </summary>
public ComputeNodeEndpointConfiguration EndpointConfiguration
{
get { return this.propertyContainer.EndpointConfigurationProperty.Value; }
}
/// <summary>
/// Gets the list of errors that are currently being encountered by the compute node.
/// </summary>
public IReadOnlyList<ComputeNodeError> Errors
{
get { return this.propertyContainer.ErrorsProperty.Value; }
}
/// <summary>
/// Gets the id of compute node.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
}
/// <summary>
/// Gets the IP address associated with the compute node.
/// </summary>
public string IPAddress
{
get { return this.propertyContainer.IPAddressProperty.Value; }
}
/// <summary>
/// Gets whether this compute node is a dedicated node. If false, the node is a low-priority node.
/// </summary>
public bool? IsDedicated
{
get { return this.propertyContainer.IsDedicatedProperty.Value; }
}
/// <summary>
/// Gets the time at which the compute node was started.
/// </summary>
public DateTime? LastBootTime
{
get { return this.propertyContainer.LastBootTimeProperty.Value; }
}
/// <summary>
/// Gets the execution information for the most recent tasks that ran on this compute node. Note that this element
/// is only returned if at least one task was run on this compute node since the time it was assigned to its current
/// pool.
/// </summary>
public IReadOnlyList<TaskInformation> RecentTasks
{
get { return this.propertyContainer.RecentTasksProperty.Value; }
}
/// <summary>
/// Gets the total number of currently running tasks on the compute node. This includes Job Preparation, Job Release,
/// and Job Manager tasks, but not the pool start task.
/// </summary>
public int? RunningTasksCount
{
get { return this.propertyContainer.RunningTasksCountProperty.Value; }
}
/// <summary>
/// Gets whether the node is available for task scheduling.
/// </summary>
public Common.SchedulingState? SchedulingState
{
get { return this.propertyContainer.SchedulingStateProperty.Value; }
}
/// <summary>
/// Gets the start task associated with all compute nodes in this pool.
/// </summary>
public StartTask StartTask
{
get { return this.propertyContainer.StartTaskProperty.Value; }
}
/// <summary>
/// Gets the detailed runtime information of the start task, including current state, error details, exit code, start
/// time, end time, etc.
/// </summary>
public StartTaskInformation StartTaskInformation
{
get { return this.propertyContainer.StartTaskInformationProperty.Value; }
}
/// <summary>
/// Gets the current state of the compute node.
/// </summary>
public Common.ComputeNodeState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the compute node entered the current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets the number of tasks that have been run on this compute node from the time it was allocated to this pool.
/// This includes Job Preparation, Job Release, and Job Manager tasks, but not the pool start task.
/// </summary>
public int? TotalTasksRun
{
get { return this.propertyContainer.TotalTasksRunProperty.Value; }
}
/// <summary>
/// Gets the total number of tasks which completed successfully (with exitCode 0) on the compute node. This includes
/// Job Preparation, Job Release, and Job Manager tasks, but not the pool start task.
/// </summary>
public int? TotalTasksSucceeded
{
get { return this.propertyContainer.TotalTasksSucceededProperty.Value; }
}
/// <summary>
/// Gets the URL of compute node.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
/// <summary>
/// Gets the size of the virtual machine hosting the compute node.
/// </summary>
public string VirtualMachineSize
{
get { return this.propertyContainer.VirtualMachineSizeProperty.Value; }
}
#endregion // ComputeNode
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace l2pvp
{
public class GameT15Crypter
{
private l2pvp.OpcodeObfuscator.OpcodeTable _table;
/**
*
*/
public GameT15Crypter()
{
}
public void encrypt(byte[] raw)
{
try
{
raw[0] = _table.getObfuscatedOpcode(raw[0]);
}
catch
{
System.Console.WriteLine("Exception in encrypting --- " + raw.ToString());
}
}
public void decrypt(byte[] raw)
{
// bool decrypt = super.decrypt(raw, dir);
// Crypt Key (once) or CharacterSelected (multiple possible)
// search after decryption due to CharacterSelected
//if (dir == packetDirection.serverPacket)
//{
// this.searchObfuscationKey(raw, dir);
//}
//else if (dir == packetDirection.clientPacket && _table != null)
//{
//byte old = raw[0];
try
{
raw[0] = _table.getOriginalOpcode(raw[0]);
if ((raw[0] & 0xFF) == 0xd0)
{
short exOpcode = _table.getExOpcode(raw[1] + (raw[2] << 8));
raw[1] = (byte)(exOpcode & 0xFF);
raw[2] = (byte)((exOpcode >> 8) & 0xFF);
}
//byte newop = _table.getObfuscatedOpcode(raw[0]);
//System.Console.WriteLine("Opcodes = {0} -- {1} -- {2}", old, raw[0], newop);
return;
}
catch
{
System.Console.WriteLine("Exception in decrypting --- " + raw.ToString());
}
}
// private boolean searchObfuscationKey(byte[] raw, packetDirection dir)
//{
// byte[] temp = new byte[raw.length];
// System.arraycopy(raw, 0, temp, 0, raw.length);
// DataPacket packet = new DataPacket(temp, dir, 0, this.getProtocol());
// if (dir == packetDirection.serverPacket && ("Crypt Key".equals(packet.getName()) || "CharacterSelected".equals(packet.getName())))
// {
// ValuePart part = (ValuePart) packet.getRootNode().getPartByName("obfuscation key");
// if(part == null)
// {
// System.out.printf("Check your protocol there is no part called 'obfuscation key' which is required in packet 0x00 of the GS protocol.");
// return false;
// }
// if (part instanceof IntValuePart)
// {
// int key = ((IntValuePart)part).getIntValue();
// System.out.printf("Obfuscation Key is: "+key+" -> %08X\n",key);
// this.generateOpcodeTable(key);
// }
// else
// {
// System.out.printf("On the GS protocol 'Obfuscation Key' should be of type 'd'.");
// return false;
// }
// return true;
// }
// //System.out.println("No key found...");
// return false;
//}
public void generateOpcodeTable(int key)
{
if (key == 0)
{
byte[] opcodes = new byte[0xd1]; // d0 + 1
for (int i = 0; i < opcodes.Length; i++)
{
opcodes[i] = (byte)i;
}
short[] exOpcodes = new short[0x4e];
for (int i = 0; i < exOpcodes.Length; i++)
{
exOpcodes[i] = (byte)i;
}
}
else
{
_table = OpcodeObfuscator.getObfuscatedTable(key);
}
}
}
public class OpcodeObfuscator
{
// static usage
private OpcodeObfuscator()
{
}
private static short[] shuffleEx(int key)
{
//System.err.printf("EX KEY: %08X\n" , key);
short[] array = new short[0x4e];
for (int i = 0; i < array.Length; i++)
{
array[i] = (byte)i;
}
int edx = 0;
int ecx = 2;
short tmp2;
short opcode;
int edi = 1;
int subKey;
int j = 0;
do
{
//MOVZX EAX,AX
key = rotateKey(key);
subKey = key >> 16;
subKey &= 0x7FFF;
//System.err.printf("SubKey1: %04X\n" , subKey);
// CDQ
edx = 0;
// IDIV ECX
//edxeax = (edx << 32) + eax;
//eax = (int) (edxeax / ecx);
edx = subKey % ecx++;
//System.err.printf("SubKey2: %04X - EDX: %04X\n" , subKey, edx);
// INC EDI
edi++;
// SKIPPED: DEC EBX
// SKIPPED: MOVZX EDX,DL
// MOV CL,BYTE PTR DS:[EDX+ESI+4174]
opcode = array[edx];
// MOV DL,BYTE PTR DS:[EDI-1]
tmp2 = array[edi - 1];
// MOV BYTE PTR DS:[EAX],DL
array[edx] = (byte)tmp2;
// MOV BYTE PTR DS:[EDI-1],CL
array[edi - 1] = (byte)opcode;
}
while (++j < 0x4d);
/*for (int i = 0; i < array.length; i++)
{
System.err.printf("array[%04X] = %04X\n", i, array[i]);
}*/
return array;
}
//private static int STORED_KEY = 0x73BD7EF4;//0x63E790F1;
private static int rotateKey(int key)
{
key *= 0x343FD;
key += 0x269EC3;
return key;
}
public static OpcodeTable getObfuscatedTable(int key)
{
byte[] array = new byte[0xd1];
for (int i = 0; i < array.Length; i++)
{
array[i] = (byte)i;
}
byte tmp;
byte opcode;
int edx = 0;
int ecx = 2;
int edi = 1;
int subKey;
int j = 0;
do
{
//MOVZX EAX,AX
key = rotateKey(key);
subKey = key >> 16;
subKey &= 0x7FFF;
//System.err.printf("SubKey1: %04X\n" , eax);
// CDQ
edx = 0;
// IDIV ECX
//edxeax = (edx << 32) + eax;
//eax = (int) (edxeax / ecx);
edx = subKey % ecx++;
//System.err.printf("SubKey2: %04X - EDX: %04X\n" , eax, edx);
// INC EDI
edi++;
// SKIPPED: DEC EBX (ZF enabler)
// SKIPPED: MOVZX EDX,DL
// MOV CL,BYTE PTR DS:[EDX+ESI+4174]
opcode = array[edx];
// MOV DL,BYTE PTR DS:[EDI-1]
tmp = array[edi - 1];
// MOV BYTE PTR DS:[EAX],DL
array[edx] = tmp;
// MOV BYTE PTR DS:[EDI-1],CL
array[edi - 1] = opcode;
}
while (++j < 0xd0);
OpcodeObfuscator.revertOpcodeToOriginal(array, (byte)0x12);
OpcodeObfuscator.revertOpcodeToOriginal(array, (byte)0xb1);
/*for (int i = 0; i < array.length; i++)
{
System.err.printf("array[%02X] = %02X\n", i, array[i]);
}*/
short[] exOpcodes = OpcodeObfuscator.shuffleEx(key);
return new OpcodeTable(array, exOpcodes);
}
private static void revertOpcodeToOriginal(byte[] array, byte opcode)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] == opcode)
{
array[i] = array[opcode & 0xFF];
array[opcode & 0xFF] = opcode;
return;
}
}
}
public class OpcodeTable
{
private byte[] _opcodeTable;
private short[] _exOpcodeTable;
private byte[] _reverselookup;
//private short[] _reverseEx;
public OpcodeTable(byte[] opcodeTable, short[] exOpcodeTable)
{
_opcodeTable = opcodeTable;
/*for (int i = 0; i < opcodeTable.length; i++)
{
System.out.printf("[%02X] = %02X \n", i, (opcodeTable[i] & 0xff));
}*/
_exOpcodeTable = exOpcodeTable;
/*for (int i = 0; i < exOpcodeTable.length; i++)
{
System.out.printf("[%04X] = %04X \n", i, (exOpcodeTable[i] & 0xff));
}*/
_reverselookup = new byte[opcodeTable.Length];
for (int i = 0; i < opcodeTable.Length; i++)
{
_reverselookup[opcodeTable[i & 0xFF]] = (byte)(i & 0xff);
}
}
public byte getOriginalOpcode(int obfuscatedOpcode)
{
return _opcodeTable[obfuscatedOpcode & 0xFF];
}
public short getExOpcode(int obfuscatedOpcode)
{
return _exOpcodeTable[obfuscatedOpcode & 0xFFFF];
}
public byte getObfuscatedOpcode(int opcode)
{
return _reverselookup[opcode & 0xFF];
}
}
}
public class OldCrypt
{
// Fields
private byte[] _key;
private bool enabled;
public OldCrypt()
{
this._key = new byte[8];
}
public void decrypt(byte[] raw)
{
if (this.enabled)
{
uint num1 = 0;
for (int num2 = 0; num2 < raw.Length; num2++)
{
uint num3 = (uint)(raw[num2] & 0xff);
raw[num2] = (byte)((num3 ^ (this._key[num2 & 7] & 0xff)) ^ num1);
num1 = num3;
}
ulong num4 = (ulong)(this._key[0] & 0xff);
num4 |= (ulong)(this._key[1] << 8) & 0xff00;
num4 |= (ulong)(this._key[2] << 0x10) & 0xff0000;
num4 |= (ulong)(this._key[3] << 0x18) & 0xff000000;
num4 += (ulong)raw.Length;
this._key[0] = (byte)(num4 & 0xff);
this._key[1] = (byte)((num4 >> 8) & 0xff);
this._key[2] = (byte)((num4 >> 0x10) & 0xff);
this._key[3] = (byte)((num4 >> 0x18) & 0xff);
}
}
public void decrypt(byte[] raw, ulong size)
{
if (this.enabled)
{
uint num1 = 0;
for (uint num2 = 0; num2 < size; num2 += 1)
{
uint num3 = (uint)(raw[(int)((IntPtr)num2)] & 0xff);
raw[(int)((IntPtr)num2)] = (byte)((num3 ^ (this._key[(int)((IntPtr)(num2 & 7))] & 0xff)) ^ num1);
num1 = num3;
}
ulong num4 = (ulong)(this._key[0] & 0xff);
num4 |= (ulong)(this._key[1] << 8) & 0xff00;
num4 |= (ulong)(this._key[2] << 0x10) & 0xff0000;
num4 |= (ulong)(this._key[3] << 0x18) & 0xff000000;
num4 += (ulong)size;
this._key[0] = (byte)(num4 & 0xff);
this._key[1] = (byte)((num4 >> 8) & 0xff);
this._key[2] = (byte)((num4 >> 0x10) & 0xff);
this._key[3] = (byte)((num4 >> 0x18) & 0xff);
this.Write_Key();
}
}
public void encrypt(byte[] raw)
{
if (this.enabled)
{
uint num1 = 0;
for (int num2 = 0; num2 < raw.Length; num2++)
{
uint num3 = (uint)(raw[num2] & 0xff);
raw[num2] = (byte)((num3 ^ (this._key[num2 & 7] & 0xff)) ^ num1);
num1 = raw[num2];
}
ulong num4 = (ulong)(this._key[0] & 0xff);
num4 |= (ulong)(this._key[1] << 8) & 0xff00;
num4 |= (ulong)(this._key[2] << 0x10) & 0xff0000;
num4 |= (ulong)(this._key[3] << 0x18) & 0xff000000;
num4 += (ulong)raw.Length;
this._key[0] = (byte)(num4 & 0xff);
this._key[1] = (byte)((num4 >> 8) & 0xff);
this._key[2] = (byte)((num4 >> 0x10) & 0xff);
this._key[3] = (byte)((num4 >> 0x18) & 0xff);
}
}
public void encrypt(byte[] raw, ulong size)
{
if (this.enabled)
{
uint num1 = 0;
for (uint num2 = 0; num2 < size; num2 += 1)
{
uint num3 = (uint)(raw[(int)((IntPtr)num2)] & 0xff);
raw[(int)((IntPtr)num2)] = (byte)((num3 ^ (this._key[(int)((IntPtr)(num2 & 7))] & 0xff)) ^ num1);
num1 = raw[(int)((IntPtr)num2)];
}
ulong num4 = (ulong)(this._key[0] & 0xff);
num4 |= (ulong)(this._key[1] << 8) & 0xff00;
num4 |= (ulong)(this._key[2] << 0x10) & 0xff0000;
num4 |= (ulong)(this._key[3] << 0x18) & 0xff000000;
num4 += (ulong)size;
this._key[0] = (byte)(num4 & 0xff);
this._key[1] = (byte)((num4 >> 8) & 0xff);
this._key[2] = (byte)((num4 >> 0x10) & 0xff);
this._key[3] = (byte)((num4 >> 0x18) & 0xff);
}
}
public void setKey(byte[] key)
{
this._key[0] = key[0];
this._key[1] = key[1];
this._key[2] = key[2];
this._key[3] = key[3];
this._key[4] = key[4];
this._key[5] = key[5];
this._key[6] = key[6];
this._key[7] = key[7];
this.enabled = true;
}
private void Write_Key()
{
}
}
public class Crypt
{
private byte[] _inKey;
private byte[] _outKey;
//byte[] _idTable = null;
//short[] _exIdTable = null;
public Crypt()
{
_inKey = new byte[16];
_outKey = new byte[16];
//_idTable = new byte[208];
//_exIdTable = new short[76];
//for (int i = 0; i < _idTable.Length; i++)
// _idTable[i] = Convert.ToByte(i);
//for (int i = 0; i < _exIdTable.Length; i++)
// _exIdTable[i] = Convert.ToInt16(i);
}
public void setKey(byte[] key)
{
Array.Copy(key, 0, _inKey, 0, 16);
Array.Copy(key, 0, _outKey, 0, 16);
}
public void decrypt(byte[] raw)
{
decrypt(raw, 0, raw.Length);
}
public void decrypt(byte[] raw, int offset, int size)
{
int temp = 0;
for (int i = 0; i < size; i++)
{
int temp2 = raw[offset + i] & 0xFF;
raw[offset + i] = (byte)(temp2 ^ _inKey[i & 15] ^ temp);
temp = temp2;
}
ulong old = (ulong)_inKey[8] & 0xff;
old |= (ulong)_inKey[9] << 8 & 0xff00;
old |= (ulong)_inKey[10] << 0x10 & 0xff0000;
old |= (ulong)_inKey[11] << 0x18 & 0xff000000;
old += (ulong)size;
_inKey[8] = (byte)(old & 0xff);
_inKey[9] = (byte)(old >> 0x08 & 0xff);
_inKey[10] = (byte)(old >> 0x10 & 0xff);
_inKey[11] = (byte)(old >> 0x18 & 0xff);
}
public void encrypt(byte[] raw)
{
encrypt(raw, 0, raw.Length);
}
public void encrypt(byte[] raw, int offset, int size)
{
int temp = 0;
for (int i = 0; i < size; i++)
{
int temp2 = raw[offset + i] & 0xFF;
temp = temp2 ^ _outKey[i & 15] ^ temp;
raw[offset + i] = (byte)temp;
}
ulong old = (ulong)_outKey[8] & 0xff;
old |= (ulong)_outKey[9] << 8 & 0xff00;
old |= (ulong)_outKey[10] << 0x10 & 0xff0000;
old |= (ulong)_outKey[11] << 0x18 & 0xff000000;
old += (ulong)size;
_outKey[8] = (byte)(old & 0xff);
_outKey[9] = (byte)(old >> 0x08 & 0xff);
_outKey[10] = (byte)(old >> 0x10 & 0xff);
_outKey[11] = (byte)(old >> 0x18 & 0xff);
}
}
}
| |
using Signum.Engine.Maps;
using Signum.Engine.DynamicQuery;
using Signum.Entities.Basics;
using Signum.Utilities.Reflection;
namespace Signum.Engine.Basics;
public static class ExceptionLogic
{
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
sb.Include<ExceptionEntity>()
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.CreationDate,
e.ExceptionType,
e.ExceptionMessage,
e.StackTraceHash,
});
DefaultEnvironment = "Default";
}
}
public static ExceptionEntity LogException(this Exception ex, Action<ExceptionEntity> completeContext)
{
var entity = GetEntity(ex);
completeContext(entity);
return entity.SaveForceNew();
}
public static ExceptionEntity LogException(this Exception ex)
{
var entity = GetEntity(ex);
return entity.SaveForceNew();
}
public static ExceptionEntity? GetExceptionEntity(this Exception ex)
{
var exEntity = ex.Data[ExceptionEntity.ExceptionDataKey] as ExceptionEntity;
return exEntity;
}
static ExceptionEntity GetEntity(Exception ex)
{
ExceptionEntity entity = ex.GetExceptionEntity() ?? new ExceptionEntity(ex);
entity.ExceptionType = ex.GetType().Name;
var exceptions = ex is AggregateException agex ?
agex.InnerExceptions.SelectMany(inner => inner.Follow(e => e.InnerException)).ToList() :
ex.Follow(e => e.InnerException).ToList();
string messages = exceptions.ToString(e => e.Message, "\r\n\r\n");
string stacktraces = exceptions.ToString(e => e.StackTrace, "\r\n\r\n");
entity.ExceptionMessage = messages.DefaultText("- No message - ");
entity.StackTrace = new BigStringEmbedded(stacktraces.DefaultText("- No stacktrace -"));
entity.ThreadId = Thread.CurrentThread.ManagedThreadId;
entity.ApplicationName = Schema.Current.ApplicationName;
entity.HResult = ex.HResult;
entity.Form = new BigStringEmbedded();
entity.QueryString = new BigStringEmbedded();
entity.Session = new BigStringEmbedded();
entity.Environment = CurrentEnvironment;
try
{
entity.User = UserHolder.Current?.ToLite(); //Session special situations
}
catch { }
try
{
entity.Data = new BigStringEmbedded(ex.Data.Dump());
}
catch (Exception e)
{
entity.Data = new BigStringEmbedded($@"Error Dumping Data!{e.GetType().Name}: {e.Message}{e.StackTrace}");
}
entity.Version = Schema.Current.Version.ToString();
return entity;
}
static ExceptionEntity SaveForceNew(this ExceptionEntity entity)
{
if (entity.Modified == ModifiedState.Clean)
return entity;
using (ExecutionMode.Global())
using (var tr = Transaction.ForceNew())
{
entity.Save();
return tr.Commit(entity);
}
}
public static string? DefaultEnvironment { get; set; }
public static string? CurrentEnvironment { get { return overridenEnvironment.Value ?? DefaultEnvironment; } }
static readonly Variable<string?> overridenEnvironment = Statics.ThreadVariable<string?>("exceptionEnviroment");
public static IDisposable OverrideEnviroment(string? newEnviroment)
{
string? oldEnviroment = overridenEnvironment.Value;
overridenEnvironment.Value = newEnviroment;
return new Disposable(() => overridenEnvironment.Value = oldEnviroment);
}
public static event Action<DeleteLogParametersEmbedded, StringBuilder, CancellationToken>? DeleteLogs;
public static int DeleteLogsTimeOut = 10 * 60 * 1000;
public static void DeleteLogsAndExceptions(DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken token)
{
using (Connector.CommandTimeoutScope(DeleteLogsTimeOut))
using (var tr = Transaction.None())
{
foreach (var action in DeleteLogs.GetInvocationListTyped())
{
token.ThrowIfCancellationRequested();
action(parameters, sb, token);
}
WriteRows(sb, "Updating ExceptionEntity.Referenced = false", () => Database.Query<ExceptionEntity>().UnsafeUpdate().Set(a => a.Referenced, a => false).Execute());
token.ThrowIfCancellationRequested();
var ex = Schema.Current.Table<ExceptionEntity>();
var referenced = (FieldValue)ex.GetField(ReflectionTools.GetPropertyInfo((ExceptionEntity e) => e.Referenced));
var commands = (from t in Schema.Current.GetDatabaseTables()
from c in t.Columns.Values
where c.ReferenceTable == ex
select (table: t, command: new SqlPreCommandSimple("UPDATE ex SET {1} = 1 FROM {0} ex JOIN {2} log ON ex.Id = log.{3}"
.FormatWith(ex.Name, referenced.Name, t.Name, c.Name)))).ToList();
foreach (var (table, command) in commands)
{
token.ThrowIfCancellationRequested();
WriteRows(sb, "Updating Exceptions.Referenced from " + table.Name.Name, () => command.ExecuteNonQuery());
}
token.ThrowIfCancellationRequested();
var dateLimit = parameters.GetDateLimitDelete(typeof(ExceptionEntity).ToTypeEntity());
if (dateLimit != null)
{
Database.Query<ExceptionEntity>()
.Where(a => !a.Referenced && a.CreationDate < dateLimit)
.UnsafeDeleteChunksLog(parameters, sb, token);
}
tr.Commit();
}
}
public static void WriteRows(StringBuilder sb, string text, Func<int> makeQuery)
{
var start = PerfCounter.Ticks;
var result = makeQuery();
var end = PerfCounter.Ticks;
var ts = TimeSpan.FromMilliseconds(PerfCounter.ToMilliseconds(start, end));
sb.AppendLine($"{text}: {result} rows affected in {ts.NiceToString()}");
}
public static void UnsafeDeleteChunksLog<T>(this IQueryable<T> sources, DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken cancellationToken)
where T : Entity
{
WriteRows(sb, "Deleting " + typeof(T).Name, () => sources.UnsafeDeleteChunks(
parameters.ChunkSize,
parameters.MaxChunks,
pauseMilliseconds: parameters.PauseTime,
cancellationToken: cancellationToken));
}
public static void ExecuteChunksLog<T>(this IUpdateable<T> sources, DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken cancellationToken)
where T : Entity
{
WriteRows(sb, "Updating " + typeof(T).Name, () => sources.ExecuteChunks(
parameters.ChunkSize,
parameters.MaxChunks,
pauseMilliseconds: parameters.PauseTime,
cancellationToken: cancellationToken));
}
}
| |
namespace YAMP
{
using System;
using System.Collections.Generic;
using System.Linq;
using YAMP.Exceptions;
/// <summary>
/// Represents the context that is used for the current input query.
/// </summary>
public class QueryContext
{
#region Fields
readonly ParseEngine _parser;
readonly Dictionary<String, IFunction> _functionBuffer;
readonly ParseContext _context;
readonly String _input;
Boolean _stop;
Statement _current;
#endregion
#region ctor
/// <summary>
/// Creates a new query context.
/// </summary>
/// <param name="context">The context to reference.</param>
/// <param name="input">The input to parse</param>
public QueryContext(ParseContext context, String input)
: this(context)
{
_input = input;
_parser = new ParseEngine(this, context);
_functionBuffer = new Dictionary<String, IFunction>();
}
/// <summary>
/// Creates a new (underlying) QueryContext
/// </summary>
/// <param name="query">The query context to copy</param>
/// <param name="input">The new input to use.</param>
internal QueryContext(QueryContext query, String input)
: this(query._context, input)
{
Parent = query;
_parser.Parent = query.Parser;
}
/// <summary>
/// Just a stupid dummy!
/// </summary>
private QueryContext(ParseContext context)
{
_context = context;
}
#endregion
#region Properties
/// <summary>
/// Gets the parent of this query context.
/// </summary>
public QueryContext Parent
{
get;
private set;
}
/// <summary>
/// Gets the result in a string representation.
/// </summary>
public String Result
{
get { return Output != null ? Output.ToString(Context) : String.Empty; }
}
/// <summary>
/// Gets or sets the input that is being used by the parser.
/// </summary>
public String Input
{
get { return _input; }
}
/// <summary>
/// Gets a boolean indicating whether the result should be printed.
/// </summary>
public Boolean IsMuted
{
get { return Output == null; }
}
/// <summary>
/// Gets the result of the query.
/// </summary>
public Value Output
{
get;
internal set;
}
/// <summary>
/// Gets the context used for this query.
/// </summary>
public ParseContext Context
{
get { return _context; }
}
/// <summary>
/// Gets the statements generated for this query.
/// </summary>
public IEnumerable<Statement> Statements
{
get { return _parser.Statements; }
}
/// <summary>
/// Gets the currently executed statement.
/// </summary>
public Statement CurrentStatement
{
get { return _current; }
}
/// <summary>
/// Gets the parser for this query.
/// </summary>
public ParseEngine Parser
{
get { return _parser; }
}
/// <summary>
/// Gets the used (global) variables.
/// </summary>
public IEnumerable<VariableInfo> Variables
{
get
{
var variables = new List<VariableInfo>();
foreach (var statement in _parser.Statements)
{
var container = statement.Container;
var symbols = container.GetGlobalSymbols();
foreach (var symbol in symbols)
{
var name = symbol.SymbolName;
var context = symbol.Context.GetSymbolContext(name);
if (!variables.Any(m => m.Context == context && m.Name.Equals(name)))
{
var assigned = statement.IsAssignment && container.IsAssigned(symbol);
var variable = new VariableInfo(name, assigned, context);
variables.Add(variable);
}
}
}
return variables;
}
}
#endregion
#region Methods
internal IFunction GetFromBuffer(String functionName)
{
if (_functionBuffer.ContainsKey(functionName))
{
return _functionBuffer[functionName];
}
return null;
}
internal void SetToBuffer(String functionName, IFunction function)
{
_functionBuffer[functionName] = function;
}
/// <summary>
/// Begins the interpretation of the current parse tree.
/// </summary>
/// <param name="values">A dictionary with additional symbols to consider.</param>
public void Run(Dictionary<String, Value> values)
{
if (!_parser.CanRun)
{
if (!_parser.IsParsed)
{
_parser.Parse();
}
if (_parser.HasErrors)
{
throw new YAMPParseException(_parser);
}
}
_current = null;
_stop = false;
foreach (var statement in _parser.Statements)
{
if (_stop)
{
break;
}
_current = statement;
Output = statement.Interpret(values);
}
if (_current != null && Output != null)
{
if (!_current.IsAssignment)
{
if (Output is ArgumentsValue)
{
Output = ((ArgumentsValue)Output).First();
}
Context.AssignVariable(_context.Answer, Output);
}
}
}
/// <summary>
/// Stops the current interpretation.
/// </summary>
internal void Stop()
{
_stop = true;
}
#endregion
#region String Representation
/// <summary>
/// Outputs the string representation of the query context.
/// </summary>
/// <returns>A string variable.</returns>
public override String ToString()
{
return String.Format("{0} = {1}{2}", Input, Environment.NewLine, Output);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Windows.Forms;
using C1.Win.C1Input;
using C1.Win.C1Preview;
using C1.C1Report;
using PCSComProcurement.Purchase.BO;
using PCSComProcurement.Purchase.DS;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;
using PCSComUtils.MasterSetup.DS;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
using PCSUtils.Framework.ReportFrame;
namespace PCSProcurement.Purchase
{
/// <summary>
/// Summary description for PODeliverySlip.
/// </summary>
public class PODeliverySlip : System.Windows.Forms.Form
{
#region controls
private Panel pnlControls;
private Button btnClose;
private Button btnHelp;
private Button btnView;
private C1DateEdit dtmToDateTime;
private C1DateEdit dtmFromDateTime;
private Label lblToDateTime;
private Label lblFromDateTime;
private RadioButton radPeriod;
private RadioButton radAll;
private ToolBarButton c1pBtnClose;
#endregion
private const string THIS = "PCSProcurement.Purchase.PODeliverySlip";
private C1.C1Report.C1Report rptDeliverySlip;
private C1.C1Report.C1Report rptOverDeliverySlip;
private C1.C1Report.C1Report rptPrintable;
private C1.C1Report.C1Report rptOverPrintable;
private C1.C1Report.C1Report rptPrintableReceive;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private PO_PurchaseOrderMasterVO voPOMaster;
private string strReportFilePath = null;
private string strPrintFilePath = null;
private const string RECEIVE_SLIP = "ReceiveSlip";
private const string mstrReportFileName = "DeliverySlip.xml";
private const string mstrViewFileName = "DeliverySlipView.xml";
private const string SCHEDULE_HOUR_FLD = "ScheduleHour";
private const string SHORT_TIME_FORMAT = "HH:mm";
private const string COMPANY_FLD = "fldCompany";
private const string ADDRESS_FLD = "fldAddress";
private const string TEL_FLD = "fldTel";
private const string FAX_FLD = "fldFax";
private const string SLIP_NO_FLD = "fldSlipNo";
private const string SEPERATOR = "-";
private const string DATE_FORMAT = "yyyyMMddHH";
private const string PONO_FLD = "fldPoNo";
private const string ISSUE_DATE_FLD = "fldIssueDate";
private const string ISSUEHOUR_FLD = "fldIssueHour";
private const string CUST_CODE_FLD = "fldCustCode";
private const string CUST_NAME_FLD = "fldCustName";
private const string CCN_CODE_FLD = "fldCCNCode";
private const string CCN_NAME_FLD = "fldCCNName";
private const string SUB_REPORT_FLD = "subReceiveSlip";
private const string TITLE_FLD = "fldTitle";
private const string COPIED_FLD = "fldCopied";
private const string TITLE_VN_FLD = "fldTitleVN";
private const int MAX_LINE_PER_SLIP = 10;
private C1PrintPreviewControl ppvSlip;
private const string TABLE_NAME = "Delivery Slip";
public PODeliverySlip(object pobjPOMaster)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
voPOMaster = (PO_PurchaseOrderMasterVO)pobjPOMaster;
}
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PODeliverySlip));
this.c1pBtnClose = new System.Windows.Forms.ToolBarButton();
this.pnlControls = new System.Windows.Forms.Panel();
this.btnClose = new System.Windows.Forms.Button();
this.btnHelp = new System.Windows.Forms.Button();
this.btnView = new System.Windows.Forms.Button();
this.dtmToDateTime = new C1.Win.C1Input.C1DateEdit();
this.dtmFromDateTime = new C1.Win.C1Input.C1DateEdit();
this.lblToDateTime = new System.Windows.Forms.Label();
this.lblFromDateTime = new System.Windows.Forms.Label();
this.radPeriod = new System.Windows.Forms.RadioButton();
this.radAll = new System.Windows.Forms.RadioButton();
this.rptDeliverySlip = new C1.C1Report.C1Report();
this.rptPrintable = new C1.C1Report.C1Report();
this.rptPrintableReceive = new C1.C1Report.C1Report();
this.ppvSlip = new C1.Win.C1Preview.C1PrintPreviewControl();
this.pnlControls.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dtmToDateTime)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dtmFromDateTime)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rptDeliverySlip)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rptPrintable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rptPrintableReceive)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ppvSlip)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ppvSlip.PreviewPane)).BeginInit();
this.ppvSlip.SuspendLayout();
this.SuspendLayout();
//
// c1pBtnClose
//
resources.ApplyResources(this.c1pBtnClose, "c1pBtnClose");
this.c1pBtnClose.Name = "c1pBtnClose";
//
// pnlControls
//
this.pnlControls.Controls.Add(this.btnClose);
this.pnlControls.Controls.Add(this.btnHelp);
this.pnlControls.Controls.Add(this.btnView);
this.pnlControls.Controls.Add(this.dtmToDateTime);
this.pnlControls.Controls.Add(this.dtmFromDateTime);
this.pnlControls.Controls.Add(this.lblToDateTime);
this.pnlControls.Controls.Add(this.lblFromDateTime);
this.pnlControls.Controls.Add(this.radPeriod);
this.pnlControls.Controls.Add(this.radAll);
resources.ApplyResources(this.pnlControls, "pnlControls");
this.pnlControls.Name = "pnlControls";
//
// btnClose
//
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnClose, "btnClose");
this.btnClose.Name = "btnClose";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// btnHelp
//
resources.ApplyResources(this.btnHelp, "btnHelp");
this.btnHelp.Name = "btnHelp";
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// btnView
//
resources.ApplyResources(this.btnView, "btnView");
this.btnView.Name = "btnView";
this.btnView.Click += new System.EventHandler(this.btnView_Click);
//
// dtmToDateTime
//
//
//
//
this.dtmToDateTime.Calendar.DayNameLength = 1;
this.dtmToDateTime.Calendar.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("dtmToDateTime.Calendar.ImeMode")));
this.dtmToDateTime.Calendar.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("dtmToDateTime.Calendar.RightToLeft")));
this.dtmToDateTime.DisplayFormat.Inherit = ((C1.Win.C1Input.FormatInfoInheritFlags)(resources.GetObject("dtmToDateTime.DisplayFormat.Inherit")));
this.dtmToDateTime.EditFormat.Inherit = ((C1.Win.C1Input.FormatInfoInheritFlags)(resources.GetObject("dtmToDateTime.EditFormat.Inherit")));
resources.ApplyResources(this.dtmToDateTime, "dtmToDateTime");
this.dtmToDateTime.Name = "dtmToDateTime";
this.dtmToDateTime.ParseInfo.Inherit = ((C1.Win.C1Input.ParseInfoInheritFlags)(resources.GetObject("dtmToDateTime.ParseInfo.Inherit")));
this.dtmToDateTime.PreValidation.Inherit = ((C1.Win.C1Input.PreValidationInheritFlags)(resources.GetObject("dtmToDateTime.PreValidation.Inherit")));
this.dtmToDateTime.Tag = null;
//
// dtmFromDateTime
//
//
//
//
this.dtmFromDateTime.Calendar.DayNameLength = 1;
this.dtmFromDateTime.Calendar.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("dtmFromDateTime.Calendar.ImeMode")));
this.dtmFromDateTime.Calendar.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("dtmFromDateTime.Calendar.RightToLeft")));
this.dtmFromDateTime.DisplayFormat.Inherit = ((C1.Win.C1Input.FormatInfoInheritFlags)(resources.GetObject("dtmFromDateTime.DisplayFormat.Inherit")));
this.dtmFromDateTime.EditFormat.Inherit = ((C1.Win.C1Input.FormatInfoInheritFlags)(resources.GetObject("dtmFromDateTime.EditFormat.Inherit")));
resources.ApplyResources(this.dtmFromDateTime, "dtmFromDateTime");
this.dtmFromDateTime.Name = "dtmFromDateTime";
this.dtmFromDateTime.ParseInfo.Inherit = ((C1.Win.C1Input.ParseInfoInheritFlags)(resources.GetObject("dtmFromDateTime.ParseInfo.Inherit")));
this.dtmFromDateTime.PreValidation.Inherit = ((C1.Win.C1Input.PreValidationInheritFlags)(resources.GetObject("dtmFromDateTime.PreValidation.Inherit")));
this.dtmFromDateTime.Tag = null;
//
// lblToDateTime
//
this.lblToDateTime.ForeColor = System.Drawing.Color.Maroon;
resources.ApplyResources(this.lblToDateTime, "lblToDateTime");
this.lblToDateTime.Name = "lblToDateTime";
//
// lblFromDateTime
//
this.lblFromDateTime.ForeColor = System.Drawing.Color.Maroon;
resources.ApplyResources(this.lblFromDateTime, "lblFromDateTime");
this.lblFromDateTime.Name = "lblFromDateTime";
//
// radPeriod
//
resources.ApplyResources(this.radPeriod, "radPeriod");
this.radPeriod.Name = "radPeriod";
this.radPeriod.CheckedChanged += new System.EventHandler(this.radPeriod_CheckedChanged);
//
// radAll
//
this.radAll.Checked = true;
resources.ApplyResources(this.radAll, "radAll");
this.radAll.Name = "radAll";
this.radAll.TabStop = true;
this.radAll.CheckedChanged += new System.EventHandler(this.radAll_CheckedChanged);
//
// rptDeliverySlip
//
this.rptDeliverySlip.ReportDefinition = resources.GetString("rptDeliverySlip.ReportDefinition");
this.rptDeliverySlip.ReportName = "Deliver Slip";
//
// rptPrintable
//
this.rptPrintable.ReportDefinition = resources.GetString("rptPrintable.ReportDefinition");
this.rptPrintable.ReportName = "Delivery Slip";
//
// rptPrintableReceive
//
this.rptPrintableReceive.ReportDefinition = resources.GetString("rptPrintableReceive.ReportDefinition");
this.rptPrintableReceive.ReportName = "Receive Slip";
//
// ppvSlip
//
resources.ApplyResources(this.ppvSlip, "ppvSlip");
this.ppvSlip.Name = "ppvSlip";
//
// ppvSlip.OutlineView
//
resources.ApplyResources(this.ppvSlip.PreviewOutlineView, "ppvSlip.OutlineView");
this.ppvSlip.PreviewOutlineView.Name = "OutlineView";
//
// ppvSlip.PreviewPane
//
this.ppvSlip.PreviewPane.IntegrateExternalTools = true;
resources.ApplyResources(this.ppvSlip.PreviewPane, "ppvSlip.PreviewPane");
//
// ppvSlip.PreviewTextSearchPanel
//
resources.ApplyResources(this.ppvSlip.PreviewTextSearchPanel, "ppvSlip.PreviewTextSearchPanel");
this.ppvSlip.PreviewTextSearchPanel.MinimumSize = new System.Drawing.Size(200, 240);
this.ppvSlip.PreviewTextSearchPanel.Name = "PreviewTextSearchPanel";
//
// ppvSlip.ThumbnailView
//
resources.ApplyResources(this.ppvSlip.PreviewThumbnailView, "ppvSlip.ThumbnailView");
this.ppvSlip.PreviewThumbnailView.Name = "ThumbnailView";
this.ppvSlip.PreviewThumbnailView.UseImageAsThumbnail = false;
//
// PODeliverySlip
//
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnClose;
this.Controls.Add(this.pnlControls);
this.Controls.Add(this.ppvSlip);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "PODeliverySlip";
this.Load += new System.EventHandler(this.PODeliverySlipReport_Load);
this.pnlControls.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dtmToDateTime)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dtmFromDateTime)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rptDeliverySlip)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rptPrintable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rptPrintableReceive)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ppvSlip.PreviewPane)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ppvSlip)).EndInit();
this.ppvSlip.ResumeLayout(false);
this.ppvSlip.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private void PODeliverySlipReport_Load(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".PODeliverySlipReport_Load()";
try
{
#region Security
//Set authorization for user
Security objSecurity = new Security();
this.Name = THIS;
if(objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
{
this.Close();
// You don't have the right to view this item
PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning);
return;
}
#endregion
strReportFilePath = Application.StartupPath + "\\" +Constants.REPORT_DEFINITION_STORE_LOCATION + "\\" + mstrViewFileName;
strPrintFilePath = Application.StartupPath + "\\" +Constants.REPORT_DEFINITION_STORE_LOCATION + "\\" + mstrReportFileName;
// format date time
dtmFromDateTime.FormatType = FormatTypeEnum.CustomFormat;
dtmFromDateTime.CustomFormat = Constants.DATETIME_FORMAT_HOUR;
dtmToDateTime.FormatType = FormatTypeEnum.CustomFormat;
dtmToDateTime.CustomFormat = Constants.DATETIME_FORMAT_HOUR;
ppvSlip.PreviewNavigationPanel.Visible = false;
ppvSlip.PreviewPane.ZoomMode = ZoomModeEnum.PageWidth;
EnableButtons();
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void radAll_CheckedChanged(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".radAll_CheckedChanged()";
try
{
EnableButtons();
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void radPeriod_CheckedChanged(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".radPeriod_CheckedChanged()";
try
{
EnableButtons();
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void btnView_Click(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".btnView_Click()";
try
{
Cursor = Cursors.WaitCursor;
DateTime dtmToDate = DateTime.MaxValue;
DateTime dtmFromDate = DateTime.MinValue;
if (radPeriod.Checked)
{
if (dtmFromDateTime.Value == DBNull.Value)
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Error);
dtmFromDateTime.Focus();
dtmFromDateTime.SelectAll();
return;
}
if (dtmToDateTime.Value == DBNull.Value)
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Error);
dtmToDateTime.Focus();
dtmToDateTime.SelectAll();
return;
}
// to date must greater than from date
dtmToDate = (DateTime)dtmToDateTime.Value;
dtmFromDate = (DateTime)dtmFromDateTime.Value;
}
if (dtmFromDate > dtmToDate)
{
PCSMessageBox.Show(ErrorCode.MESSAGE_MP_PERIODDATE, MessageBoxIcon.Error);
dtmFromDateTime.Focus();
return;
}
// check if report file is exist or not
if (!File.Exists(strReportFilePath))
{
PCSMessageBox.Show(ErrorCode.MESSAGE_REPORT_TEMPLATE_FILE_NOT_FOUND, MessageBoxIcon.Error);
return;
}
// check if report file is exist or not
if (!File.Exists(strPrintFilePath))
{
PCSMessageBox.Show(ErrorCode.MESSAGE_REPORT_TEMPLATE_FILE_NOT_FOUND, MessageBoxIcon.Error);
return;
}
// only care about date and hour,
// ignore minutes and the other information
if (dtmToDate != DateTime.MaxValue)
dtmToDate = new DateTime(dtmToDate.Year, dtmToDate.Month, dtmToDate.Day, dtmToDate.Hour, 59, 59);
if (dtmFromDate != DateTime.MinValue)
dtmFromDate = new DateTime(dtmFromDate.Year, dtmFromDate.Month, dtmFromDate.Day, dtmFromDate.Hour, 0, 0);
// get the issue date
DateTime dtmIssueDate = new UtilsBO().GetDBDate();
PODeliverySlipBO boDeliverySlip = new PODeliverySlipBO();
// execute report
DataTable dtbData = boDeliverySlip.ExecuteReport(voPOMaster.PurchaseOrderMasterID, dtmFromDate, dtmToDate);
// refine data source
DataSet dstData = BuildReportData(dtbData);
RenderReport(dtmIssueDate, dstData);
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
finally
{
Cursor = Cursors.Default;
}
}
private void btnClose_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void btnHelp_Click(object sender, System.EventArgs e)
{
}
/// <summary>
/// Rendering the report with all parameter
/// </summary>
/// <param name="pdtmIssueDate">The Issue Date</param>
/// <param name="pdtbReportData">Report Data</param>
private void RenderReport(DateTime pdtmIssueDate, DataTable pdtbReportData, bool pblnPrintTwoSlipInOnePage)
{
// prevent reentrant calls
if (rptDeliverySlip.IsBusy)
return;
// initialize control
rptDeliverySlip.Clear(); // clear any existing fields
rptPrintable.Clear();
string[] strReportInfo = rptDeliverySlip.GetReportInfo(strPrintFilePath);
string[] strPrintInfo = rptPrintable.GetReportInfo(strPrintFilePath);
if (strReportInfo != null && strReportInfo.Length > 0)
rptDeliverySlip.Load(strReportFilePath, strReportInfo[0]);
if (strPrintInfo != null && strPrintInfo.Length > 0)
rptPrintable.Load(strPrintFilePath, strPrintInfo[0]);
int intNumOfRows = pdtbReportData.Rows.Count;
// set datasource object that provides data to report.
rptDeliverySlip.DataSource.Recordset = pdtbReportData;
rptPrintable.DataSource.Recordset = pdtbReportData;
C1Report rptSubReport = rptDeliverySlip.Fields[SUB_REPORT_FLD].Subreport;
C1Report rptPrintSubReport = rptPrintable.Fields[SUB_REPORT_FLD].Subreport;
if (intNumOfRows > 0 && !pblnPrintTwoSlipInOnePage)
{
rptDeliverySlip.Fields[SUB_REPORT_FLD].Text = string.Empty;
rptPrintable.Fields[SUB_REPORT_FLD].Text = string.Empty;
rptDeliverySlip.Groups[SCHEDULE_HOUR_FLD].SectionFooter.Visible = false;
rptPrintable.Groups[SCHEDULE_HOUR_FLD].SectionFooter.Visible = false;
#region PUSH PARAMETER VALUE
// header information get from system params
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[PONO_FLD].Text = voPOMaster.Code;
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[PONO_FLD].Text = voPOMaster.Code;
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
}
catch{}
#endregion
// render the report into the PrintPreviewControl
PreviewOnlyNoPrintDialog dlgDeliveryPreview = new PreviewOnlyNoPrintDialog();
dlgDeliveryPreview.ReportViewer.Document = rptDeliverySlip.Document;
dlgDeliveryPreview.ReportViewer.PreviewNavigationPanel.Visible = false;
dlgDeliveryPreview.ReportViewer.PreviewPane.ZoomMode = ZoomModeEnum.PageWidth;
try
{
dlgDeliveryPreview.FormTitle = rptDeliverySlip.Fields[TITLE_FLD].Text;
}
catch{}
dlgDeliveryPreview.Show();
// make a copy of delivery slip to receive slip and show in different printpreview
C1Report rptReceiveSlip = new C1Report();
rptReceiveSlip.CopyFrom(rptDeliverySlip);
rptPrintableReceive.CopyFrom(rptPrintable);
try
{
rptReceiveSlip.Fields[TITLE_FLD].Text = rptSubReport.Fields[TITLE_FLD].Text;
rptPrintableReceive.Fields[TITLE_FLD].Text = rptPrintSubReport.Fields[TITLE_FLD].Text;
}
catch{}
try
{
rptReceiveSlip.Fields["fldCopied"].Text = rptSubReport.Fields["fldCopied"].Text;
rptPrintableReceive.Fields["fldCopied"].Text = rptPrintSubReport.Fields["fldCopied"].Text;
}
catch{}
try
{
rptReceiveSlip.Fields["fldTitleVN"].Text = rptSubReport.Fields["fldTitleVN"].Text;
rptPrintableReceive.Fields["fldTitleVN"].Text = rptPrintSubReport.Fields["fldTitleVN"].Text;
}
catch{}
PreviewOnlyNoPrintDialog dlgReceivePreview = new PreviewOnlyNoPrintDialog();
dlgReceivePreview.ReportViewer.Document = rptReceiveSlip.Document;
dlgReceivePreview.ReportViewer.PreviewNavigationPanel.Visible = false;
dlgReceivePreview.ReportViewer.PreviewPane.ZoomMode = ZoomModeEnum.PageWidth;
dlgReceivePreview.ReportViewer.Name = RECEIVE_SLIP;
try
{
dlgReceivePreview.FormTitle = rptReceiveSlip.Fields[TITLE_FLD].Text;
}
catch{}
dlgReceivePreview.Show();
}
else if (intNumOfRows > 0 && pblnPrintTwoSlipInOnePage)
{
rptSubReport.DataSource.Recordset = pdtbReportData;
rptPrintSubReport.DataSource.Recordset = pdtbReportData;
#region PUSH PARAMETER VALUE
// header information get from system params
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[PONO_FLD].Text = voPOMaster.Code;
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[PONO_FLD].Text = voPOMaster.Code;
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[PONO_FLD].Text = voPOMaster.Code;
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[PONO_FLD].Text = voPOMaster.Code;
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
}
catch{}
#endregion
// render the report into the PrintPreviewControl
PreviewOnlyNoPrintDialog dlgPreview = new PreviewOnlyNoPrintDialog();
dlgPreview.ReportViewer.Document = rptDeliverySlip.Document;
dlgPreview.ReportViewer.PreviewNavigationPanel.Visible = false;
dlgPreview.ReportViewer.PreviewPane.ZoomMode = ZoomModeEnum.PageWidth;
try
{
dlgPreview.FormTitle = rptDeliverySlip.Fields[TITLE_FLD].Text;
}
catch{}
dlgPreview.Show();
}
else
{
// enable report header section
rptDeliverySlip.Sections[SectionTypeEnum.Header].Visible = true;
rptPrintable.Sections[SectionTypeEnum.Header].Visible = true;
// enable page header section
//rptDeliverySlip.Sections[SectionTypeEnum.PageHeader].Visible = true;
#region PUSH PARAMETER VALUE
// header information get from system params
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[SLIP_NO_FLD].Text = voPOMaster.Code + SEPERATOR + pdtmIssueDate.ToString(DATE_FORMAT);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[SLIP_NO_FLD].Text = voPOMaster.Code + SEPERATOR + pdtmIssueDate.ToString(DATE_FORMAT);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[PONO_FLD].Text = voPOMaster.Code;
rptPrintable.Sections[SectionTypeEnum.Header].Fields[PONO_FLD].Text = voPOMaster.Code;
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
}
catch{}
UtilsBO boUtils = new UtilsBO();
MST_PartyVO voParty = (MST_PartyVO)boUtils.GetPartyInfo(voPOMaster.PartyID);
MST_CCNVO voCCN = (MST_CCNVO)boUtils.GetCCNInfo(voPOMaster.CCNID);
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[CUST_CODE_FLD].Text = voParty.Code;
rptPrintable.Sections[SectionTypeEnum.Header].Fields[CUST_CODE_FLD].Text = voParty.Code;
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[CUST_NAME_FLD].Text = voParty.Name;
rptPrintable.Sections[SectionTypeEnum.Header].Fields[CUST_NAME_FLD].Text = voParty.Name;
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[CCN_CODE_FLD].Text = voCCN.Code;
rptPrintable.Sections[SectionTypeEnum.Header].Fields[CCN_CODE_FLD].Text = voCCN.Code;
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[CCN_NAME_FLD].Text = voCCN.Name;
rptPrintable.Sections[SectionTypeEnum.Header].Fields[CCN_NAME_FLD].Text = voCCN.Name;
}
catch{}
#endregion
// render the report into the PrintPreviewControl
PreviewOnlyNoPrintDialog dlgPreview = new PreviewOnlyNoPrintDialog();
dlgPreview.ReportViewer.Document = rptDeliverySlip.Document;
dlgPreview.ReportViewer.PreviewNavigationPanel.Visible = false;
dlgPreview.ReportViewer.PreviewPane.ZoomMode = ZoomModeEnum.PageWidth;
try
{
dlgPreview.FormTitle = rptDeliverySlip.Fields[TITLE_FLD].Text;
}
catch{}
dlgPreview.Show();
}
}
/// <summary>
/// Rendering the report with all parameter
/// </summary>
/// <param name="pdtmIssueDate">The Issue Date</param>
/// <param name="pdtbReportData">Report Data</param>
private void RenderReport(DateTime pdtmIssueDate, DataSet pdstReportData)
{
// prevent reentrant calls
if (rptDeliverySlip.IsBusy)
return;
// initialize control
rptDeliverySlip.Clear(); // clear any existing fields
rptPrintable.Clear();
rptOverDeliverySlip = new C1Report();
rptOverPrintable = new C1Report();
rptOverDeliverySlip.CopyFrom(rptDeliverySlip);
rptOverPrintable.CopyFrom(rptPrintable);
rptOverDeliverySlip.Clear(); // clear any existing fields
rptOverPrintable.Clear();
string[] strReportInfo = rptDeliverySlip.GetReportInfo(strPrintFilePath);
string[] strPrintInfo = rptPrintable.GetReportInfo(strPrintFilePath);
if (strReportInfo != null && strReportInfo.Length > 0)
{
rptDeliverySlip.Load(strReportFilePath, strReportInfo[0]);
rptOverDeliverySlip.Load(strReportFilePath, strReportInfo[0]);
}
if (strPrintInfo != null && strPrintInfo.Length > 0)
{
rptPrintable.Load(strPrintFilePath, strPrintInfo[0]);
rptOverPrintable.Load(strPrintFilePath, strPrintInfo[0]);
}
DataTable dtbOriginalData = pdstReportData.Tables[TABLE_NAME];
DataTable dtbSecondData = new DataTable();
if (pdstReportData.Tables.Count > 1)
dtbSecondData = pdstReportData.Tables[TABLE_NAME + MAX_LINE_PER_SLIP.ToString()];
//int intNumOfRows = dtbOriginalData.Rows.Count;
// set datasource object that provides data to report.
rptDeliverySlip.DataSource.Recordset = dtbOriginalData;
rptPrintable.DataSource.Recordset = dtbOriginalData;
C1Report rptSubReport = rptDeliverySlip.Fields[SUB_REPORT_FLD].Subreport;
C1Report rptPrintSubReport = rptPrintable.Fields[SUB_REPORT_FLD].Subreport;
if (dtbOriginalData.Rows.Count > 0)
{
rptSubReport.DataSource.Recordset = dtbOriginalData;
rptPrintSubReport.DataSource.Recordset = dtbOriginalData;
#region PUSH PARAMETER VALUE
// header information get from system params
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[PONO_FLD].Text = voPOMaster.Code;
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[PONO_FLD].Text = voPOMaster.Code;
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[PONO_FLD].Text = voPOMaster.Code;
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[PONO_FLD].Text = voPOMaster.Code;
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
rptPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
rptSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
rptPrintSubReport.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
}
catch{}
#endregion
// render the report into the PrintPreviewControl
PreviewOnlyNoPrintDialog dlgPreview = new PreviewOnlyNoPrintDialog();
dlgPreview.ReportViewer.Document = rptDeliverySlip.Document;
dlgPreview.ReportViewer.PreviewNavigationPanel.Visible = false;
dlgPreview.ReportViewer.PreviewPane.ZoomMode = ZoomModeEnum.ActualSize;
try
{
dlgPreview.FormTitle = rptDeliverySlip.Fields[TITLE_FLD].Text;
}
catch{}
dlgPreview.Show();
}
// print delivery slip and receive slip seperated
if (pdstReportData.Tables.Count > 1)
{
#region Displays the over data
if (dtbSecondData != null && dtbSecondData.Rows.Count > 0)
{
rptOverDeliverySlip.DataSource.Recordset = dtbSecondData;
rptOverPrintable.DataSource.Recordset = dtbSecondData;
rptOverDeliverySlip.Fields[SUB_REPORT_FLD].Text = string.Empty;
rptOverPrintable.Fields[SUB_REPORT_FLD].Text = string.Empty;
rptOverDeliverySlip.Groups[SCHEDULE_HOUR_FLD].SectionFooter.Visible = false;
rptOverPrintable.Groups[SCHEDULE_HOUR_FLD].SectionFooter.Visible = false;
#region Delivery Slip first
#region PUSH PARAMETER VALUE
// header information get from system params
try
{
rptOverDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
rptOverPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
}
catch{}
try
{
rptOverDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
rptOverPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
}
catch{}
try
{
rptOverDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
rptOverPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
}
catch{}
try
{
rptOverDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
rptOverPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
}
catch{}
try
{
rptOverDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[PONO_FLD].Text = voPOMaster.Code;
rptOverPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[PONO_FLD].Text = voPOMaster.Code;
}
catch{}
try
{
rptOverDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
rptOverPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
}
catch{}
try
{
rptOverDeliverySlip.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
rptOverPrintable.Sections[SectionTypeEnum.GroupHeader2].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
}
catch{}
#endregion
// render the report into the PrintPreviewControl
PreviewOnlyNoPrintDialog dlgDeliveryPreview = new PreviewOnlyNoPrintDialog();
dlgDeliveryPreview.ReportViewer.Document = rptOverDeliverySlip.Document;
dlgDeliveryPreview.ReportViewer.PreviewNavigationPanel.Visible = false;
dlgDeliveryPreview.ReportViewer.PreviewPane.ZoomMode = ZoomModeEnum.PageWidth;
try
{
dlgDeliveryPreview.FormTitle = rptOverDeliverySlip.Fields[TITLE_FLD].Text;
}
catch{}
dlgDeliveryPreview.Show();
#endregion
#region Receive Slip
// make a copy of delivery slip to receive slip and show in different printpreview
C1Report rptReceiveSlip = new C1Report();
rptReceiveSlip.CopyFrom(rptOverDeliverySlip);
rptPrintableReceive.CopyFrom(rptOverPrintable);
try
{
rptReceiveSlip.Fields[TITLE_FLD].Text = rptSubReport.Fields[TITLE_FLD].Text;
rptPrintableReceive.Fields[TITLE_FLD].Text = rptPrintSubReport.Fields[TITLE_FLD].Text;
}
catch{}
try
{
rptReceiveSlip.Fields[COPIED_FLD].Text = rptSubReport.Fields[COPIED_FLD].Text;
rptPrintableReceive.Fields[COPIED_FLD].Text = rptPrintSubReport.Fields[COPIED_FLD].Text;
}
catch{}
try
{
rptReceiveSlip.Fields[TITLE_VN_FLD].Text = rptSubReport.Fields[TITLE_VN_FLD].Text;
rptPrintableReceive.Fields[TITLE_VN_FLD].Text = rptPrintSubReport.Fields[TITLE_VN_FLD].Text;
}
catch{}
PreviewOnlyNoPrintDialog dlgReceivePreview = new PreviewOnlyNoPrintDialog();
dlgReceivePreview.ReportViewer.Document = rptReceiveSlip.Document;
dlgReceivePreview.ReportViewer.PreviewNavigationPanel.Visible = false;
dlgReceivePreview.ReportViewer.PreviewPane.ZoomMode = ZoomModeEnum.PageWidth;
dlgReceivePreview.ReportViewer.Name = RECEIVE_SLIP;
try
{
dlgReceivePreview.FormTitle = rptReceiveSlip.Fields[TITLE_FLD].Text;
}
catch{}
dlgReceivePreview.Show();
#endregion
}
#endregion
}
else if (dtbOriginalData.Rows.Count == 0)
{
// enable report header section
rptDeliverySlip.Sections[SectionTypeEnum.Header].Visible = true;
rptPrintable.Sections[SectionTypeEnum.Header].Visible = true;
// enable page header section
//rptDeliverySlip.Sections[SectionTypeEnum.PageHeader].Visible = true;
#region PUSH PARAMETER VALUE
// header information get from system params
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[COMPANY_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[ADDRESS_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.ADDRESS);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[TEL_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.TEL);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[FAX_FLD].Text = SystemProperty.SytemParams.Get(SystemParam.FAX);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[SLIP_NO_FLD].Text = voPOMaster.Code + SEPERATOR + pdtmIssueDate.ToString(DATE_FORMAT);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[SLIP_NO_FLD].Text = voPOMaster.Code + SEPERATOR + pdtmIssueDate.ToString(DATE_FORMAT);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[PONO_FLD].Text = voPOMaster.Code;
rptPrintable.Sections[SectionTypeEnum.Header].Fields[PONO_FLD].Text = voPOMaster.Code;
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[ISSUE_DATE_FLD].Text = pdtmIssueDate.ToString(Constants.DATETIME_FORMAT);
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
rptPrintable.Sections[SectionTypeEnum.Header].Fields[ISSUEHOUR_FLD].Text = pdtmIssueDate.ToString(SHORT_TIME_FORMAT);
}
catch{}
UtilsBO boUtils = new UtilsBO();
MST_PartyVO voParty = (MST_PartyVO)boUtils.GetPartyInfo(voPOMaster.PartyID);
MST_CCNVO voCCN = (MST_CCNVO)boUtils.GetCCNInfo(voPOMaster.CCNID);
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[CUST_CODE_FLD].Text = voParty.Code;
rptPrintable.Sections[SectionTypeEnum.Header].Fields[CUST_CODE_FLD].Text = voParty.Code;
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[CUST_NAME_FLD].Text = voParty.Name;
rptPrintable.Sections[SectionTypeEnum.Header].Fields[CUST_NAME_FLD].Text = voParty.Name;
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[CCN_CODE_FLD].Text = voCCN.Code;
rptPrintable.Sections[SectionTypeEnum.Header].Fields[CCN_CODE_FLD].Text = voCCN.Code;
}
catch{}
try
{
rptDeliverySlip.Sections[SectionTypeEnum.Header].Fields[CCN_NAME_FLD].Text = voCCN.Name;
rptPrintable.Sections[SectionTypeEnum.Header].Fields[CCN_NAME_FLD].Text = voCCN.Name;
}
catch{}
#endregion
// render the report into the PrintPreviewControl
PreviewOnlyNoPrintDialog dlgPreview = new PreviewOnlyNoPrintDialog();
dlgPreview.ReportViewer.Document = rptDeliverySlip.Document;
dlgPreview.ReportViewer.PreviewNavigationPanel.Visible = false;
dlgPreview.ReportViewer.PreviewPane.ZoomMode = ZoomModeEnum.PageWidth;
try
{
dlgPreview.FormTitle = rptDeliverySlip.Fields[TITLE_FLD].Text;
}
catch{}
dlgPreview.Show();
}
}
/// <summary>
/// Enable button based on the option All or Period
/// </summary>
private void EnableButtons()
{
lblFromDateTime.Enabled = radPeriod.Checked;
dtmFromDateTime.Enabled = radPeriod.Checked;
lblToDateTime.Enabled = radPeriod.Checked;
dtmToDateTime.Enabled = radPeriod.Checked;
}
/// <summary>
/// Build report data match with the report template from source data
/// </summary>
/// <param name="pdtbData">Source Data</param>
/// <returns>True if more than 10 rows</returns>
private bool BuildReportData(ref DataTable pdtbData)
{
bool blnIsOver = false;
DataTable dtbResult = pdtbData.Clone();
foreach (DataColumn dcolData in dtbResult.Columns)
dcolData.AllowDBNull = true;
ArrayList arrDates = new ArrayList();
// get all schedule date
foreach (DataRow drowData in pdtbData.Rows)
{
DateTime dtmRowDate = (DateTime)drowData[PO_DeliveryScheduleTable.SCHEDULEDATE_FLD];
int intRowHour = (int)drowData[SCHEDULE_HOUR_FLD];
dtmRowDate = dtmRowDate.AddHours(intRowHour);
if (!arrDates.Contains(dtmRowDate))
arrDates.Add(dtmRowDate);
}
arrDates.Sort();
arrDates.TrimToSize();
// foreach schedule date
foreach (DateTime dtmScheduleDate in arrDates)
{
DateTime dtmDate = new DateTime(dtmScheduleDate.Year, dtmScheduleDate.Month, dtmScheduleDate.Day);
// select all delivery line of today in source table
string strExpr = PO_DeliveryScheduleTable.SCHEDULEDATE_FLD + Constants.EQUAL + "'" + dtmDate.ToString() + "'"
+ Constants.AND + SCHEDULE_HOUR_FLD + Constants.EQUAL + "'" + dtmScheduleDate.Hour + "'";
DataRow[] drowLines = pdtbData.Select(strExpr);
int intMissing = MAX_LINE_PER_SLIP - drowLines.Length;
if (drowLines.Length > MAX_LINE_PER_SLIP)
blnIsOver = true;
//if (intMissing < 0)
// continue;
for (int i = 0; i < drowLines.Length; i++)
{
dtbResult.ImportRow(drowLines[i]);
}
for (int i = 1; i <= intMissing; i++)
{
DataRow drowNew = dtbResult.NewRow();
drowNew[PO_DeliveryScheduleTable.SCHEDULEDATE_FLD] = dtmDate;
drowNew[SCHEDULE_HOUR_FLD] = dtmScheduleDate.Hour;
dtbResult.Rows.Add(drowNew);
}
}
pdtbData.Clear();
pdtbData = dtbResult.Copy();
return blnIsOver;
}
/// <summary>
/// Build report data match with the report template from source data
/// </summary>
/// <param name="pdtbData">Source Data</param>
/// <returns>DataSet will have more than one DataTable inside if any time have more than 10 rows</returns>
private DataSet BuildReportData(DataTable pdtbData)
{
DataSet dstData = new DataSet();
DataTable dtbResult = pdtbData.Clone();
DataTable dtbOver = pdtbData.Clone();
dtbOver.TableName += MAX_LINE_PER_SLIP.ToString();
foreach (DataColumn dcolData in dtbResult.Columns)
dcolData.AllowDBNull = true;
ArrayList arrDates = new ArrayList();
// get all schedule date
foreach (DataRow drowData in pdtbData.Rows)
{
DateTime dtmRowDate = (DateTime)drowData[PO_DeliveryScheduleTable.SCHEDULEDATE_FLD];
int intRowHour = (int)drowData[SCHEDULE_HOUR_FLD];
dtmRowDate = dtmRowDate.AddHours(intRowHour);
if (!arrDates.Contains(dtmRowDate))
arrDates.Add(dtmRowDate);
}
arrDates.Sort();
arrDates.TrimToSize();
// foreach schedule date
foreach (DateTime dtmScheduleDate in arrDates)
{
DateTime dtmDate = new DateTime(dtmScheduleDate.Year, dtmScheduleDate.Month, dtmScheduleDate.Day);
// select all delivery line of today in source table
string strExpr = PO_DeliveryScheduleTable.SCHEDULEDATE_FLD + Constants.EQUAL + "'" + dtmDate.ToString() + "'"
+ Constants.AND + SCHEDULE_HOUR_FLD + Constants.EQUAL + "'" + dtmScheduleDate.Hour + "'";
DataRow[] drowLines = pdtbData.Select(strExpr);
int intMissing = MAX_LINE_PER_SLIP - drowLines.Length;
if (drowLines.Length > MAX_LINE_PER_SLIP)
{
for (int i = 0; i < drowLines.Length; i++)
dtbOver.ImportRow(drowLines[i]);
}
else
{
for (int i = 0; i < drowLines.Length; i++)
dtbResult.ImportRow(drowLines[i]);
for (int i = 1; i <= intMissing; i++)
{
DataRow drowNew = dtbResult.NewRow();
drowNew[PO_DeliveryScheduleTable.SCHEDULEDATE_FLD] = dtmDate;
drowNew[SCHEDULE_HOUR_FLD] = dtmScheduleDate.Hour;
dtbResult.Rows.Add(drowNew);
}
}
}
dstData.Tables.Add(dtbResult);
if (dtbOver.Rows.Count > 0)
dstData.Tables.Add(dtbOver);
return dstData;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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.Linq;
using NUnit.Framework.Interfaces;
using NUnit.TestData.OneTimeSetUpTearDownData;
using NUnit.TestUtilities;
using NUnit.TestData.TestFixtureTests;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Tests of the NUnitTestFixture class
/// </summary>
[TestFixture]
public class TestFixtureTests
{
private static string dataAssembly = "nunit.testdata";
private static void CanConstructFrom(Type fixtureType)
{
CanConstructFrom(fixtureType, fixtureType.Name);
}
private static void CanConstructFrom(Type fixtureType, string expectedName)
{
TestSuite fixture = TestBuilder.MakeFixture(fixtureType);
Assert.AreEqual(expectedName, fixture.Name);
Assert.AreEqual(fixtureType.FullName, fixture.FullName);
}
private static Type GetTestDataType(string typeName)
{
string qualifiedName = string.Format("{0},{1}", typeName, dataAssembly);
Type type = Type.GetType(qualifiedName);
return type;
}
[Test]
public void ConstructFromType()
{
CanConstructFrom(typeof(FixtureWithTestFixtureAttribute));
}
[Test]
public void ConstructFromNestedType()
{
CanConstructFrom(typeof(OuterClass.NestedTestFixture), "OuterClass+NestedTestFixture");
}
[Test]
public void ConstructFromDoublyNestedType()
{
CanConstructFrom(typeof(OuterClass.NestedTestFixture.DoublyNestedTestFixture), "OuterClass+NestedTestFixture+DoublyNestedTestFixture");
}
public void ConstructFromTypeWithoutTestFixtureAttributeContainingTest()
{
CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTest));
}
[Test]
public void ConstructFromTypeWithoutTestFixtureAttributeContainingTestCase()
{
CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTestCase));
}
[Test]
public void ConstructFromTypeWithoutTestFixtureAttributeContainingTestCaseSource()
{
CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTestCaseSource));
}
#if !PORTABLE
[Test]
public void ConstructFromTypeWithoutTestFixtureAttributeContainingTheory()
{
CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTheory));
}
#endif
[Test]
public void CannotRunConstructorWithArgsNotSupplied()
{
TestAssert.IsNotRunnable(typeof(NoDefaultCtorFixture));
}
[Test]
public void CanRunConstructorWithArgsSupplied()
{
TestAssert.IsRunnable(typeof(FixtureWithArgsSupplied));
}
[Test]
public void CapturesArgumentsForConstructorWithArgsSupplied()
{
var fixture = TestBuilder.MakeFixture(typeof(FixtureWithArgsSupplied));
Assert.That(fixture.Arguments, Is.EqualTo(new[] { 7, 3 }));
}
[Test]
public void CapturesNoArgumentsForConstructorWithoutArgsSupplied()
{
var fixture = TestBuilder.MakeFixture(typeof(RegularFixtureWithOneTest));
Assert.That(fixture.Arguments, Is.EqualTo(new object[0]));
}
[Test]
public void CapturesArgumentsForConstructorWithMultipleArgsSupplied()
{
var fixture = TestBuilder.MakeFixture(typeof(FixtureWithMultipleArgsSupplied));
Assert.True(fixture.HasChildren);
var expectedArgumentSeries = new[]
{
new object[] {8, 4},
new object[] {7, 3}
};
var actualArgumentSeries = fixture.Tests.Select(x => x.Arguments).ToArray();
Assert.That(actualArgumentSeries, Is.EquivalentTo(expectedArgumentSeries));
}
[Test]
public void BadConstructorRunsWithSetUpError()
{
var result = TestBuilder.RunTestFixture(typeof(BadCtorFixture));
Assert.That(result.ResultState, Is.EqualTo(ResultState.SetUpError));
}
[Test]
public void CanRunMultipleSetUp()
{
TestAssert.IsRunnable(typeof(MultipleSetUpAttributes));
}
[Test]
public void CanRunMultipleTearDown()
{
TestAssert.IsRunnable(typeof(MultipleTearDownAttributes));
}
[Test]
public void FixtureUsingIgnoreAttributeIsIgnored()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(FixtureUsingIgnoreAttribute));
Assert.AreEqual(RunState.Ignored, suite.RunState);
Assert.AreEqual("testing ignore a fixture", suite.Properties.Get(PropertyNames.SkipReason));
}
[Test]
public void FixtureUsingIgnorePropertyIsIgnored()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(FixtureUsingIgnoreProperty));
Assert.AreEqual(RunState.Ignored, suite.RunState);
Assert.AreEqual("testing ignore a fixture", suite.Properties.Get(PropertyNames.SkipReason));
}
[Test]
public void FixtureUsingIgnoreReasonPropertyIsIgnored()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(FixtureUsingIgnoreReasonProperty));
Assert.AreEqual(RunState.Ignored, suite.RunState);
Assert.AreEqual("testing ignore a fixture", suite.Properties.Get(PropertyNames.SkipReason));
}
// [Test]
// public void CannotRunAbstractFixture()
// {
// TestAssert.IsNotRunnable(typeof(AbstractTestFixture));
// }
[Test]
public void CanRunFixtureDerivedFromAbstractTestFixture()
{
TestAssert.IsRunnable(typeof(DerivedFromAbstractTestFixture));
}
[Test]
public void CanRunFixtureDerivedFromAbstractDerivedTestFixture()
{
TestAssert.IsRunnable(typeof(DerivedFromAbstractDerivedTestFixture));
}
// [Test]
// public void CannotRunAbstractDerivedFixture()
// {
// TestAssert.IsNotRunnable(typeof(AbstractDerivedTestFixture));
// }
[Test]
public void FixtureInheritingTwoTestFixtureAttributesIsLoadedOnlyOnce()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(DoubleDerivedClassWithTwoInheritedAttributes));
Assert.That(suite, Is.TypeOf(typeof(TestFixture)));
Assert.That(suite.Tests.Count, Is.EqualTo(0));
}
[Test]
public void CanRunMultipleTestFixtureSetUp()
{
TestAssert.IsRunnable(typeof(MultipleFixtureSetUpAttributes));
}
[Test]
public void CanRunMultipleTestFixtureTearDown()
{
TestAssert.IsRunnable(typeof(MultipleFixtureTearDownAttributes));
}
[Test]
public void CanRunTestFixtureWithNoTests()
{
TestAssert.IsRunnable(typeof(FixtureWithNoTests));
}
[Test]
public void ConstructFromStaticTypeWithoutTestFixtureAttribute()
{
CanConstructFrom(typeof(StaticFixtureWithoutTestFixtureAttribute));
}
[Test]
public void CanRunStaticFixture()
{
TestAssert.IsRunnable(typeof(StaticFixtureWithoutTestFixtureAttribute));
}
[Test]
public void CanRunGenericFixtureWithProperArgsProvided()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(GenericFixtureWithProperArgsProvided<>));
// GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureWithProperArgsProvided`1"));
Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(suite is ParameterizedFixtureSuite);
Assert.That(suite.Tests.Count, Is.EqualTo(2));
}
// [Test]
// public void CannotRunGenericFixtureWithNoTestFixtureAttribute()
// {
// TestSuite suite = TestBuilder.MakeFixture(
// GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureWithNoTestFixtureAttribute`1"));
//
// Assert.That(suite.RunState, Is.EqualTo(RunState.NotRunnable));
// Assert.That(suite.Properties.Get(PropertyNames.SkipReason),
// Does.StartWith("Fixture type contains generic parameters"));
// }
[Test]
public void CannotRunGenericFixtureWithNoArgsProvided()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(GenericFixtureWithNoArgsProvided<>));
// GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureWithNoArgsProvided`1"));
Test fixture = (Test)suite.Tests[0];
Assert.That(fixture.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That((string)fixture.Properties.Get(PropertyNames.SkipReason), Does.StartWith("Fixture type contains generic parameters"));
}
[Test]
public void CannotRunGenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided<>));
// GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided`1"));
TestAssert.IsNotRunnable((Test)suite.Tests[0]);
}
[Test]
public void CanRunGenericFixtureDerivedFromAbstractFixtureWithArgsProvided()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(GenericFixtureDerivedFromAbstractFixtureWithArgsProvided<>));
// GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureDerivedFromAbstractFixtureWithArgsProvided`1"));
Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(suite is ParameterizedFixtureSuite);
Assert.That(suite.Tests.Count, Is.EqualTo(2));
}
#region SetUp Signature
[Test]
public void CannotRunPrivateSetUp()
{
TestAssert.IsNotRunnable(typeof(PrivateSetUp));
}
[Test]
public void CanRunProtectedSetUp()
{
TestAssert.IsRunnable(typeof(ProtectedSetUp));
}
/// <summary>
/// Determines whether this instance [can run static set up].
/// </summary>
[Test]
public void CanRunStaticSetUp()
{
TestAssert.IsRunnable(typeof(StaticSetUp));
}
[Test]
public void CannotRunSetupWithReturnValue()
{
TestAssert.IsNotRunnable(typeof(SetUpWithReturnValue));
}
[Test]
public void CannotRunSetupWithParameters()
{
TestAssert.IsNotRunnable(typeof(SetUpWithParameters));
}
#endregion
#region TearDown Signature
[Test]
public void CannotRunPrivateTearDown()
{
TestAssert.IsNotRunnable(typeof(PrivateTearDown));
}
[Test]
public void CanRunProtectedTearDown()
{
TestAssert.IsRunnable(typeof(ProtectedTearDown));
}
[Test]
public void CanRunStaticTearDown()
{
TestAssert.IsRunnable(typeof(StaticTearDown));
}
[Test]
public void CannotRunTearDownWithReturnValue()
{
TestAssert.IsNotRunnable(typeof(TearDownWithReturnValue));
}
[Test]
public void CannotRunTearDownWithParameters()
{
TestAssert.IsNotRunnable(typeof(TearDownWithParameters));
}
#endregion
#region TestFixtureSetUp Signature
[Test]
public void CannotRunPrivateFixtureSetUp()
{
TestAssert.IsNotRunnable(typeof(PrivateFixtureSetUp));
}
[Test]
public void CanRunProtectedFixtureSetUp()
{
TestAssert.IsRunnable(typeof(ProtectedFixtureSetUp));
}
[Test]
public void CanRunStaticFixtureSetUp()
{
TestAssert.IsRunnable(typeof(StaticFixtureSetUp));
}
[Test]
public void CannotRunFixtureSetupWithReturnValue()
{
TestAssert.IsNotRunnable(typeof(FixtureSetUpWithReturnValue));
}
[Test]
public void CannotRunFixtureSetupWithParameters()
{
TestAssert.IsNotRunnable(typeof(FixtureSetUpWithParameters));
}
#endregion
#region TestFixtureTearDown Signature
[Test]
public void CannotRunPrivateFixtureTearDown()
{
TestAssert.IsNotRunnable(typeof(PrivateFixtureTearDown));
}
[Test]
public void CanRunProtectedFixtureTearDown()
{
TestAssert.IsRunnable(typeof(ProtectedFixtureTearDown));
}
[Test]
public void CanRunStaticFixtureTearDown()
{
TestAssert.IsRunnable(typeof(StaticFixtureTearDown));
}
// [TestFixture]
// [Category("fixture category")]
// [Category("second")]
// private class HasCategories
// {
// [Test] public void OneTest()
// {}
// }
//
// [Test]
// public void LoadCategories()
// {
// TestSuite fixture = LoadFixture("NUnit.Core.Tests.TestFixtureBuilderTests+HasCategories");
// Assert.IsNotNull(fixture);
// Assert.AreEqual(2, fixture.Categories.Count);
// }
[Test]
public void CannotRunFixtureTearDownWithReturnValue()
{
TestAssert.IsNotRunnable(typeof(FixtureTearDownWithReturnValue));
}
[Test]
public void CannotRunFixtureTearDownWithParameters()
{
TestAssert.IsNotRunnable(typeof(FixtureTearDownWithParameters));
}
#endregion
#region Issue 318 - Test Fixture is null on ITest objects
public class FixtureNotNullTestAttribute : TestActionAttribute
{
private readonly string _location;
public FixtureNotNullTestAttribute(string location)
{
_location = location;
}
public override void BeforeTest(ITest test)
{
Assert.That(test, Is.Not.Null, "ITest is null on a " + _location);
Assert.That(test.Fixture, Is.Not.Null, "ITest.Fixture is null on a " + _location);
Assert.That(test.Fixture.GetType(), Is.EqualTo(test.TypeInfo.Type), "ITest.Fixture is not the correct type on a " + _location);
}
}
[FixtureNotNullTest("TestFixture class")]
[TestFixture]
public class FixtureIsNotNullForTests
{
[FixtureNotNullTest("Test method")]
[Test]
public void TestMethod()
{
}
[FixtureNotNullTest("TestCase method")]
[TestCase(1)]
public void TestCaseMethod(int i)
{
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.ServiceModel.Description;
using System.Xml;
using System.Web.Services.Discovery;
using System.Net;
using System.Xml.Schema;
using System.Net.Security;
using System.IO;
using System.Diagnostics;
using System.Security.Cryptography.X509Certificates;
using System.Xml.Serialization;
using WebServiceDescription = System.Web.Services.Description.ServiceDescription;
namespace Thinktecture.Tools.Web.Services.CodeGeneration
{
/// <summary>
/// Retrieves and imports meta data for WSDL documents and XSD files.
/// </summary>
internal sealed class MetadataFactory
{
#region Public methods
/// <summary>
/// Retrieves and imports meta data for a given WSDL document specified by
/// WsdlDocument property.
/// </summary>
/// <param name="options">The metadata resolving options.</param>
/// <returns>A collection of service metadata in XML form.</returns>
public static MetadataSet GetMetadataSet(MetadataResolverOptions options)
{
if (options == null)
{
throw new ArgumentException("options could not be null.");
}
if (string.IsNullOrEmpty(options.MetadataLocation))
{
throw new ArgumentException("MetadataLocation option could not be null or an empty string.");
}
try
{
// First download the contracts if they are accessed over the web.
DownloadContract(options);
// Try to run RPC2DocumentLiteral converter.
TryTranslateRpc2DocumentLiteral(options);
MetadataSet metadataSet = new MetadataSet();
XmlDocument doc = new XmlDocument();
doc.Load(options.MetadataLocation);
MetadataSection ms = new MetadataSection(null, null, doc);
metadataSet.MetadataSections.Add(ms);
ResolveImports(options, metadataSet);
return metadataSet;
}
catch (Exception ex)
{
// TODO: Log exception.
throw new MetadataResolveException("Could not resolve metadata", ex);
}
}
/// <summary>
/// Gets the XML schemas for generating data contracts.
/// </summary>
/// <param name="options">The metadata resolving options.</param>
/// <returns>A collection of the XML schemas.</returns>
public static XmlSchemas GetXmlSchemas(MetadataResolverOptions options)
{
if (options.DataContractFiles == null)
throw new ArgumentNullException("options");
// Resolve the schemas.
XmlSchemas schemas = new XmlSchemas();
for (int fi = 0; fi < options.DataContractFiles.Length; fi++)
{
// Skip the non xsd/wsdl files.
string lowext = Path.GetExtension(options.DataContractFiles[fi]).ToLower();
if (lowext == ".xsd") // This is an XSD file.
{
XmlTextReader xmltextreader = null;
try
{
xmltextreader = new XmlTextReader(options.DataContractFiles[fi]);
XmlSchema schema = XmlSchema.Read(xmltextreader, null);
XmlSchemaSet schemaset = new XmlSchemaSet();
schemaset.Add(schema);
RemoveDuplicates(ref schemaset);
schemaset.Compile();
schemas.Add(schema);
}
finally
{
if (xmltextreader != null)
{
xmltextreader.Close();
}
}
}
else if (lowext == ".wsdl") // This is a WSDL file.
{
XmlSchemaSet schemaset = new XmlSchemaSet();
XmlSchemaSet embeddedschemaset = new XmlSchemaSet();
DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
dcp.AllowAutoRedirect = true;
dcp.Credentials = CredentialCache.DefaultCredentials;
dcp.DiscoverAny(options.DataContractFiles[fi]);
dcp.ResolveAll();
foreach (object document in dcp.Documents.Values)
{
if (document is XmlSchema)
{
schemaset.Add((XmlSchema)document);
schemas.Add((XmlSchema)document);
}
if (document is WebServiceDescription)
{
schemas.Add(((WebServiceDescription)document).Types.Schemas);
foreach (XmlSchema schema in ((WebServiceDescription)document).Types.Schemas)
{
embeddedschemaset.Add(schema);
schemas.Add(schema);
}
}
}
RemoveDuplicates(ref schemaset);
schemaset.Add(embeddedschemaset);
schemaset.Compile();
}
}
return schemas;
}
#endregion
#region Private methods
private static void DownloadContract(MetadataResolverOptions options)
{
// Return if we don't have an http endpoint.
if (!options.MetadataLocation.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase) &&
!options.MetadataLocation.StartsWith("https://", StringComparison.CurrentCultureIgnoreCase))
{
return;
}
// Create a Uri for the specified metadata location.
Uri uri = new Uri(options.MetadataLocation);
string tempFilename = GetTempFilename(uri);
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CertValidation);
WebRequest req = WebRequest.Create(options.MetadataLocation);
WebResponse result = req.GetResponse();
Stream receiveStream = result.GetResponseStream();
WriteStream(receiveStream, tempFilename);
options.MetadataLocation = tempFilename;
}
private static string GetTempFilename(Uri metadataUri)
{
string tempDir = Path.GetTempPath();
string filename = null;
Debug.Assert(tempDir != null, "Could not determine the temp directory.");
// Check if the contracts are published in the root.
if (metadataUri.Segments.Length == 1)
{
if (metadataUri.Segments[0] == "/")
{
filename = Guid.NewGuid().ToString();
}
else
{
// I haven't yet thought about this case and AFAIK,
// this code should never arrive here.
Debug.Assert(false, "Special case.");
}
}
else
{
filename = metadataUri.Segments[metadataUri.Segments.Length - 1];
filename = Path.GetFileNameWithoutExtension(filename);
}
filename = filename + ".wsdl";
return Path.Combine(tempDir, filename);
}
private static bool CertValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
private static void WriteStream(Stream stream, string targetFile)
{
XmlWriter writer = null;
StreamReader reader = null;
FileStream fileStream = null;
try
{
fileStream = File.Open(targetFile, FileMode.Create, FileAccess.Write, FileShare.None);
reader = new StreamReader(stream);
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.OmitXmlDeclaration = true;
xmlWriterSettings.Indent = true;
writer = XmlWriter.Create(fileStream, xmlWriterSettings);
string wsdl = reader.ReadToEnd();
writer.WriteRaw(wsdl);
writer.Flush();
}
finally
{
if (reader != null)
{
reader.Close();
}
if (writer != null)
{
writer.Close();
}
if (fileStream != null)
{
fileStream.Dispose();
}
TrySetTempAttribute(targetFile);
}
}
private static bool TrySetTempAttribute(string file)
{
try
{
File.SetAttributes(file, FileAttributes.Temporary);
return true;
}
catch (Exception)
{
return false;
}
}
private static void TryTranslateRpc2DocumentLiteral(MetadataResolverOptions options)
{
// TODO: This will not work properly for file names like this my.wsdl.wsdl.
string translatedWsdlFilename = options.MetadataLocation.Replace(".wsdl", "_transformed.wsdl");
try
{
if (Rpc2DocumentLiteralTranslator.ContainsRpcLiteralBindings(options.MetadataLocation))
{
// Execute the translation.
Rpc2DocumentLiteralTranslator r2d = Rpc2DocumentLiteralTranslator.Translate(options.MetadataLocation, translatedWsdlFilename);
options.MetadataLocation = translatedWsdlFilename;
}
}
catch (Rpc2DocumentLiteralTranslationException)
{
// TODO: Log the exception details.c
}
}
private static void ResolveImports(MetadataResolverOptions options, MetadataSet metadataSet)
{
// Resolve metadata using a DiscoveryClientProtocol.
DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
dcp.Credentials = GetCredentials(options);
dcp.AllowAutoRedirect = true;
dcp.DiscoverAny(options.MetadataLocation);
dcp.ResolveAll();
foreach (object osd in dcp.Documents.Values)
{
if (osd is System.Web.Services.Description.ServiceDescription)
{
MetadataSection mds = MetadataSection.CreateFromServiceDescription((System.Web.Services.Description.ServiceDescription)osd);
metadataSet.MetadataSections.Add(mds);
continue;
}
if (osd is XmlSchema)
{
MetadataSection mds = MetadataSection.CreateFromSchema((XmlSchema)osd);
metadataSet.MetadataSections.Add(mds);
continue;
}
}
}
/// <summary>
/// Returns an object of ICredentials type according to the options.
/// </summary>
private static ICredentials GetCredentials(MetadataResolverOptions options)
{
if (string.IsNullOrEmpty(options.Username))
{
return CredentialCache.DefaultCredentials;
}
else
{
return new NetworkCredential(options.Username, options.Password);
}
}
/// <summary>
/// Removes the duplicate schemas in a given XmlSchemaSet instance.
/// </summary>
private static void RemoveDuplicates(ref XmlSchemaSet set)
{
ArrayList schemalist = new ArrayList(set.Schemas());
ArrayList duplicatedschemalist = new ArrayList();
for (int schemaindex = 0; schemaindex < schemalist.Count; schemaindex++)
{
if (((XmlSchema)schemalist[schemaindex]).SourceUri == string.Empty)
{
duplicatedschemalist.Add(schemalist[schemaindex]);
}
else
{
for (int lowerschemaindex = schemaindex + 1; lowerschemaindex < schemalist.Count; lowerschemaindex++)
{
if (((XmlSchema)schemalist[lowerschemaindex]).SourceUri == ((XmlSchema)schemalist[schemaindex]).SourceUri)
{
duplicatedschemalist.Add(schemalist[lowerschemaindex]);
}
}
}
}
foreach (XmlSchema schema in duplicatedschemalist)
{
set.Remove(schema);
}
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.TestingHost.Utils;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
namespace DefaultCluster.Tests.General
{
/// <summary>
/// Summary description for ObserverTests
/// </summary>
public class ObserverTests : HostedTestClusterEnsureDefaultStarted
{
private readonly TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromSeconds(10);
private int callbackCounter;
private readonly bool[] callbacksRecieved = new bool[2];
// we keep the observer objects as instance variables to prevent them from
// being garbage collected permaturely (the runtime stores them as weak references).
private SimpleGrainObserver observer1;
private SimpleGrainObserver observer2;
public ObserverTests(DefaultClusterFixture fixture) : base(fixture)
{
}
private void TestInitialize()
{
callbackCounter = 0;
callbacksRecieved[0] = false;
callbacksRecieved[1] = false;
observer1 = null;
observer2 = null;
}
private ISimpleObserverableGrain GetGrain()
{
return this.GrainFactory.GetGrain<ISimpleObserverableGrain>(GetRandomGrainId());
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_SimpleNotification()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_SimpleNotification_Callback, result, this.Logger);
ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(this.observer1);
await grain.Subscribe(reference);
await grain.SetA(3);
await grain.SetB(2);
Assert.True(await result.WaitForFinished(timeout));
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_SimpleNotification_GeneratedFactory()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_SimpleNotification_Callback, result, this.Logger);
ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(3);
await grain.SetB(2);
Assert.True(await result.WaitForFinished(timeout));
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_SimpleNotification_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
this.Logger.Info("Invoking ObserverTest_SimpleNotification_Callback for {0} time with a = {1} and b = {2}", this.callbackCounter, a, b);
if (a == 3 && b == 0)
callbacksRecieved[0] = true;
else if (a == 3 && b == 2)
callbacksRecieved[1] = true;
else
throw new ArgumentOutOfRangeException("Unexpected callback with values: a=" + a + ",b=" + b);
if (callbackCounter == 1)
{
// Allow for callbacks occurring in any order
Assert.True(callbacksRecieved[0] || callbacksRecieved[1]);
}
else if (callbackCounter == 2)
{
Assert.True(callbacksRecieved[0] && callbacksRecieved[1]);
result.Done = true;
}
else
{
Assert.True(false);
}
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_DoubleSubscriptionSameReference()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_DoubleSubscriptionSameReference_Callback, result, this.Logger);
ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(1); // Use grain
try
{
await grain.Subscribe(reference);
}
catch (TimeoutException)
{
throw;
}
catch (Exception exc)
{
Exception baseException = exc.GetBaseException();
this.Logger.Info("Received exception: {0}", baseException);
Assert.IsAssignableFrom<OrleansException>(baseException);
if (!baseException.Message.StartsWith("Cannot subscribe already subscribed observer"))
{
Assert.True(false, "Unexpected exception message: " + baseException);
}
}
await grain.SetA(2); // Use grain
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetA(2)", timeout));
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_DoubleSubscriptionSameReference_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
this.Logger.Info("Invoking ObserverTest_DoubleSubscriptionSameReference_Callback for {0} time with a={1} and b={2}", this.callbackCounter, a, b);
Assert.True(callbackCounter <= 2, "Callback has been called more times than was expected " + callbackCounter);
if (callbackCounter == 2)
{
result.Continue = true;
}
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_SubscribeUnsubscribe()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_SubscribeUnsubscribe_Callback, result, this.Logger);
ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(5);
Assert.True(await result.WaitForContinue(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await grain.Unsubscribe(reference);
await grain.SetB(3);
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetB", timeout));
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_SubscribeUnsubscribe_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
this.Logger.Info("Invoking ObserverTest_SubscribeUnsubscribe_Callback for {0} time with a = {1} and b = {2}", this.callbackCounter, a, b);
Assert.True(callbackCounter < 2, "Callback has been called more times than was expected.");
Assert.Equal(5, a);
Assert.Equal(0, b);
result.Continue = true;
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_Unsubscribe()
{
TestInitialize();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(null, null, this.Logger);
ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
try
{
await grain.Unsubscribe(reference);
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
catch (TimeoutException)
{
throw;
}
catch (Exception exc)
{
Exception baseException = exc.GetBaseException();
if (!(baseException is OrleansException))
Assert.True(false);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_DoubleSubscriptionDifferentReferences()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result, this.Logger);
ISimpleGrainObserver reference1 = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
this.observer2 = new SimpleGrainObserver(this.ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result, this.Logger);
ISimpleGrainObserver reference2 = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer2);
await grain.Subscribe(reference1);
await grain.Subscribe(reference2);
grain.SetA(6).Ignore();
Assert.True(await result.WaitForFinished(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference1);
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference2);
}
void ObserverTest_DoubleSubscriptionDifferentReferences_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
this.Logger.Info("Invoking ObserverTest_DoubleSubscriptionDifferentReferences_Callback for {0} time with a = {1} and b = {2}", this.callbackCounter, a, b);
Assert.True(callbackCounter < 3, "Callback has been called more times than was expected.");
Assert.Equal(6, a);
Assert.Equal(0, b);
if (callbackCounter == 2)
result.Done = true;
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_DeleteObject()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_DeleteObject_Callback, result, this.Logger);
ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(5);
Assert.True(await result.WaitForContinue(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
await grain.SetB(3);
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetB", timeout));
}
void ObserverTest_DeleteObject_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
this.Logger.Info("Invoking ObserverTest_DeleteObject_Callback for {0} time with a = {1} and b = {2}", this.callbackCounter, a, b);
Assert.True(callbackCounter < 2, "Callback has been called more times than was expected.");
Assert.Equal(5, a);
Assert.Equal(0, b);
result.Continue = true;
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_SubscriberMustBeGrainReference()
{
TestInitialize();
await Assert.ThrowsAsync<NotSupportedException>(async () =>
{
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = this.GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_SimpleNotification_Callback, result, this.Logger);
ISimpleGrainObserver reference = this.observer1;
// Should be: this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(obj);
await grain.Subscribe(reference);
// Not reached
});
}
[Fact, TestCategory("BVT")]
public async Task ObserverTest_CreateObjectReference_ThrowsForInvalidArgumentTypes()
{
TestInitialize();
// Attempt to create an object reference to a Grain class.
await Assert.ThrowsAsync<ArgumentException>(() => this.Client.CreateObjectReference<ISimpleGrainObserver>(new DummyObserverGrain()));
// Attempt to create an object reference to an existing GrainReference.
var observer = new DummyObserver();
var reference = await this.Client.CreateObjectReference<ISimpleGrainObserver>(observer);
await Assert.ThrowsAsync<ArgumentException>(() => this.Client.CreateObjectReference<ISimpleGrainObserver>(reference));
}
private class DummyObserverGrain : Grain, ISimpleGrainObserver
{
public void StateChanged(int a, int b) { }
}
private class DummyObserver : ISimpleGrainObserver
{
public void StateChanged(int a, int b) { }
}
internal class SimpleGrainObserver : ISimpleGrainObserver
{
readonly Action<int, int, AsyncResultHandle> action;
readonly AsyncResultHandle result;
private readonly ILogger logger;
public SimpleGrainObserver(Action<int, int, AsyncResultHandle> action, AsyncResultHandle result, ILogger logger)
{
this.action = action;
this.result = result;
this.logger = logger;
}
#region ISimpleGrainObserver Members
public void StateChanged(int a, int b)
{
this.logger.Debug("SimpleGrainObserver.StateChanged a={0} b={1}", a, b);
action?.Invoke(a, b, result);
}
#endregion
}
}
}
| |
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 MRTutorial.Identity.Client.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;
}
}
}
| |
using System;
using System.IO;
using log4net;
namespace Rhino.ServiceBus.Hosting
{
using System.Reflection;
using System.Text;
public class RemoteAppDomainHost
{
private readonly string boosterType;
private readonly string assemblyName;
private readonly string assemblyLocation;
private HostedService current;
private string configurationFile;
private string hostType = typeof (DefaultHost).FullName;
private string hostAsm = typeof (DefaultHost).Assembly.FullName;
public RemoteAppDomainHost(Assembly assembly, string configuration)
: this(assembly.Location, configuration)
{
}
public RemoteAppDomainHost(string assemblyPath, Type boosterType)
: this(assemblyPath, (string)null)
{
this.boosterType = boosterType.FullName;
}
public RemoteAppDomainHost(Type boosterType)
: this(boosterType.Assembly.Location, boosterType)
{
}
public RemoteAppDomainHost(string assemblyPath, string configuration)
{
configurationFile = configuration;
assemblyName = Path.GetFileNameWithoutExtension(assemblyPath);
assemblyLocation = GetAssemblyLocation(assemblyPath);
}
private static string GetAssemblyLocation(string assemblyPath)
{
if (Path.IsPathRooted(assemblyPath))
return Path.GetDirectoryName(assemblyPath);
var currentDirPath = Path.Combine(Environment.CurrentDirectory, assemblyPath);
if (File.Exists(currentDirPath))
return Path.GetDirectoryName(currentDirPath);
var basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyPath);
if (File.Exists(basePath))
return Path.GetDirectoryName(basePath);
// no idea, use the default
return Path.GetDirectoryName(assemblyPath);
}
protected string AssemblyName
{
get { return assemblyName; }
}
public IApplicationHost ApplicationHost { get { return current.ApplicationHost; } }
public void Start()
{
HostedService service = CreateNewAppDomain();
current = service;
try
{
service.Start();
}
catch (ReflectionTypeLoadException e)
{
var sb = new StringBuilder();
foreach (var exception in e.LoaderExceptions)
{
sb.AppendLine(exception.ToString());
}
throw new TypeLoadException(sb.ToString(), e);
}
}
private HostedService CreateNewAppDomain()
{
var appDomainSetup = new AppDomainSetup
{
ApplicationBase = assemblyLocation,
ApplicationName = assemblyName,
ConfigurationFile = ConfigurationFile,
ShadowCopyFiles = "true" //yuck
};
AppDomain appDomain = AppDomain.CreateDomain(assemblyName, null, appDomainSetup);
return CreateRemoteHost(appDomain);
}
protected virtual HostedService CreateRemoteHost(AppDomain appDomain)
{
object instance = appDomain.CreateInstanceAndUnwrap(hostAsm,
hostType);
var hoster = (IApplicationHost)instance;
if (boosterType != null)
hoster.SetBootStrapperTypeName(boosterType);
return new HostedService(hoster, assemblyName, appDomain);
}
private string ConfigurationFile
{
get
{
if (configurationFile != null)
return configurationFile;
configurationFile = Path.Combine(assemblyLocation, assemblyName + ".dll.config");
if (File.Exists(configurationFile) == false)
configurationFile = Path.Combine(assemblyLocation, assemblyName + ".exe.config");
return configurationFile;
}
}
public void Close()
{
if (current != null)
current.Stop();
}
#region Nested type: HostedService
protected class HostedService
{
private readonly IApplicationHost hoster;
private readonly string assembly;
private readonly AppDomain appDomain;
private readonly ILog log = LogManager.GetLogger(typeof (HostedService));
public IApplicationHost ApplicationHost { get { return hoster; } }
public HostedService(IApplicationHost hoster, string assembly, AppDomain appDomain)
{
this.hoster = hoster;
this.assembly = assembly;
this.appDomain = appDomain;
}
public void Stop()
{
hoster.Dispose();
try
{
AppDomain.Unload(appDomain);
}
catch (Exception e)
{
log.Error(
"Could not unload app domain, it is likely that there is a running thread that could not be aborted", e);
}
}
public void Start()
{
hoster.Start(assembly);
}
public void InitialDeployment(string user)
{
hoster.InitialDeployment(assembly, user);
}
}
#endregion
public void InitialDeployment(string user)
{
HostedService service = CreateNewAppDomain();
current = service;
service.InitialDeployment(user);
}
public RemoteAppDomainHost SetHostType(Type host)
{
hostType = host.FullName;
hostAsm = host.Assembly.FullName;
return this;
}
public void SetHostType(string hostTypeName)
{
var parts = hostTypeName.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
if(parts.Length!=2)
throw new InvalidOperationException("Could not parse host name");
hostType = parts[0].Trim();
hostAsm = parts[1].Trim();
}
public RemoteAppDomainHost Configuration(string configFile)
{
configurationFile = configFile;
return this;
}
}
}
| |
// 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;
/// <summary>
/// ToInt16(System.Int64)
/// </summary>
public class ConvertToInt16_8
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify methos ToInt16(random).");
try
{
Int16 random = TestLibrary.Generator.GetInt16(-55);
Int16 actual = Convert.ToInt16((Int64)random);
Int16 expected = random;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt16(0)");
try
{
Int64 i = 0;
Int16 actual = Convert.ToInt16(i);
Int16 expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt16(int16.max)");
try
{
Int64 i = Int16.MaxValue;
Int16 actual = Convert.ToInt16(i);
Int16 expected = Int16.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt16(int16.min)");
try
{
Int64 i = Int16.MinValue;
Int16 actual = Convert.ToInt16(i);
Int16 expected = Int16.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException is not thrown.");
try
{
Int64 i = Int16.MaxValue + 1;
Int16 r = Convert.ToInt16(i);
TestLibrary.TestFramework.LogError("101.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: OverflowException is not thrown.");
try
{
Int64 i = Int16.MinValue - 1;
Int16 r = Convert.ToInt16(i);
TestLibrary.TestFramework.LogError("102.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ConvertToInt16_8 test = new ConvertToInt16_8();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt16_8");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using System;
using System.Collections.Generic;
namespace AldursLab.WurmApi.PersistentObjects
{
class PersistentCollection : IPersistentCollection
{
readonly string collectionId;
readonly IPersistenceStrategy persistenceStrategy;
readonly ISerializationStrategy serializationStrategy;
readonly IObjectDeserializationErrorHandlingStrategy deserializationErrorHandlingStrategy;
readonly Dictionary<string, Persistent> objects = new Dictionary<string, Persistent>();
internal PersistentCollection(string collectionId, IPersistenceStrategy persistenceStrategy,
ISerializationStrategy serializationStrategy,
IObjectDeserializationErrorHandlingStrategy deserializationErrorHandlingStrategy)
{
this.collectionId = collectionId;
this.persistenceStrategy = persistenceStrategy;
this.serializationStrategy = serializationStrategy;
this.deserializationErrorHandlingStrategy = deserializationErrorHandlingStrategy;
}
internal void SaveChanged()
{
Save(false);
}
internal void SaveAll()
{
Save(true);
}
void Save(bool all)
{
foreach (var persistent in objects)
{
if (all || persistent.Value.HasChanged)
{
var data = persistent.Value.GetSerializedData(serializationStrategy);
persistenceStrategy.Save(persistent.Key, collectionId, data);
persistent.Value.HasChanged = false;
}
}
}
public IPersistent<TEntity> GetObject<TEntity>(string objectId)
where TEntity : Entity, new()
{
Persistent persistent;
if (objects.TryGetValue(objectId, out persistent))
{
var castObj = persistent as Persistent<TEntity>;
if (castObj == null)
{
var type = persistent.GetType();
throw new InvalidOperationException(
string.Format(
"Previously resolved Persistent<T> is of entity type different than requested, requested type: {0}, actual type: {1}",
typeof(Persistent<TEntity>).FullName, type.FullName));
}
return castObj;
}
Persistent<TEntity> obj = null;
bool retry;
int currentRetry = 0;
int retryMax = 100;
do
{
var resolver = new ObjectResolver<TEntity>(objectId, collectionId, persistenceStrategy,
serializationStrategy, deserializationErrorHandlingStrategy);
try
{
obj = resolver.GetObject();
retry = false;
}
catch (RetryException)
{
if (retryMax == currentRetry)
{
throw new InvalidOperationException(string.Format("Maximum retry count reached ({0})", retryMax));
}
retry = true;
currentRetry++;
}
} while (retry);
objects.Add(objectId, obj);
return obj;
}
class ObjectResolver<TEntity> where TEntity : Entity, new()
{
readonly string objectId;
readonly string collectionId;
readonly IPersistenceStrategy persistenceStrategy;
readonly ISerializationStrategy serializationStrategy;
readonly IObjectDeserializationErrorHandlingStrategy objectDeserializationErrorHandlingStrategy;
public ObjectResolver(string objectId, string collectionId, IPersistenceStrategy persistenceStrategy,
ISerializationStrategy serializationStrategy,
IObjectDeserializationErrorHandlingStrategy objectDeserializationErrorHandlingStrategy)
{
if (objectId == null) throw new ArgumentNullException(nameof(objectId));
if (collectionId == null) throw new ArgumentNullException(nameof(collectionId));
if (persistenceStrategy == null) throw new ArgumentNullException(nameof(persistenceStrategy));
if (serializationStrategy == null) throw new ArgumentNullException(nameof(serializationStrategy));
if (objectDeserializationErrorHandlingStrategy == null)
throw new ArgumentNullException(nameof(objectDeserializationErrorHandlingStrategy));
this.objectId = objectId;
this.collectionId = collectionId;
this.persistenceStrategy = persistenceStrategy;
this.serializationStrategy = serializationStrategy;
this.objectDeserializationErrorHandlingStrategy = objectDeserializationErrorHandlingStrategy;
}
public Persistent<TEntity> GetObject()
{
var o = new Persistent<TEntity>(objectId);
var data = persistenceStrategy.TryLoad(objectId, collectionId);
if (data == null)
{
// data does not exist, return new with default
return o;
}
try
{
o.Entity = serializationStrategy.Deserialize<TEntity>(data);
}
catch (DeserializationErrorsException<TEntity> exception)
{
var errorContext = new ErrorContext(exception.Errors, persistenceStrategy, collectionId,
objectId);
objectDeserializationErrorHandlingStrategy.Handle(errorContext);
if (errorContext.Decision == Decision.DoNotIgnoreAndRethrowTheException)
{
throw;
}
else if (errorContext.Decision == Decision.IgnoreErrorsAndReturnDefaultsForMissingData)
{
o.Entity = exception.DeserializedFallbackEntity;
return o;
}
else if (errorContext.Decision == Decision.RetryDeserialization)
{
throw new RetryException();
}
else
{
throw new InvalidOperationException("Unknown Decision: " + errorContext.Decision);
}
}
if (o.Entity.ObjectId != objectId)
{
var errorContext = new ErrorContext(
new[]
{
new DeserializationErrorDetails()
{
DeserializationErrorKind = DeserializationErrorKind.ObjectIdMismatch
}
},
persistenceStrategy, collectionId, objectId);
objectDeserializationErrorHandlingStrategy.Handle(errorContext);
if (errorContext.Decision == Decision.DoNotIgnoreAndRethrowTheException)
{
throw new InvalidOperationException(
string.Format(
"Deserialized entity objectId {0} is different than requested objectId {1}",
o.Entity.ObjectId, objectId));
}
else if (errorContext.Decision == Decision.IgnoreErrorsAndReturnDefaultsForMissingData)
{
o.Entity.ObjectId = objectId;
}
else if (errorContext.Decision == Decision.RetryDeserialization)
{
throw new RetryException();
}
else
{
throw new InvalidOperationException("Unknown Decision: " + errorContext.Decision);
}
}
return o;
}
}
[Serializable]
public class RetryException : Exception
{
}
}
}
| |
// 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;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Collections;
using System.Collections.Specialized;
internal class XmlAttributeComparer : IComparer
{
public int Compare(object o1, object o2)
{
XmlAttribute a1 = (XmlAttribute)o1;
XmlAttribute a2 = (XmlAttribute)o2;
int ns = string.Compare(a1.NamespaceURI, a2.NamespaceURI, StringComparison.Ordinal);
if (ns == 0)
{
return string.Compare(a1.Name, a2.Name, StringComparison.Ordinal);
}
return ns;
}
}
internal class XmlFacetComparer : IComparer
{
public int Compare(object o1, object o2)
{
XmlSchemaFacet f1 = (XmlSchemaFacet)o1;
XmlSchemaFacet f2 = (XmlSchemaFacet)o2;
return string.Compare(f1.GetType().Name + ":" + f1.Value, f2.GetType().Name + ":" + f2.Value, StringComparison.Ordinal);
}
}
internal class QNameComparer : IComparer
{
public int Compare(object o1, object o2)
{
XmlQualifiedName qn1 = (XmlQualifiedName)o1;
XmlQualifiedName qn2 = (XmlQualifiedName)o2;
int ns = string.Compare(qn1.Namespace, qn2.Namespace, StringComparison.Ordinal);
if (ns == 0)
{
return string.Compare(qn1.Name, qn2.Name, StringComparison.Ordinal);
}
return ns;
}
}
internal class XmlSchemaObjectComparer : IComparer
{
private readonly QNameComparer _comparer = new QNameComparer();
public int Compare(object o1, object o2)
{
return _comparer.Compare(NameOf((XmlSchemaObject)o1), NameOf((XmlSchemaObject)o2));
}
internal static XmlQualifiedName NameOf(XmlSchemaObject o)
{
if (o is XmlSchemaAttribute)
{
return ((XmlSchemaAttribute)o).QualifiedName;
}
else if (o is XmlSchemaAttributeGroup)
{
return ((XmlSchemaAttributeGroup)o).QualifiedName;
}
else if (o is XmlSchemaComplexType)
{
return ((XmlSchemaComplexType)o).QualifiedName;
}
else if (o is XmlSchemaSimpleType)
{
return ((XmlSchemaSimpleType)o).QualifiedName;
}
else if (o is XmlSchemaElement)
{
return ((XmlSchemaElement)o).QualifiedName;
}
else if (o is XmlSchemaGroup)
{
return ((XmlSchemaGroup)o).QualifiedName;
}
else if (o is XmlSchemaGroupRef)
{
return ((XmlSchemaGroupRef)o).RefName;
}
else if (o is XmlSchemaNotation)
{
return ((XmlSchemaNotation)o).QualifiedName;
}
else if (o is XmlSchemaSequence)
{
XmlSchemaSequence s = (XmlSchemaSequence)o;
if (s.Items.Count == 0)
return new XmlQualifiedName(".sequence", Namespace(o));
return NameOf(s.Items[0]);
}
else if (o is XmlSchemaAll)
{
XmlSchemaAll a = (XmlSchemaAll)o;
if (a.Items.Count == 0)
return new XmlQualifiedName(".all", Namespace(o));
return NameOf(a.Items);
}
else if (o is XmlSchemaChoice)
{
XmlSchemaChoice c = (XmlSchemaChoice)o;
if (c.Items.Count == 0)
return new XmlQualifiedName(".choice", Namespace(o));
return NameOf(c.Items);
}
else if (o is XmlSchemaAny)
{
return new XmlQualifiedName("*", SchemaObjectWriter.ToString(((XmlSchemaAny)o).NamespaceList));
}
else if (o is XmlSchemaIdentityConstraint)
{
return ((XmlSchemaIdentityConstraint)o).QualifiedName;
}
return new XmlQualifiedName("?", Namespace(o));
}
internal static XmlQualifiedName NameOf(XmlSchemaObjectCollection items)
{
ArrayList list = new ArrayList();
for (int i = 0; i < items.Count; i++)
{
list.Add(NameOf(items[i]));
}
list.Sort(new QNameComparer());
return (XmlQualifiedName)list[0];
}
internal static string Namespace(XmlSchemaObject o)
{
while (o != null && !(o is XmlSchema))
{
o = o.Parent;
}
return o == null ? "" : ((XmlSchema)o).TargetNamespace;
}
}
internal class SchemaObjectWriter
{
private readonly StringBuilder _w = new StringBuilder();
private int _indentLevel = -1;
private void WriteIndent()
{
for (int i = 0; i < _indentLevel; i++)
{
_w.Append(" ");
}
}
protected void WriteAttribute(string localName, string ns, string value)
{
if (value == null || value.Length == 0)
return;
_w.Append(",");
_w.Append(ns);
if (ns != null && ns.Length != 0)
_w.Append(":");
_w.Append(localName);
_w.Append("=");
_w.Append(value);
}
protected void WriteAttribute(string localName, string ns, XmlQualifiedName value)
{
if (value.IsEmpty)
return;
WriteAttribute(localName, ns, value.ToString());
}
protected void WriteStartElement(string name)
{
NewLine();
_indentLevel++;
_w.Append("[");
_w.Append(name);
}
protected void WriteEndElement()
{
_w.Append("]");
_indentLevel--;
}
protected void NewLine()
{
_w.Append(Environment.NewLine);
WriteIndent();
}
protected string GetString()
{
return _w.ToString();
}
private void WriteAttribute(XmlAttribute a)
{
if (a.Value != null)
{
WriteAttribute(a.Name, a.NamespaceURI, a.Value);
}
}
private void WriteAttributes(XmlAttribute[] a, XmlSchemaObject o)
{
if (a == null) return;
ArrayList attrs = new ArrayList();
for (int i = 0; i < a.Length; i++)
{
attrs.Add(a[i]);
}
attrs.Sort(new XmlAttributeComparer());
for (int i = 0; i < attrs.Count; i++)
{
XmlAttribute attribute = (XmlAttribute)attrs[i];
WriteAttribute(attribute);
}
}
internal static string ToString(NamespaceList list)
{
if (list == null)
return null;
switch (list.Type)
{
case NamespaceList.ListType.Any:
return "##any";
case NamespaceList.ListType.Other:
return "##other";
case NamespaceList.ListType.Set:
ArrayList ns = new ArrayList();
foreach (string s in list.Enumerate)
{
ns.Add(s);
}
ns.Sort();
StringBuilder sb = new StringBuilder();
bool first = true;
foreach (string s in ns)
{
if (first)
{
first = false;
}
else
{
sb.Append(" ");
}
if (s.Length == 0)
{
sb.Append("##local");
}
else
{
sb.Append(s);
}
}
return sb.ToString();
default:
return list.ToString();
}
}
internal string WriteXmlSchemaObject(XmlSchemaObject o)
{
if (o == null) return string.Empty;
Write3_XmlSchemaObject((XmlSchemaObject)o);
return GetString();
}
private void WriteSortedItems(XmlSchemaObjectCollection items)
{
if (items == null) return;
ArrayList list = new ArrayList();
for (int i = 0; i < items.Count; i++)
{
list.Add(items[i]);
}
list.Sort(new XmlSchemaObjectComparer());
for (int i = 0; i < list.Count; i++)
{
Write3_XmlSchemaObject((XmlSchemaObject)list[i]);
}
}
private void Write1_XmlSchemaAttribute(XmlSchemaAttribute o)
{
if ((object)o == null) return;
WriteStartElement("attribute");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
WriteAttribute(@"default", @"", ((string)o.@DefaultValue));
WriteAttribute(@"fixed", @"", ((string)o.@FixedValue));
if (o.Parent != null && !(o.Parent is XmlSchema))
{
if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0)
{
WriteAttribute(@"form", @"", "qualified");
}
else
{
WriteAttribute(@"form", @"", "unqualified");
}
}
WriteAttribute(@"name", @"", ((string)o.@Name));
if (!o.RefName.IsEmpty)
{
WriteAttribute("ref", "", o.RefName);
}
else if (!o.SchemaTypeName.IsEmpty)
{
WriteAttribute("type", "", o.SchemaTypeName);
}
XmlSchemaUse use = o.Use == XmlSchemaUse.None ? XmlSchemaUse.Optional : o.Use;
WriteAttribute(@"use", @"", Write30_XmlSchemaUse(use));
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@SchemaType);
WriteEndElement();
}
private void Write3_XmlSchemaObject(XmlSchemaObject o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
if (t == typeof(XmlSchemaComplexType))
{
Write35_XmlSchemaComplexType((XmlSchemaComplexType)o);
return;
}
else if (t == typeof(XmlSchemaSimpleType))
{
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o);
return;
}
else if (t == typeof(XmlSchemaElement))
{
Write46_XmlSchemaElement((XmlSchemaElement)o);
return;
}
else if (t == typeof(XmlSchemaAppInfo))
{
Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)o);
return;
}
else if (t == typeof(XmlSchemaDocumentation))
{
Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)o);
return;
}
else if (t == typeof(XmlSchemaAnnotation))
{
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o);
return;
}
else if (t == typeof(XmlSchemaGroup))
{
Write57_XmlSchemaGroup((XmlSchemaGroup)o);
return;
}
else if (t == typeof(XmlSchemaXPath))
{
Write49_XmlSchemaXPath("xpath", "", (XmlSchemaXPath)o);
return;
}
else if (t == typeof(XmlSchemaIdentityConstraint))
{
Write48_XmlSchemaIdentityConstraint((XmlSchemaIdentityConstraint)o);
return;
}
else if (t == typeof(XmlSchemaUnique))
{
Write51_XmlSchemaUnique((XmlSchemaUnique)o);
return;
}
else if (t == typeof(XmlSchemaKeyref))
{
Write50_XmlSchemaKeyref((XmlSchemaKeyref)o);
return;
}
else if (t == typeof(XmlSchemaKey))
{
Write47_XmlSchemaKey((XmlSchemaKey)o);
return;
}
else if (t == typeof(XmlSchemaGroupRef))
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o);
return;
}
else if (t == typeof(XmlSchemaAny))
{
Write53_XmlSchemaAny((XmlSchemaAny)o);
return;
}
else if (t == typeof(XmlSchemaSequence))
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o);
return;
}
else if (t == typeof(XmlSchemaChoice))
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o);
return;
}
else if (t == typeof(XmlSchemaAll))
{
Write43_XmlSchemaAll((XmlSchemaAll)o);
return;
}
else if (t == typeof(XmlSchemaComplexContentRestriction))
{
Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o);
return;
}
else if (t == typeof(XmlSchemaComplexContentExtension))
{
Write42_XmlSchemaComplexContentExtension((XmlSchemaComplexContentExtension)o);
return;
}
else if (t == typeof(XmlSchemaSimpleContentRestriction))
{
Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o);
return;
}
else if (t == typeof(XmlSchemaSimpleContentExtension))
{
Write38_XmlSchemaSimpleContentExtension((XmlSchemaSimpleContentExtension)o);
return;
}
else if (t == typeof(XmlSchemaComplexContent))
{
Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o);
return;
}
else if (t == typeof(XmlSchemaSimpleContent))
{
Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o);
return;
}
else if (t == typeof(XmlSchemaAnyAttribute))
{
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o);
return;
}
else if (t == typeof(XmlSchemaAttributeGroupRef))
{
Write32_XmlSchemaAttributeGroupRef((XmlSchemaAttributeGroupRef)o);
return;
}
else if (t == typeof(XmlSchemaAttributeGroup))
{
Write31_XmlSchemaAttributeGroup((XmlSchemaAttributeGroup)o);
return;
}
else if (t == typeof(XmlSchemaSimpleTypeRestriction))
{
Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o);
return;
}
else if (t == typeof(XmlSchemaSimpleTypeList))
{
Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o);
return;
}
else if (t == typeof(XmlSchemaSimpleTypeUnion))
{
Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o);
return;
}
else if (t == typeof(XmlSchemaAttribute))
{
Write1_XmlSchemaAttribute((XmlSchemaAttribute)o);
return;
}
}
private void Write5_XmlSchemaAnnotation(XmlSchemaAnnotation o)
{
if ((object)o == null) return;
WriteStartElement("annotation");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
System.Xml.Schema.XmlSchemaObjectCollection a = (System.Xml.Schema.XmlSchemaObjectCollection)o.@Items;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
XmlSchemaObject ai = (XmlSchemaObject)a[ia];
if (ai is XmlSchemaAppInfo)
{
Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)ai);
}
else if (ai is XmlSchemaDocumentation)
{
Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)ai);
}
}
}
WriteEndElement();
}
private void Write6_XmlSchemaDocumentation(XmlSchemaDocumentation o)
{
if ((object)o == null) return;
WriteStartElement("documentation");
WriteAttribute(@"source", @"", ((string)o.@Source));
WriteAttribute(@"lang", @"http://www.w3.org/XML/1998/namespace", ((string)o.@Language));
XmlNode[] a = (XmlNode[])o.@Markup;
if (a != null)
{
for (int ia = 0; ia < a.Length; ia++)
{
XmlNode ai = (XmlNode)a[ia];
WriteStartElement("node");
WriteAttribute("xml", "", ai.OuterXml);
}
}
WriteEndElement();
}
private void Write7_XmlSchemaAppInfo(XmlSchemaAppInfo o)
{
if ((object)o == null) return;
WriteStartElement("appinfo");
WriteAttribute("source", "", o.Source);
XmlNode[] a = (XmlNode[])o.@Markup;
if (a != null)
{
for (int ia = 0; ia < a.Length; ia++)
{
XmlNode ai = (XmlNode)a[ia];
WriteStartElement("node");
WriteAttribute("xml", "", ai.OuterXml);
}
}
WriteEndElement();
}
private void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType o)
{
if ((object)o == null) return;
WriteStartElement("simpleType");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
WriteAttribute(@"name", @"", ((string)o.@Name));
WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved));
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@Content is XmlSchemaSimpleTypeUnion)
{
Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o.@Content);
}
else if (o.@Content is XmlSchemaSimpleTypeRestriction)
{
Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o.@Content);
}
else if (o.@Content is XmlSchemaSimpleTypeList)
{
Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o.@Content);
}
WriteEndElement();
}
private string Write11_XmlSchemaDerivationMethod(XmlSchemaDerivationMethod v)
{
return v.ToString();
}
private void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion o)
{
if ((object)o == null) return;
WriteStartElement("union");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (o.MemberTypes != null)
{
ArrayList list = new ArrayList();
for (int i = 0; i < o.MemberTypes.Length; i++)
{
list.Add(o.MemberTypes[i]);
}
list.Sort(new QNameComparer());
_w.Append(",");
_w.Append("memberTypes=");
for (int i = 0; i < list.Count; i++)
{
XmlQualifiedName q = (XmlQualifiedName)list[i];
_w.Append(q.ToString());
_w.Append(",");
}
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteSortedItems(o.@BaseTypes);
WriteEndElement();
}
private void Write14_XmlSchemaSimpleTypeList(XmlSchemaSimpleTypeList o)
{
if ((object)o == null) return;
WriteStartElement("list");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (!o.@ItemTypeName.IsEmpty)
{
WriteAttribute(@"itemType", @"", o.@ItemTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@ItemType);
WriteEndElement();
}
private void Write15_XmlSchemaSimpleTypeRestriction(XmlSchemaSimpleTypeRestriction o)
{
if ((object)o == null) return;
WriteStartElement("restriction");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@BaseType);
WriteFacets(o.Facets);
WriteEndElement();
}
private void WriteFacets(XmlSchemaObjectCollection facets)
{
if (facets == null) return;
ArrayList a = new ArrayList();
for (int i = 0; i < facets.Count; i++)
{
a.Add(facets[i]);
}
a.Sort(new XmlFacetComparer());
for (int ia = 0; ia < a.Count; ia++)
{
XmlSchemaObject ai = (XmlSchemaObject)a[ia];
if (ai is XmlSchemaMinExclusiveFacet)
{
Write_XmlSchemaFacet("minExclusive", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMaxInclusiveFacet)
{
Write_XmlSchemaFacet("maxInclusive", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMaxExclusiveFacet)
{
Write_XmlSchemaFacet("maxExclusive", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMinInclusiveFacet)
{
Write_XmlSchemaFacet("minInclusive", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaLengthFacet)
{
Write_XmlSchemaFacet("length", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaEnumerationFacet)
{
Write_XmlSchemaFacet("enumeration", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMinLengthFacet)
{
Write_XmlSchemaFacet("minLength", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaPatternFacet)
{
Write_XmlSchemaFacet("pattern", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaTotalDigitsFacet)
{
Write_XmlSchemaFacet("totalDigits", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMaxLengthFacet)
{
Write_XmlSchemaFacet("maxLength", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaWhiteSpaceFacet)
{
Write_XmlSchemaFacet("whiteSpace", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaFractionDigitsFacet)
{
Write_XmlSchemaFacet("fractionDigit", (XmlSchemaFacet)ai);
}
}
}
private void Write_XmlSchemaFacet(string name, XmlSchemaFacet o)
{
if ((object)o == null) return;
WriteStartElement(name);
WriteAttribute("id", "", o.Id);
WriteAttribute("value", "", o.Value);
if (o.IsFixed)
{
WriteAttribute(@"fixed", @"", XmlConvert.ToString(o.IsFixed));
}
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteEndElement();
}
private string Write30_XmlSchemaUse(XmlSchemaUse v)
{
string s = null;
switch (v)
{
case XmlSchemaUse.@Optional: s = @"optional"; break;
case XmlSchemaUse.@Prohibited: s = @"prohibited"; break;
case XmlSchemaUse.@Required: s = @"required"; break;
default: break;
}
return s;
}
private void Write31_XmlSchemaAttributeGroup(XmlSchemaAttributeGroup o)
{
if ((object)o == null) return;
WriteStartElement("attributeGroup");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttribute(@"name", @"", ((string)o.@Name));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute);
WriteEndElement();
}
private void Write32_XmlSchemaAttributeGroupRef(XmlSchemaAttributeGroupRef o)
{
if ((object)o == null) return;
WriteStartElement("attributeGroup");
WriteAttribute(@"id", @"", ((string)o.@Id));
if (!o.RefName.IsEmpty)
{
WriteAttribute("ref", "", o.RefName);
}
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteEndElement();
}
private void Write33_XmlSchemaAnyAttribute(XmlSchemaAnyAttribute o)
{
if ((object)o == null) return;
WriteStartElement("anyAttribute");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttribute("namespace", "", ToString(o.NamespaceList));
XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents;
WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteEndElement();
}
private string Write34_XmlSchemaContentProcessing(XmlSchemaContentProcessing v)
{
string s = null;
switch (v)
{
case XmlSchemaContentProcessing.@Skip: s = @"skip"; break;
case XmlSchemaContentProcessing.@Lax: s = @"lax"; break;
case XmlSchemaContentProcessing.@Strict: s = @"strict"; break;
default: break;
}
return s;
}
private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o)
{
if ((object)o == null) return;
WriteStartElement("complexType");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttribute(@"name", @"", ((string)o.@Name));
WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved));
if (((bool)o.@IsAbstract) != false)
{
WriteAttribute(@"abstract", @"", XmlConvert.ToString((bool)((bool)o.@IsAbstract)));
}
WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved));
if (((bool)o.@IsMixed) != false)
{
WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed)));
}
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@ContentModel is XmlSchemaComplexContent)
{
Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o.@ContentModel);
}
else if (o.@ContentModel is XmlSchemaSimpleContent)
{
Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o.@ContentModel);
}
if (o.@Particle is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle);
}
else if (o.@Particle is XmlSchemaGroupRef)
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle);
}
else if (o.@Particle is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle);
}
else if (o.@Particle is XmlSchemaAll)
{
Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle);
}
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute);
WriteEndElement();
}
private void Write36_XmlSchemaSimpleContent(XmlSchemaSimpleContent o)
{
if ((object)o == null) return;
WriteStartElement("simpleContent");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@Content is XmlSchemaSimpleContentRestriction)
{
Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o.@Content);
}
else if (o.@Content is XmlSchemaSimpleContentExtension)
{
Write38_XmlSchemaSimpleContentExtension((XmlSchemaSimpleContentExtension)o.@Content);
}
WriteEndElement();
}
private void Write38_XmlSchemaSimpleContentExtension(XmlSchemaSimpleContentExtension o)
{
if ((object)o == null) return;
WriteStartElement("extension");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute);
WriteEndElement();
}
private void Write40_XmlSchemaSimpleContentRestriction(XmlSchemaSimpleContentRestriction o)
{
if ((object)o == null) return;
WriteStartElement("restriction");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@BaseType);
WriteFacets(o.Facets);
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute);
WriteEndElement();
}
private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent o)
{
if ((object)o == null) return;
WriteStartElement("complexContent");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed)));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@Content is XmlSchemaComplexContentRestriction)
{
Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o.@Content);
}
else if (o.@Content is XmlSchemaComplexContentExtension)
{
Write42_XmlSchemaComplexContentExtension((XmlSchemaComplexContentExtension)o.@Content);
}
WriteEndElement();
}
private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExtension o)
{
if ((object)o == null) return;
WriteStartElement("extension");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@Particle is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle);
}
else if (o.@Particle is XmlSchemaGroupRef)
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle);
}
else if (o.@Particle is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle);
}
else if (o.@Particle is XmlSchemaAll)
{
Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle);
}
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute);
WriteEndElement();
}
private void Write43_XmlSchemaAll(XmlSchemaAll o)
{
if ((object)o == null) return;
WriteStartElement("all");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteSortedItems(o.@Items);
WriteEndElement();
}
private void Write46_XmlSchemaElement(XmlSchemaElement o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
WriteStartElement("element");
WriteAttribute(@"id", @"", o.Id);
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
if (((bool)o.@IsAbstract) != false)
{
WriteAttribute(@"abstract", @"", XmlConvert.ToString((bool)((bool)o.@IsAbstract)));
}
WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved));
WriteAttribute(@"default", @"", o.DefaultValue);
WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved));
WriteAttribute(@"fixed", @"", o.FixedValue);
if (o.Parent != null && !(o.Parent is XmlSchema))
{
if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0)
{
WriteAttribute(@"form", @"", "qualified");
}
else
{
WriteAttribute(@"form", @"", "unqualified");
}
}
if (o.Name != null && o.Name.Length != 0)
{
WriteAttribute(@"name", @"", o.Name);
}
if (o.IsNillable)
{
WriteAttribute(@"nillable", @"", XmlConvert.ToString(o.IsNillable));
}
if (!o.SubstitutionGroup.IsEmpty)
{
WriteAttribute("substitutionGroup", "", o.SubstitutionGroup);
}
if (!o.RefName.IsEmpty)
{
WriteAttribute("ref", "", o.RefName);
}
else if (!o.SchemaTypeName.IsEmpty)
{
WriteAttribute("type", "", o.SchemaTypeName);
}
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation(o.Annotation);
if (o.SchemaType is XmlSchemaComplexType)
{
Write35_XmlSchemaComplexType((XmlSchemaComplexType)o.SchemaType);
}
else if (o.SchemaType is XmlSchemaSimpleType)
{
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.SchemaType);
}
WriteSortedItems(o.Constraints);
WriteEndElement();
}
private void Write47_XmlSchemaKey(XmlSchemaKey o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
WriteStartElement("key");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttribute(@"name", @"", ((string)o.@Name));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath)o.@Selector);
{
XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]);
}
}
}
WriteEndElement();
}
private void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
if (t == typeof(XmlSchemaUnique))
{
Write51_XmlSchemaUnique((XmlSchemaUnique)o);
return;
}
else if (t == typeof(XmlSchemaKeyref))
{
Write50_XmlSchemaKeyref((XmlSchemaKeyref)o);
return;
}
else if (t == typeof(XmlSchemaKey))
{
Write47_XmlSchemaKey((XmlSchemaKey)o);
return;
}
}
private void Write49_XmlSchemaXPath(string name, string ns, XmlSchemaXPath o)
{
if ((object)o == null) return;
WriteStartElement(name);
WriteAttribute(@"id", @"", o.@Id);
WriteAttribute(@"xpath", @"", o.@XPath);
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteEndElement();
}
private void Write50_XmlSchemaKeyref(XmlSchemaKeyref o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
WriteStartElement("keyref");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttribute(@"name", @"", ((string)o.@Name));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
// UNDONE compare reference here
WriteAttribute(@"refer", @"", o.@Refer);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath)o.@Selector);
{
XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]);
}
}
}
WriteEndElement();
}
private void Write51_XmlSchemaUnique(XmlSchemaUnique o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
WriteStartElement("unique");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttribute(@"name", @"", ((string)o.@Name));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
Write49_XmlSchemaXPath("selector", "", (XmlSchemaXPath)o.@Selector);
XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
Write49_XmlSchemaXPath("field", "", (XmlSchemaXPath)a[ia]);
}
}
WriteEndElement();
}
private void Write52_XmlSchemaChoice(XmlSchemaChoice o)
{
if ((object)o == null) return;
System.Type t = o.GetType();
WriteStartElement("choice");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteSortedItems(o.@Items);
WriteEndElement();
}
private void Write53_XmlSchemaAny(XmlSchemaAny o)
{
if ((object)o == null) return;
WriteStartElement("any");
WriteAttribute(@"id", @"", o.@Id);
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
WriteAttribute(@"namespace", @"", ToString(o.NamespaceList));
XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents;
WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteEndElement();
}
private void Write54_XmlSchemaSequence(XmlSchemaSequence o)
{
if ((object)o == null) return;
WriteStartElement("sequence");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Items;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
XmlSchemaObject ai = (XmlSchemaObject)a[ia];
if (ai is XmlSchemaAny)
{
Write53_XmlSchemaAny((XmlSchemaAny)ai);
}
else if (ai is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)ai);
}
else if (ai is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)ai);
}
else if (ai is XmlSchemaElement)
{
Write46_XmlSchemaElement((XmlSchemaElement)ai);
}
else if (ai is XmlSchemaGroupRef)
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)ai);
}
}
}
WriteEndElement();
}
private void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef o)
{
if ((object)o == null) return;
WriteStartElement("group");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs));
if (!o.RefName.IsEmpty)
{
WriteAttribute("ref", "", o.RefName);
}
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
WriteEndElement();
}
private void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentRestriction o)
{
if ((object)o == null) return;
WriteStartElement("restriction");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@Particle is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle);
}
else if (o.@Particle is XmlSchemaGroupRef)
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle);
}
else if (o.@Particle is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle);
}
else if (o.@Particle is XmlSchemaAll)
{
Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle);
}
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute);
WriteEndElement();
}
private void Write57_XmlSchemaGroup(XmlSchemaGroup o)
{
if ((object)o == null) return;
WriteStartElement("group");
WriteAttribute(@"id", @"", ((string)o.@Id));
WriteAttribute(@"name", @"", ((string)o.@Name));
WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
if (o.@Particle is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle);
}
else if (o.@Particle is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle);
}
else if (o.@Particle is XmlSchemaAll)
{
Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle);
}
WriteEndElement();
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A collection of music tracks in playlist form.
/// </summary>
public class MusicPlaylist_Core : TypeCore, ICreativeWork
{
public MusicPlaylist_Core()
{
this._TypeId = 177;
this._Id = "MusicPlaylist";
this._Schema_Org_Url = "http://schema.org/MusicPlaylist";
string label = "";
GetLabel(out label, "MusicPlaylist", typeof(MusicPlaylist_Core));
this._Label = label;
this._Ancestors = new int[]{266,78};
this._SubTypes = new int[]{174};
this._SuperTypes = new int[]{78};
this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,145,223};
}
/// <summary>
/// The subject matter of the content.
/// </summary>
private About_Core about;
public About_Core About
{
get
{
return about;
}
set
{
about = value;
SetPropertyInstance(about);
}
}
/// <summary>
/// Specifies the Person that is legally accountable for the CreativeWork.
/// </summary>
private AccountablePerson_Core accountablePerson;
public AccountablePerson_Core AccountablePerson
{
get
{
return accountablePerson;
}
set
{
accountablePerson = value;
SetPropertyInstance(accountablePerson);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// A secondary title of the CreativeWork.
/// </summary>
private AlternativeHeadline_Core alternativeHeadline;
public AlternativeHeadline_Core AlternativeHeadline
{
get
{
return alternativeHeadline;
}
set
{
alternativeHeadline = value;
SetPropertyInstance(alternativeHeadline);
}
}
/// <summary>
/// The media objects that encode this creative work. This property is a synonym for encodings.
/// </summary>
private AssociatedMedia_Core associatedMedia;
public AssociatedMedia_Core AssociatedMedia
{
get
{
return associatedMedia;
}
set
{
associatedMedia = value;
SetPropertyInstance(associatedMedia);
}
}
/// <summary>
/// An embedded audio object.
/// </summary>
private Audio_Core audio;
public Audio_Core Audio
{
get
{
return audio;
}
set
{
audio = value;
SetPropertyInstance(audio);
}
}
/// <summary>
/// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely.
/// </summary>
private Author_Core author;
public Author_Core Author
{
get
{
return author;
}
set
{
author = value;
SetPropertyInstance(author);
}
}
/// <summary>
/// Awards won by this person or for this creative work.
/// </summary>
private Awards_Core awards;
public Awards_Core Awards
{
get
{
return awards;
}
set
{
awards = value;
SetPropertyInstance(awards);
}
}
/// <summary>
/// Comments, typically from users, on this CreativeWork.
/// </summary>
private Comment_Core comment;
public Comment_Core Comment
{
get
{
return comment;
}
set
{
comment = value;
SetPropertyInstance(comment);
}
}
/// <summary>
/// The location of the content.
/// </summary>
private ContentLocation_Core contentLocation;
public ContentLocation_Core ContentLocation
{
get
{
return contentLocation;
}
set
{
contentLocation = value;
SetPropertyInstance(contentLocation);
}
}
/// <summary>
/// Official rating of a piece of content\u2014for example,'MPAA PG-13'.
/// </summary>
private ContentRating_Core contentRating;
public ContentRating_Core ContentRating
{
get
{
return contentRating;
}
set
{
contentRating = value;
SetPropertyInstance(contentRating);
}
}
/// <summary>
/// A secondary contributor to the CreativeWork.
/// </summary>
private Contributor_Core contributor;
public Contributor_Core Contributor
{
get
{
return contributor;
}
set
{
contributor = value;
SetPropertyInstance(contributor);
}
}
/// <summary>
/// The party holding the legal copyright to the CreativeWork.
/// </summary>
private CopyrightHolder_Core copyrightHolder;
public CopyrightHolder_Core CopyrightHolder
{
get
{
return copyrightHolder;
}
set
{
copyrightHolder = value;
SetPropertyInstance(copyrightHolder);
}
}
/// <summary>
/// The year during which the claimed copyright for the CreativeWork was first asserted.
/// </summary>
private CopyrightYear_Core copyrightYear;
public CopyrightYear_Core CopyrightYear
{
get
{
return copyrightYear;
}
set
{
copyrightYear = value;
SetPropertyInstance(copyrightYear);
}
}
/// <summary>
/// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork.
/// </summary>
private Creator_Core creator;
public Creator_Core Creator
{
get
{
return creator;
}
set
{
creator = value;
SetPropertyInstance(creator);
}
}
/// <summary>
/// The date on which the CreativeWork was created.
/// </summary>
private DateCreated_Core dateCreated;
public DateCreated_Core DateCreated
{
get
{
return dateCreated;
}
set
{
dateCreated = value;
SetPropertyInstance(dateCreated);
}
}
/// <summary>
/// The date on which the CreativeWork was most recently modified.
/// </summary>
private DateModified_Core dateModified;
public DateModified_Core DateModified
{
get
{
return dateModified;
}
set
{
dateModified = value;
SetPropertyInstance(dateModified);
}
}
/// <summary>
/// Date of first broadcast/publication.
/// </summary>
private DatePublished_Core datePublished;
public DatePublished_Core DatePublished
{
get
{
return datePublished;
}
set
{
datePublished = value;
SetPropertyInstance(datePublished);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// A link to the page containing the comments of the CreativeWork.
/// </summary>
private DiscussionURL_Core discussionURL;
public DiscussionURL_Core DiscussionURL
{
get
{
return discussionURL;
}
set
{
discussionURL = value;
SetPropertyInstance(discussionURL);
}
}
/// <summary>
/// Specifies the Person who edited the CreativeWork.
/// </summary>
private Editor_Core editor;
public Editor_Core Editor
{
get
{
return editor;
}
set
{
editor = value;
SetPropertyInstance(editor);
}
}
/// <summary>
/// The media objects that encode this creative work
/// </summary>
private Encodings_Core encodings;
public Encodings_Core Encodings
{
get
{
return encodings;
}
set
{
encodings = value;
SetPropertyInstance(encodings);
}
}
/// <summary>
/// Genre of the creative work
/// </summary>
private Genre_Core genre;
public Genre_Core Genre
{
get
{
return genre;
}
set
{
genre = value;
SetPropertyInstance(genre);
}
}
/// <summary>
/// Headline of the article
/// </summary>
private Headline_Core headline;
public Headline_Core Headline
{
get
{
return headline;
}
set
{
headline = value;
SetPropertyInstance(headline);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a>
/// </summary>
private InLanguage_Core inLanguage;
public InLanguage_Core InLanguage
{
get
{
return inLanguage;
}
set
{
inLanguage = value;
SetPropertyInstance(inLanguage);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// Indicates whether this content is family friendly.
/// </summary>
private IsFamilyFriendly_Core isFamilyFriendly;
public IsFamilyFriendly_Core IsFamilyFriendly
{
get
{
return isFamilyFriendly;
}
set
{
isFamilyFriendly = value;
SetPropertyInstance(isFamilyFriendly);
}
}
/// <summary>
/// The keywords/tags used to describe this content.
/// </summary>
private Keywords_Core keywords;
public Keywords_Core Keywords
{
get
{
return keywords;
}
set
{
keywords = value;
SetPropertyInstance(keywords);
}
}
/// <summary>
/// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept.
/// </summary>
private Mentions_Core mentions;
public Mentions_Core Mentions
{
get
{
return mentions;
}
set
{
mentions = value;
SetPropertyInstance(mentions);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The number of tracks in this album or playlist.
/// </summary>
private NumTracks_Core numTracks;
public NumTracks_Core NumTracks
{
get
{
return numTracks;
}
set
{
numTracks = value;
SetPropertyInstance(numTracks);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// Specifies the Person or Organization that distributed the CreativeWork.
/// </summary>
private Provider_Core provider;
public Provider_Core Provider
{
get
{
return provider;
}
set
{
provider = value;
SetPropertyInstance(provider);
}
}
/// <summary>
/// The publisher of the creative work.
/// </summary>
private Publisher_Core publisher;
public Publisher_Core Publisher
{
get
{
return publisher;
}
set
{
publisher = value;
SetPropertyInstance(publisher);
}
}
/// <summary>
/// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork.
/// </summary>
private PublishingPrinciples_Core publishingPrinciples;
public PublishingPrinciples_Core PublishingPrinciples
{
get
{
return publishingPrinciples;
}
set
{
publishingPrinciples = value;
SetPropertyInstance(publishingPrinciples);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The Organization on whose behalf the creator was working.
/// </summary>
private SourceOrganization_Core sourceOrganization;
public SourceOrganization_Core SourceOrganization
{
get
{
return sourceOrganization;
}
set
{
sourceOrganization = value;
SetPropertyInstance(sourceOrganization);
}
}
/// <summary>
/// A thumbnail image relevant to the Thing.
/// </summary>
private ThumbnailURL_Core thumbnailURL;
public ThumbnailURL_Core ThumbnailURL
{
get
{
return thumbnailURL;
}
set
{
thumbnailURL = value;
SetPropertyInstance(thumbnailURL);
}
}
/// <summary>
/// A music recording (track)\u2014usually a single song.
/// </summary>
private Tracks_Core tracks;
public Tracks_Core Tracks
{
get
{
return tracks;
}
set
{
tracks = value;
SetPropertyInstance(tracks);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
/// <summary>
/// The version of the CreativeWork embodied by a specified resource.
/// </summary>
private Version_Core version;
public Version_Core Version
{
get
{
return version;
}
set
{
version = value;
SetPropertyInstance(version);
}
}
/// <summary>
/// An embedded video object.
/// </summary>
private Video_Core video;
public Video_Core Video
{
get
{
return video;
}
set
{
video = value;
SetPropertyInstance(video);
}
}
}
}
| |
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 Contoso.Provisioning.Services.SiteManager.AppWeb
{
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
}
}
| |
//
// 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 Microsoft.Azure.Management.Compute.Models;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet("New", "AzureRmContainerServiceConfig")]
[OutputType(typeof(ContainerService))]
public class NewAzureRmContainerServiceConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
{
[Parameter(
Mandatory = false,
Position = 0,
ValueFromPipelineByPropertyName = true)]
public string Location { get; set; }
[Parameter(
Mandatory = false,
Position = 1,
ValueFromPipelineByPropertyName = true)]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
Position = 2,
ValueFromPipelineByPropertyName = true)]
public ContainerServiceOchestratorTypes? OrchestratorType { get; set; }
[Parameter(
Mandatory = false,
Position = 3,
ValueFromPipelineByPropertyName = true)]
public int? MasterCount { get; set; }
[Parameter(
Mandatory = false,
Position = 4,
ValueFromPipelineByPropertyName = true)]
public string MasterDnsPrefix { get; set; }
[Parameter(
Mandatory = false,
Position = 5,
ValueFromPipelineByPropertyName = true)]
public ContainerServiceAgentPoolProfile[] AgentPoolProfile { get; set; }
[Parameter(
Mandatory = false,
Position = 6,
ValueFromPipelineByPropertyName = true)]
public string WindowsProfileAdminUsername { get; set; }
[Parameter(
Mandatory = false,
Position = 7,
ValueFromPipelineByPropertyName = true)]
public string WindowsProfileAdminPassword { get; set; }
[Parameter(
Mandatory = false,
Position = 8,
ValueFromPipelineByPropertyName = true)]
public string AdminUsername { get; set; }
[Parameter(
Mandatory = false,
Position = 9,
ValueFromPipelineByPropertyName = true)]
public string[] SshPublicKey { get; set; }
[Parameter(
Mandatory = false,
Position = 10,
ValueFromPipelineByPropertyName = true)]
public bool? VmDiagnosticsEnabled { get; set; }
protected override void ProcessRecord()
{
// OrchestratorProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceOrchestratorProfile vOrchestratorProfile = null;
// MasterProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile vMasterProfile = null;
// WindowsProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile vWindowsProfile = null;
// LinuxProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile vLinuxProfile = null;
// DiagnosticsProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceDiagnosticsProfile vDiagnosticsProfile = null;
if (this.OrchestratorType != null)
{
if (vOrchestratorProfile == null)
{
vOrchestratorProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceOrchestratorProfile();
}
vOrchestratorProfile.OrchestratorType = this.OrchestratorType;
}
if (this.MasterCount != null)
{
if (vMasterProfile == null)
{
vMasterProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile();
}
vMasterProfile.Count = this.MasterCount;
}
if (this.MasterDnsPrefix != null)
{
if (vMasterProfile == null)
{
vMasterProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile();
}
vMasterProfile.DnsPrefix = this.MasterDnsPrefix;
}
if (this.WindowsProfileAdminUsername != null)
{
if (vWindowsProfile == null)
{
vWindowsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile();
}
vWindowsProfile.AdminUsername = this.WindowsProfileAdminUsername;
}
if (this.WindowsProfileAdminPassword != null)
{
if (vWindowsProfile == null)
{
vWindowsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile();
}
vWindowsProfile.AdminPassword = this.WindowsProfileAdminPassword;
}
if (this.AdminUsername != null)
{
if (vLinuxProfile == null)
{
vLinuxProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile();
}
vLinuxProfile.AdminUsername = this.AdminUsername;
}
if (this.SshPublicKey != null)
{
if (vLinuxProfile == null)
{
vLinuxProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile();
}
if (vLinuxProfile.Ssh == null)
{
vLinuxProfile.Ssh = new Microsoft.Azure.Management.Compute.Models.ContainerServiceSshConfiguration();
}
if (vLinuxProfile.Ssh.PublicKeys == null)
{
vLinuxProfile.Ssh.PublicKeys = new List<Microsoft.Azure.Management.Compute.Models.ContainerServiceSshPublicKey>();
}
foreach (var element in this.SshPublicKey)
{
var vPublicKeys = new Microsoft.Azure.Management.Compute.Models.ContainerServiceSshPublicKey();
vPublicKeys.KeyData = element;
vLinuxProfile.Ssh.PublicKeys.Add(vPublicKeys);
}
}
if (this.VmDiagnosticsEnabled != null)
{
if (vDiagnosticsProfile == null)
{
vDiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceDiagnosticsProfile();
}
if (vDiagnosticsProfile.VmDiagnostics == null)
{
vDiagnosticsProfile.VmDiagnostics = new Microsoft.Azure.Management.Compute.Models.ContainerServiceVMDiagnostics();
}
vDiagnosticsProfile.VmDiagnostics.Enabled = this.VmDiagnosticsEnabled;
}
var vContainerService = new ContainerService
{
Location = this.Location,
Tags = (this.Tag == null) ? null : this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value),
AgentPoolProfiles = this.AgentPoolProfile,
OrchestratorProfile = vOrchestratorProfile,
MasterProfile = vMasterProfile,
WindowsProfile = vWindowsProfile,
LinuxProfile = vLinuxProfile,
DiagnosticsProfile = vDiagnosticsProfile,
};
WriteObject(vContainerService);
}
}
}
| |
using System;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using MongoDB.Bson;
using MongoDB.Util;
namespace MongoDB
{
/// <summary>
/// Oid is an immutable object that represents a Mongo ObjectId.
/// </summary>
[Serializable]
public sealed class Oid : IEquatable<Oid>, IComparable<Oid>, IFormattable, IXmlSerializable
{
private static readonly OidGenerator OidGenerator = new OidGenerator();
private byte[] _bytes;
/// <summary>
/// Initializes a new instance of the <see cref="Oid"/> class.
/// </summary>
/// <remarks>
/// Needed for some serializers.
/// </remarks>
private Oid()
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "Oid" /> class.
/// </summary>
/// <param name = "value">The value.</param>
public Oid(string value)
{
if(value == null)
throw new ArgumentNullException("value");
ParseBytes(value);
}
/// <summary>
/// Initializes a new instance of the <see cref = "Oid" /> class.
/// </summary>
/// <param name = "value">The value.</param>
public Oid(byte[] value)
{
if(value == null)
throw new ArgumentNullException("value");
_bytes = new byte[12];
Array.Copy(value, _bytes, 12);
}
/// <summary>
/// Initializes a new instance of the <see cref="Oid"/> class.
/// </summary>
/// <param name="oid">The oid.</param>
public Oid(Oid oid)
{
if(oid == null)
throw new ArgumentNullException("oid");
_bytes = oid._bytes;
}
/// <summary>
/// Gets the created.
/// </summary>
/// <value>The created.</value>
public DateTime Created
{
get
{
var time = new byte[4];
Array.Copy(_bytes, time, 4);
Array.Reverse(time);
var seconds = BitConverter.ToInt32(time, 0);
return BsonInfo.Epoch.AddSeconds(seconds);
}
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name = "other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name = "other" /> parameter.
/// Zero
/// This object is equal to <paramref name = "other" />.
/// Greater than zero
/// This object is greater than <paramref name = "other" />.
/// </returns>
public int CompareTo(Oid other)
{
if(ReferenceEquals(other, null))
return 1;
var otherBytes = other._bytes;
for(var x = 0; x < _bytes.Length; x++)
if(_bytes[x] < otherBytes[x])
return -1;
else if(_bytes[x] > otherBytes[x])
return 1;
return 0;
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name = "other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name = "other" /> parameter; otherwise, false.
/// </returns>
public bool Equals(Oid other)
{
return CompareTo(other) == 0;
}
/// <summary>
/// Determines whether the specified <see cref = "System.Object" /> is equal to this instance.
/// </summary>
/// <param name = "obj">The <see cref = "System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref = "System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if(obj is Oid)
return CompareTo((Oid)obj) == 0;
return false;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return ToString().GetHashCode();
}
/// <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()
{
return BitConverter.ToString(_bytes).Replace("-", "").ToLower();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
/// <remarks>
/// J = Returns Javascript string
/// </remarks>
public string ToString(string format)
{
if(string.IsNullOrEmpty(format))
return ToString();
if(format == "J")
return String.Format("\"{0}\"", ToString());
throw new ArgumentException("Invalid format string","format");
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="formatProvider">The format provider.</param>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
/// <remarks>
/// J = Returns Javascript string
/// </remarks>
public string ToString(string format, IFormatProvider formatProvider)
{
return ToString(format);
}
/// <summary>
/// Converts the Oid to a byte array.
/// </summary>
public byte[] ToByteArray()
{
var ret = new byte[12];
Array.Copy(_bytes, ret, 12);
return ret;
}
/// <summary>
/// Generates an Oid using OidGenerator.
/// </summary>
/// <returns>
/// A <see cref = "Oid" />
/// </returns>
public static Oid NewOid()
{
return OidGenerator.Generate();
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name = "a">A.</param>
/// <param name = "b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(Oid a, Oid b){
if (ReferenceEquals(a, b)){
return true;
}
if((Object)a == null || (Object)b == null){
return false;
}
return a.Equals(b);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name = "a">A.</param>
/// <param name = "b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(Oid a, Oid b)
{
return !(a == b);
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name = "a">A.</param>
/// <param name = "b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator >(Oid a, Oid b)
{
return a.CompareTo(b) > 0;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name = "a">A.</param>
/// <param name = "b">The b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator <(Oid a, Oid b)
{
return a.CompareTo(b) < 0;
}
/// <summary>
/// Validates the hex.
/// </summary>
/// <param name = "value">The value.</param>
private void ValidateHex(string value)
{
if(value == null || value.Length != 24)
throw new ArgumentException("Oid strings should be 24 characters");
var notHexChars = new Regex(@"[^A-Fa-f0-9]", RegexOptions.None);
if(notHexChars.IsMatch(value))
throw new ArgumentOutOfRangeException("value", "Value contains invalid characters");
}
/// <summary>
/// Decodes the hex.
/// </summary>
/// <param name = "value">The value.</param>
/// <returns></returns>
private static byte[] DecodeHex(string value)
{
var numberChars = value.Length;
var bytes = new byte[numberChars/2];
for(var i = 0; i < numberChars; i += 2)
try
{
bytes[i/2] = Convert.ToByte(value.Substring(i, 2), 16);
}
catch
{
//failed to convert these 2 chars, they may contain illegal charracters
bytes[i/2] = 0;
}
return bytes;
}
/// <summary>
/// Parses the bytes.
/// </summary>
/// <param name="value">The value.</param>
private void ParseBytes(string value)
{
value = value.Replace("\"", "");
ValidateHex(value);
_bytes = DecodeHex(value);
}
/// <summary>
/// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
/// </summary>
/// <returns>
/// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.
/// </returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
void IXmlSerializable.ReadXml(XmlReader reader)
{
ParseBytes(reader.ReadElementContentAsString());
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param>
void IXmlSerializable.WriteXml(XmlWriter writer)
{
writer.WriteString(ToString());
}
}
}
| |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using FluentNHibernate.Automapping.TestFixtures;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.ClassBased;
using FluentNHibernate.MappingModel.Collections;
using FluentNHibernate.Utils;
using NUnit.Framework;
namespace FluentNHibernate.Testing.ConventionsTests.Inspection
{
[TestFixture, Category("Inspection DSL")]
public class JoinedSubclassInspectorMapsToJoinedSubclassMapping
{
private JoinedSubclassMapping mapping;
private IJoinedSubclassInspector inspector;
[SetUp]
public void CreateDsl()
{
mapping = new JoinedSubclassMapping();
inspector = new JoinedSubclassInspector(mapping);
}
[Test]
public void AbstractMapped()
{
mapping.Abstract = true;
inspector.Abstract.ShouldEqual(true);
}
[Test]
public void AbstractIsSet()
{
mapping.Abstract = true;
inspector.IsSet(Prop(x => x.Abstract))
.ShouldBeTrue();
}
[Test]
public void AbstractIsNotSet()
{
inspector.IsSet(Prop(x => x.Abstract))
.ShouldBeFalse();
}
[Test]
public void AnysCollectionHasSameCountAsMapping()
{
mapping.AddAny(new AnyMapping());
inspector.Anys.Count().ShouldEqual(1);
}
[Test]
public void AnysCollectionOfInspectors()
{
mapping.AddAny(new AnyMapping());
inspector.Anys.First().ShouldBeOfType<IAnyInspector>();
}
[Test]
public void AnysCollectionIsEmpty()
{
inspector.Anys.IsEmpty().ShouldBeTrue();
}
[Test]
public void CheckMapped()
{
mapping.Check = "x";
inspector.Check.ShouldEqual("x");
}
[Test]
public void CheckIsSet()
{
mapping.Check = "x";
inspector.IsSet(Prop(x => x.Check))
.ShouldBeTrue();
}
[Test]
public void CheckIsNotSet()
{
inspector.IsSet(Prop(x => x.Check))
.ShouldBeFalse();
}
[Test]
public void CollectionsCollectionHasSameCountAsMapping()
{
mapping.AddCollection(new BagMapping());
inspector.Collections.Count().ShouldEqual(1);
}
[Test]
public void CollectionsCollectionOfInspectors()
{
mapping.AddCollection(new BagMapping());
inspector.Collections.First().ShouldBeOfType<ICollectionInspector>();
}
[Test]
public void CollectionsCollectionIsEmpty()
{
inspector.Collections.IsEmpty().ShouldBeTrue();
}
[Test]
public void DynamicInsertMapped()
{
mapping.DynamicInsert = true;
inspector.DynamicInsert.ShouldEqual(true);
}
[Test]
public void DynamicInsertIsSet()
{
mapping.DynamicInsert = true;
inspector.IsSet(Prop(x => x.DynamicInsert))
.ShouldBeTrue();
}
[Test]
public void DynamicInsertIsNotSet()
{
inspector.IsSet(Prop(x => x.DynamicInsert))
.ShouldBeFalse();
}
[Test]
public void DynamicUpdateMapped()
{
mapping.DynamicUpdate = true;
inspector.DynamicUpdate.ShouldEqual(true);
}
[Test]
public void DynamicUpdateIsSet()
{
mapping.DynamicUpdate = true;
inspector.IsSet(Prop(x => x.DynamicUpdate))
.ShouldBeTrue();
}
[Test]
public void DynamicUpdateIsNotSet()
{
inspector.IsSet(Prop(x => x.DynamicUpdate))
.ShouldBeFalse();
}
[Test]
public void ExtendsMapped()
{
mapping.Extends = "other-class";
inspector.Extends.ShouldEqual("other-class");
}
[Test]
public void ExtendsIsSet()
{
mapping.Extends = "other-class";
inspector.IsSet(Prop(x => x.Extends))
.ShouldBeTrue();
}
[Test]
public void ExtendsIsNotSet()
{
inspector.IsSet(Prop(x => x.Extends))
.ShouldBeFalse();
}
[Test]
public void JoinsCollectionHasSameCountAsMapping()
{
mapping.AddJoin(new JoinMapping());
inspector.Joins.Count().ShouldEqual(1);
}
[Test]
public void JoinsCollectionOfInspectors()
{
mapping.AddJoin(new JoinMapping());
inspector.Joins.First().ShouldBeOfType<IJoinInspector>();
}
[Test]
public void JoinsCollectionIsEmpty()
{
inspector.Joins.IsEmpty().ShouldBeTrue();
}
[Test]
public void KeyMapped()
{
mapping.Key = new KeyMapping();
mapping.Key.ForeignKey = "test";
inspector.Key.ForeignKey.ShouldEqual("test");
}
[Test]
public void KeyIsSet()
{
mapping.Key = new KeyMapping();
mapping.Key.ForeignKey = "test";
inspector.IsSet(Prop(x => x.Key))
.ShouldBeTrue();
}
[Test]
public void KeyIsNotSet()
{
inspector.IsSet(Prop(x => x.Key))
.ShouldBeFalse();
}
[Test]
public void LazyMapped()
{
mapping.Lazy = true;
inspector.LazyLoad.ShouldEqual(true);
}
[Test]
public void LazyIsSet()
{
mapping.Lazy = true;
inspector.IsSet(Prop(x => x.LazyLoad))
.ShouldBeTrue();
}
[Test]
public void LazyIsNotSet()
{
inspector.IsSet(Prop(x => x.LazyLoad))
.ShouldBeFalse();
}
[Test]
public void NameMapped()
{
mapping.Name = "name";
inspector.Name.ShouldEqual("name");
}
[Test]
public void NameIsSet()
{
mapping.Name = "name";
inspector.IsSet(Prop(x => x.Name))
.ShouldBeTrue();
}
[Test]
public void NameIsNotSet()
{
inspector.IsSet(Prop(x => x.Name))
.ShouldBeFalse();
}
[Test]
public void OneToOnesCollectionHasSameCountAsMapping()
{
mapping.AddOneToOne(new OneToOneMapping());
inspector.OneToOnes.Count().ShouldEqual(1);
}
[Test]
public void OneToOnesCollectionOfInspectors()
{
mapping.AddOneToOne(new OneToOneMapping());
inspector.OneToOnes.First().ShouldBeOfType<IOneToOneInspector>();
}
[Test]
public void OneToOnesCollectionIsEmpty()
{
inspector.OneToOnes.IsEmpty().ShouldBeTrue();
}
[Test]
public void PropertiesCollectionHasSameCountAsMapping()
{
mapping.AddProperty(new PropertyMapping());
inspector.Properties.Count().ShouldEqual(1);
}
[Test]
public void PropertiesCollectionOfInspectors()
{
mapping.AddProperty(new PropertyMapping());
inspector.Properties.First().ShouldBeOfType<IPropertyInspector>();
}
[Test]
public void PropertiesCollectionIsEmpty()
{
inspector.Properties.IsEmpty().ShouldBeTrue();
}
[Test]
public void ProxyMapped()
{
mapping.Proxy = "proxy";
inspector.Proxy.ShouldEqual("proxy");
}
[Test]
public void ProxyIsSet()
{
mapping.Proxy = "proxy";
inspector.IsSet(Prop(x => x.Proxy))
.ShouldBeTrue();
}
[Test]
public void ProxyIsNotSet()
{
inspector.IsSet(Prop(x => x.Proxy))
.ShouldBeFalse();
}
[Test]
public void ReferencesCollectionHasSameCountAsMapping()
{
mapping.AddReference(new ManyToOneMapping());
inspector.References.Count().ShouldEqual(1);
}
[Test]
public void ReferencesCollectionOfInspectors()
{
mapping.AddReference(new ManyToOneMapping());
inspector.References.First().ShouldBeOfType<IManyToOneInspector>();
}
[Test]
public void ReferencesCollectionIsEmpty()
{
inspector.References.IsEmpty().ShouldBeTrue();
}
[Test]
public void SelectBeforeUpdateMapped()
{
mapping.SelectBeforeUpdate = true;
inspector.SelectBeforeUpdate.ShouldEqual(true);
}
[Test]
public void SelectBeforeUpdateIsSet()
{
mapping.SelectBeforeUpdate = true;
inspector.IsSet(Prop(x => x.SelectBeforeUpdate))
.ShouldBeTrue();
}
[Test]
public void SelectBeforeUpdateIsNotSet()
{
inspector.IsSet(Prop(x => x.SelectBeforeUpdate))
.ShouldBeFalse();
}
[Test]
public void SubclassesCollectionHasSameCountAsMapping()
{
mapping.AddSubclass(new JoinedSubclassMapping());
inspector.Subclasses.Count().ShouldEqual(1);
}
[Test]
public void SubclassesCollectionOfInspectors()
{
mapping.AddSubclass(new JoinedSubclassMapping());
inspector.Subclasses.First().ShouldBeOfType<IJoinedSubclassInspector>();
}
[Test]
public void SubclassesCollectionIsEmpty()
{
inspector.Subclasses.IsEmpty().ShouldBeTrue();
}
[Test]
public void TableNameMapped()
{
mapping.TableName = "table";
inspector.TableName.ShouldEqual("table");
}
[Test]
public void TableNameIsSet()
{
mapping.TableName = "table";
inspector.IsSet(Prop(x => x.TableName))
.ShouldBeTrue();
}
[Test]
public void TableNameIsNotSet()
{
inspector.IsSet(Prop(x => x.TableName))
.ShouldBeFalse();
}
[Test]
public void TypeMapped()
{
mapping.Type = typeof(ExampleClass);
inspector.Type.ShouldEqual(typeof(ExampleClass));
}
[Test]
public void TypeIsSet()
{
mapping.Type = typeof(ExampleClass);
inspector.IsSet(Prop(x => x.Type))
.ShouldBeTrue();
}
[Test]
public void TypeIsNotSet()
{
inspector.IsSet(Prop(x => x.Type))
.ShouldBeFalse();
}
#region Helpers
private PropertyInfo Prop(Expression<Func<IJoinedSubclassInspector, object>> propertyExpression)
{
return ReflectionHelper.GetProperty(propertyExpression);
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !WINDOWS_PHONE_7
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
#endif
using NLog.Common;
using NLog.Config;
using NLog.Internal.NetworkSenders;
using NLog.Targets;
[TestFixture]
public class NetworkTargetTests : NLogTestBase
{
[Test]
public void NetworkTargetHappyPathTest()
{
var senderFactory = new MySenderFactory();
var target = new NetworkTarget();
target.Address = "tcp://someaddress/";
target.SenderFactory = senderFactory;
target.Layout = "${message}";
target.NewLine = true;
target.KeepConnection = true;
target.Initialize(null);
var exceptions = new List<Exception>();
var mre = new ManualResetEvent(false);
int remaining = 3;
AsyncContinuation asyncContinuation = ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (--remaining == 0)
{
mre.Set();
}
}
};
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg1").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg2").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg3").WithContinuation(asyncContinuation));
mre.WaitOne();
foreach (var ex in exceptions)
{
if (ex != null)
{
Assert.Fail(ex.ToString());
}
}
Assert.AreEqual(1, senderFactory.Senders.Count);
var sender = senderFactory.Senders[0];
target.Close();
Assert.AreEqual(18L, sender.MemoryStream.Length);
Assert.AreEqual("msg1\r\nmsg2\r\nmsg3\r\n", target.Encoding.GetString(sender.MemoryStream.GetBuffer(), 0, (int)sender.MemoryStream.Length));
// we invoke the sender 3 times, each time sending 4 bytes
var actual = senderFactory.Log.ToString();
Assert.IsTrue(actual.IndexOf("1: connect tcp://someaddress/") != -1);
Assert.IsTrue(actual.IndexOf("1: send 0 6") != -1);
Assert.IsTrue(actual.IndexOf("1: send 0 6") != -1);
Assert.IsTrue(actual.IndexOf("1: send 0 6") != -1);
Assert.IsTrue(actual.IndexOf("1: close") != -1);
}
[Test]
public void NetworkTargetMultipleConnectionsTest()
{
var senderFactory = new MySenderFactory();
var target = new NetworkTarget();
target.Address = "tcp://${logger}.company.lan/";
target.SenderFactory = senderFactory;
target.Layout = "${message}";
target.KeepConnection = true;
target.Initialize(null);
var exceptions = new List<Exception>();
var mre = new ManualResetEvent(false);
int remaining = 3;
AsyncContinuation asyncContinuation = ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (--remaining == 0)
{
mre.Set();
}
}
};
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg1").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg2").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger3", "msg3").WithContinuation(asyncContinuation));
mre.WaitOne();
foreach (var ex in exceptions)
{
if (ex != null)
{
Assert.Fail(ex.ToString());
}
}
mre.Reset();
AsyncContinuation flushContinuation = ex =>
{
mre.Set();
};
target.Flush(flushContinuation);
mre.WaitOne();
target.Close();
var actual = senderFactory.Log.ToString();
Assert.IsTrue(actual.IndexOf("1: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(actual.IndexOf("1: send 0 4") != -1);
Assert.IsTrue(actual.IndexOf("2: connect tcp://logger2.company.lan/") != -1);
Assert.IsTrue(actual.IndexOf("2: send 0 4") != -1);
Assert.IsTrue(actual.IndexOf("3: connect tcp://logger3.company.lan/") != -1);
Assert.IsTrue(actual.IndexOf("3: send 0 4") != -1);
Assert.IsTrue(actual.IndexOf("1: flush") != -1);
Assert.IsTrue(actual.IndexOf("2: flush") != -1);
Assert.IsTrue(actual.IndexOf("3: flush") != -1);
Assert.IsTrue(actual.IndexOf("1: close") != -1);
Assert.IsTrue(actual.IndexOf("2: close") != -1);
Assert.IsTrue(actual.IndexOf("3: close") != -1);
}
[Test]
public void NothingToFlushTest()
{
var senderFactory = new MySenderFactory();
var target = new NetworkTarget();
target.Address = "tcp://${logger}.company.lan/";
target.SenderFactory = senderFactory;
target.Layout = "${message}";
target.KeepConnection = true;
target.Initialize(null);
var mre = new ManualResetEvent(false);
AsyncContinuation flushContinuation = ex =>
{
mre.Set();
};
target.Flush(flushContinuation);
mre.WaitOne();
target.Close();
string expectedLog = @"";
Assert.AreEqual(expectedLog, senderFactory.Log.ToString());
}
[Test]
public void NetworkTargetMultipleConnectionsWithCacheOverflowTest()
{
var senderFactory = new MySenderFactory();
var target = new NetworkTarget();
target.Address = "tcp://${logger}.company.lan/";
target.SenderFactory = senderFactory;
target.Layout = "${message}";
target.KeepConnection = true;
target.ConnectionCacheSize = 2;
target.Initialize(null);
var exceptions = new List<Exception>();
var mre = new ManualResetEvent(false);
int remaining = 6;
AsyncContinuation asyncContinuation = ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (--remaining == 0)
{
mre.Set();
}
}
};
// logger1 should be kept alive because it's being referenced frequently
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg1").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg2").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg3").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger3", "msg1").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg2").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg3").WithContinuation(asyncContinuation));
mre.WaitOne();
foreach (var ex in exceptions)
{
if (ex != null)
{
Assert.Fail(ex.ToString());
}
}
target.Close();
string result = senderFactory.Log.ToString();
Assert.IsTrue(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("1: send 0 4") != -1);
Assert.IsTrue(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("2: send 0 4") != -1);
Assert.IsTrue(result.IndexOf("1: send 0 4") != -1);
Assert.IsTrue(result.IndexOf("2: close") != -1);
Assert.IsTrue(result.IndexOf("3: connect tcp://logger3.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("3: send 0 4") != -1);
Assert.IsTrue(result.IndexOf("1: send 0 4") != -1);
Assert.IsTrue(result.IndexOf("3: close") != -1);
Assert.IsTrue(result.IndexOf("4: connect tcp://logger2.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("4: send 0 4") != -1);
Assert.IsTrue(result.IndexOf("1: close") != -1);
Assert.IsTrue(result.IndexOf("4: close") != -1);
}
[Test]
public void NetworkTargetMultipleConnectionsWithoutKeepAliveTest()
{
var senderFactory = new MySenderFactory();
var target = new NetworkTarget();
target.Address = "tcp://${logger}.company.lan/";
target.SenderFactory = senderFactory;
target.Layout = "${message}";
target.KeepConnection = false;
target.Initialize(null);
var exceptions = new List<Exception>();
var mre = new ManualResetEvent(false);
int remaining = 6;
AsyncContinuation asyncContinuation = ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (--remaining == 0)
{
mre.Set();
}
}
};
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg1").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg2").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg3").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger3", "msg1").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg2").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg3").WithContinuation(asyncContinuation));
mre.WaitOne();
foreach (var ex in exceptions)
{
if (ex != null)
{
Assert.Fail(ex.ToString());
}
}
target.Close();
string result = senderFactory.Log.ToString();
Assert.IsTrue(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("1: send 0 4") != -1);
Assert.IsTrue(result.IndexOf("1: close") != -1);
Assert.IsTrue(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("2: send 0 4") != -1);
Assert.IsTrue(result.IndexOf("2: close") != -1);
Assert.IsTrue(result.IndexOf("3: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("3: send 0 4") != -1);
Assert.IsTrue(result.IndexOf("3: close") != -1);
Assert.IsTrue(result.IndexOf("4: connect tcp://logger3.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("4: send 0 4") != -1);
Assert.IsTrue(result.IndexOf("4: close") != -1);
Assert.IsTrue(result.IndexOf("5: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("5: send 0 4") != -1);
Assert.IsTrue(result.IndexOf("5: close") != -1);
Assert.IsTrue(result.IndexOf("6: connect tcp://logger2.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("6: send 0 4") != -1);
Assert.IsTrue(result.IndexOf("6: close") != -1);
}
[Test]
public void NetworkTargetMultipleConnectionsWithMessageSplitTest()
{
var senderFactory = new MySenderFactory();
var target = new NetworkTarget();
target.Address = "tcp://${logger}.company.lan/";
target.SenderFactory = senderFactory;
target.Layout = "${message}";
target.KeepConnection = true;
target.MaxMessageSize = 9;
target.OnOverflow = NetworkTargetOverflowAction.Split;
target.Initialize(null);
var exceptions = new List<Exception>();
var mre = new ManualResetEvent(false);
int remaining = 3;
AsyncContinuation asyncContinuation = ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (--remaining == 0)
{
mre.Set();
}
}
};
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "012345678901234567890123456789").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "012345678901234").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "012345678901234567890123").WithContinuation(asyncContinuation));
mre.WaitOne();
foreach (var ex in exceptions)
{
if (ex != null)
{
Assert.Fail(ex.ToString());
}
}
target.Close();
var result = senderFactory.Log.ToString();
Assert.IsTrue(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("1: send 0 9") != -1);
Assert.IsTrue(result.IndexOf("1: send 9 9") != -1);
Assert.IsTrue(result.IndexOf("1: send 18 9") != -1);
Assert.IsTrue(result.IndexOf("1: send 27 3") != -1);
Assert.IsTrue(result.IndexOf("1: send 0 9") != -1);
Assert.IsTrue(result.IndexOf("1: send 9 6") != -1);
Assert.IsTrue(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("2: send 0 9") != -1);
Assert.IsTrue(result.IndexOf("2: send 9 9") != -1);
Assert.IsTrue(result.IndexOf("2: send 18 6") != -1);
Assert.IsTrue(result.IndexOf("1: close") != -1);
Assert.IsTrue(result.IndexOf("2: close") != -1);
}
[Test]
public void NetworkTargetMultipleConnectionsWithMessageDiscardTest()
{
var senderFactory = new MySenderFactory();
var target = new NetworkTarget();
target.Address = "tcp://${logger}.company.lan/";
target.SenderFactory = senderFactory;
target.Layout = "${message}";
target.KeepConnection = true;
target.MaxMessageSize = 10;
target.OnOverflow = NetworkTargetOverflowAction.Discard;
target.Initialize(null);
var exceptions = new List<Exception>();
var mre = new ManualResetEvent(false);
int remaining = 3;
AsyncContinuation asyncContinuation = ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (--remaining == 0)
{
mre.Set();
}
}
};
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "012345678901234").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "01234").WithContinuation(asyncContinuation));
mre.WaitOne();
foreach (var ex in exceptions)
{
if (ex != null)
{
Assert.Fail(ex.ToString());
}
}
target.Close();
string result = senderFactory.Log.ToString();
Assert.IsTrue(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("1: send 0 7") != -1);
Assert.IsTrue(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("2: send 0 5") != -1);
Assert.IsTrue(result.IndexOf("1: close") != -1);
Assert.IsTrue(result.IndexOf("2: close") != -1);
}
[Test]
public void NetworkTargetMultipleConnectionsWithMessageErrorTest()
{
var senderFactory = new MySenderFactory();
var target = new NetworkTarget();
target.Address = "tcp://${logger}.company.lan/";
target.SenderFactory = senderFactory;
target.Layout = "${message}";
target.KeepConnection = true;
target.MaxMessageSize = 10;
target.OnOverflow = NetworkTargetOverflowAction.Error;
target.Initialize(null);
var exceptions = new List<Exception>();
var mre = new ManualResetEvent(false);
int remaining = 3;
AsyncContinuation asyncContinuation = ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (--remaining == 0)
{
mre.Set();
}
}
};
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "012345678901234").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "01234").WithContinuation(asyncContinuation));
mre.WaitOne();
Assert.IsNull(exceptions[0]);
Assert.IsNotNull(exceptions[1]);
Assert.AreEqual("Attempted to send a message larger than MaxMessageSize (10). Actual size was: 15. Adjust OnOverflow and MaxMessageSize parameters accordingly.", exceptions[1].Message);
Assert.IsNull(exceptions[2]);
target.Close();
string result = senderFactory.Log.ToString();
Assert.IsTrue(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("1: send 0 7") != -1);
Assert.IsTrue(result.IndexOf("1: close") != -1);
Assert.IsTrue(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("2: send 0 5") != -1);
Assert.IsTrue(result.IndexOf("2: close") != -1);
}
[Test]
public void NetworkTargetSendFailureTests()
{
var senderFactory = new MySenderFactory()
{
FailCounter = 3, // first 3 sends will fail
};
var target = new NetworkTarget();
target.Address = "tcp://${logger}.company.lan/";
target.SenderFactory = senderFactory;
target.Layout = "${message}";
target.KeepConnection = true;
target.OnOverflow = NetworkTargetOverflowAction.Discard;
target.Initialize(null);
var exceptions = new List<Exception>();
var mre = new ManualResetEvent(false);
int remaining = 5;
AsyncContinuation asyncContinuation = ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (--remaining == 0)
{
mre.Set();
}
}
};
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "01234").WithContinuation(asyncContinuation));
mre.WaitOne();
Assert.IsNotNull(exceptions[0]);
Assert.IsNotNull(exceptions[1]);
Assert.IsNotNull(exceptions[2]);
Assert.IsNull(exceptions[3]);
Assert.IsNull(exceptions[4]);
target.Close();
var result = senderFactory.Log.ToString();
Assert.IsTrue(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("1: send 0 7") != -1);
Assert.IsTrue(result.IndexOf("1: failed") != -1);
Assert.IsTrue(result.IndexOf("1: close") != -1);
Assert.IsTrue(result.IndexOf("2: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("2: send 0 7") != -1);
Assert.IsTrue(result.IndexOf("2: failed") != -1);
Assert.IsTrue(result.IndexOf("2: close") != -1);
Assert.IsTrue(result.IndexOf("3: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("3: send 0 7") != -1);
Assert.IsTrue(result.IndexOf("3: failed") != -1);
Assert.IsTrue(result.IndexOf("3: close") != -1);
Assert.IsTrue(result.IndexOf("4: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("4: send 0 7") != -1);
Assert.IsTrue(result.IndexOf("4: send 0 5") != -1);
Assert.IsTrue(result.IndexOf("4: close") != -1);
}
#if !SILVERLIGHT
[Test]
public void NetworkTargetTcpTest()
{
NetworkTarget target;
target = new NetworkTarget()
{
Address = "tcp://127.0.0.1:3004",
Layout = "${message}\n",
KeepConnection = true,
};
string expectedResult = string.Empty;
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Exception receiveException = null;
var resultStream = new MemoryStream();
var receiveFinished = new ManualResetEvent(false);
listener.Bind(new IPEndPoint(IPAddress.Loopback, 3004));
listener.Listen(10);
listener.BeginAccept(
result =>
{
try
{
// Console.WriteLine("Accepting...");
byte[] buffer = new byte[4096];
using (Socket connectedSocket = listener.EndAccept(result))
{
// Console.WriteLine("Accepted...");
int got;
while ((got = connectedSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0)
{
resultStream.Write(buffer, 0, got);
}
// Console.WriteLine("Closing connection...");
}
}
catch (Exception ex)
{
Console.WriteLine("Receive exception {0}", ex);
receiveException = ex;
}
finally
{
receiveFinished.Set();
}
}, null);
target.Initialize(new LoggingConfiguration());
int pendingWrites = 100;
var writeCompleted = new ManualResetEvent(false);
var exceptions = new List<Exception>();
AsyncContinuation writeFinished =
ex =>
{
lock (exceptions)
{
Console.WriteLine("{0} Write finished {1}", pendingWrites, ex);
exceptions.Add(ex);
pendingWrites--;
if (pendingWrites == 0)
{
writeCompleted.Set();
}
}
};
int toWrite = pendingWrites;
for (int i = 0; i < toWrite; ++i)
{
var ev = new LogEventInfo(LogLevel.Info, "logger1", "messagemessagemessagemessagemessage" + i).WithContinuation(writeFinished);
target.WriteAsyncLogEvent(ev);
expectedResult += "messagemessagemessagemessagemessage" + i + "\n";
}
Assert.IsTrue(writeCompleted.WaitOne(10000, false), "Writes did not complete");
target.Close();
Assert.IsTrue(receiveFinished.WaitOne(10000, false), "Receive did not complete");
string resultString = Encoding.UTF8.GetString(resultStream.GetBuffer(), 0, (int)resultStream.Length);
Assert.IsNull(receiveException, "Receive exception: " + receiveException);
Assert.AreEqual(expectedResult, resultString);
}
}
[Test]
public void NetworkTargetUdpTest()
{
var target = new NetworkTarget()
{
Address = "udp://127.0.0.1:3002",
Layout = "${message}\n",
KeepConnection = true,
};
string expectedResult = string.Empty;
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
Exception receiveException = null;
var receivedMessages = new List<string>();
var receiveFinished = new ManualResetEvent(false);
byte[] receiveBuffer = new byte[4096];
listener.Bind(new IPEndPoint(IPAddress.Loopback, 3002));
EndPoint remoteEndPoint = null;
AsyncCallback receivedDatagram = null;
receivedDatagram = result =>
{
try
{
int got = listener.EndReceiveFrom(result, ref remoteEndPoint);
string message = Encoding.UTF8.GetString(receiveBuffer, 0, got);
lock (receivedMessages)
{
receivedMessages.Add(message);
if (receivedMessages.Count == 100)
{
receiveFinished.Set();
}
}
remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null);
}
catch (Exception ex)
{
receiveException = ex;
}
};
remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null);
target.Initialize(new LoggingConfiguration());
int pendingWrites = 100;
var writeCompleted = new ManualResetEvent(false);
var exceptions = new List<Exception>();
AsyncContinuation writeFinished =
ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
pendingWrites--;
if (pendingWrites == 0)
{
writeCompleted.Set();
}
}
};
int toWrite = pendingWrites;
for (int i = 0; i < toWrite; ++i)
{
var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished);
target.WriteAsyncLogEvent(ev);
expectedResult += "message" + i + "\n";
}
Assert.IsTrue(writeCompleted.WaitOne(10000, false));
target.Close();
Assert.IsTrue(receiveFinished.WaitOne(10000, false));
Assert.AreEqual(toWrite, receivedMessages.Count);
for (int i = 0; i < toWrite; ++i)
{
Assert.IsTrue(receivedMessages.Contains("message" + i + "\n"), "Message #" + i + " not received.");
}
Assert.IsNull(receiveException, "Receive exception: " + receiveException);
}
}
[Test]
public void NetworkTargetNotConnectedTest()
{
var target = new NetworkTarget()
{
Address = "tcp4://127.0.0.1:33415",
Layout = "${message}\n",
KeepConnection = true,
};
target.Initialize(new LoggingConfiguration());
int toWrite = 10;
int pendingWrites = toWrite;
var writeCompleted = new ManualResetEvent(false);
var exceptions = new List<Exception>();
AsyncContinuation writeFinished =
ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
pendingWrites--;
Console.WriteLine("Write finished. Pending {0}", pendingWrites);
if (pendingWrites == 0)
{
writeCompleted.Set();
}
}
};
for (int i = 0; i < toWrite; ++i)
{
var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished);
target.WriteAsyncLogEvent(ev);
}
Console.WriteLine("Waiting for completion...");
writeCompleted.WaitOne();
Console.WriteLine("Closing...");
// no exception
target.Close();
Assert.AreEqual(toWrite, exceptions.Count);
foreach (var ex in exceptions)
{
Assert.IsNotNull(ex);
}
Thread.Sleep(1000);
}
#endif
[Test]
public void NetworkTargetSendFailureWithoutKeepAliveTests()
{
var senderFactory = new MySenderFactory()
{
FailCounter = 3, // first 3 sends will fail
};
var target = new NetworkTarget();
target.Address = "tcp://${logger}.company.lan/";
target.SenderFactory = senderFactory;
target.Layout = "${message}";
target.KeepConnection = false;
target.OnOverflow = NetworkTargetOverflowAction.Discard;
target.Initialize(null);
var exceptions = new List<Exception>();
var mre = new ManualResetEvent(false);
int remaining = 5;
AsyncContinuation asyncContinuation = ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (--remaining == 0)
{
mre.Set();
}
}
};
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "01234").WithContinuation(asyncContinuation));
mre.WaitOne();
Assert.IsNotNull(exceptions[0]);
Assert.IsNotNull(exceptions[1]);
Assert.IsNotNull(exceptions[2]);
Assert.IsNull(exceptions[3]);
Assert.IsNull(exceptions[4]);
target.Close();
var result = senderFactory.Log.ToString();
Assert.IsTrue(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("1: send 0 7") != -1);
Assert.IsTrue(result.IndexOf("1: failed") != -1);
Assert.IsTrue(result.IndexOf("1: close") != -1);
Assert.IsTrue(result.IndexOf("2: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("2: send 0 7") != -1);
Assert.IsTrue(result.IndexOf("2: failed") != -1);
Assert.IsTrue(result.IndexOf("2: close") != -1);
Assert.IsTrue(result.IndexOf("3: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("3: send 0 7") != -1);
Assert.IsTrue(result.IndexOf("3: failed") != -1);
Assert.IsTrue(result.IndexOf("3: close") != -1);
Assert.IsTrue(result.IndexOf("4: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("4: send 0 7") != -1);
Assert.IsTrue(result.IndexOf("4: close") != -1);
Assert.IsTrue(result.IndexOf("5: connect tcp://logger1.company.lan/") != -1);
Assert.IsTrue(result.IndexOf("5: send 0 5") != -1);
Assert.IsTrue(result.IndexOf("5: close") != -1);
}
internal class MySenderFactory : INetworkSenderFactory
{
internal List<MyNetworkSender> Senders = new List<MyNetworkSender>();
internal StringWriter Log = new StringWriter();
private int idCounter;
public NetworkSender Create(string url)
{
var sender = new MyNetworkSender(url, ++this.idCounter, this.Log, this);
this.Senders.Add(sender);
return sender;
}
public int FailCounter { get; set; }
}
internal class MyNetworkSender : NetworkSender
{
private readonly int id;
private readonly TextWriter log;
private readonly MySenderFactory senderFactory;
internal MemoryStream MemoryStream { get; set; }
public MyNetworkSender(string url, int id, TextWriter log, MySenderFactory senderFactory)
: base(url)
{
this.id = id;
this.log = log;
this.senderFactory = senderFactory;
this.MemoryStream = new MemoryStream();
}
protected override void DoInitialize()
{
base.DoInitialize();
this.log.WriteLine("{0}: connect {1}", this.id, this.Address);
}
protected override void DoFlush(AsyncContinuation continuation)
{
this.log.WriteLine("{0}: flush", this.id);
continuation(null);
}
protected override void DoClose(AsyncContinuation continuation)
{
this.log.WriteLine("{0}: close", this.id);
continuation(null);
}
protected override void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation)
{
this.log.WriteLine("{0}: send {1} {2}", this.id, offset, length);
this.MemoryStream.Write(bytes, offset, length);
if (this.senderFactory.FailCounter > 0)
{
this.log.WriteLine("{0}: failed", this.id);
this.senderFactory.FailCounter--;
asyncContinuation(new IOException("some IO error has occured"));
}
else
{
asyncContinuation(null);
}
}
}
}
}
#endif
| |
// Python Tools for Visual Studio
// 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.IO;
using System.Linq;
using AnalysisTests;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Interpreter.Default;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
using Microsoft.PythonTools.Refactoring;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.Text;
using TestUtilities;
using TestUtilities.Mocks;
using TestUtilities.Python;
namespace PythonToolsTests {
using AP = AnalysisProtocol;
[TestClass]
public class ExtractMethodTests {
private const string ErrorReturn = "When the selection contains a return statement, all code paths must be terminated by a return statement too.";
private const string ErrorYield = "Cannot extract code containing \"yield\" expression";
private const string ErrorContinue = "The selection contains a \"continue\" statement, but not the enclosing loop";
private const string ErrorBreak = "The selection contains a \"break\" statement, but not the enclosing loop";
private const string ErrorReturnWithOutputs = "Cannot extract method that assigns to variables and returns";
private const string ErrorImportStar = "Cannot extract method containing from ... import * statement";
private const string ErrorExtractFromClass = "Cannot extract statements from a class definition";
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy();
}
[TestMethod, Priority(1)]
public void TestGlobalNonLocalVars() {
SuccessTest("ABC = 42",
@"def f():
ABC = 42
def f():
nonlocal ABC
ABC = 200
print(ABC)
return f",
@"def g():
ABC = 42
return ABC
def f():
ABC = g()
def f():
nonlocal ABC
ABC = 200
print(ABC)
return f");
SuccessTest("ABC = 42",
@"def f():
ABC = 42
def f():
print(ABC)
return f",
@"def g():
ABC = 42
return ABC
def f():
ABC = g()
def f():
print(ABC)
return f");
SuccessTest("ABC = 42",
@"def f():
global ABC
ABC = 42",
@"def g():
ABC = 42
return ABC
def f():
global ABC
ABC = g()");
}
[TestMethod, Priority(1)]
public void TestDefinitions() {
SuccessTest("x = .. = h()",
@"def f():
def g():
return 42
def h():
return 23
x = g()
z = h()
",
@"def g(g, h):
x = g()
z = h()
def f():
def g():
return 42
def h():
return 23
g(g, h)
");
SuccessTest("x = .. = h()",
@"def f():
class g():
pass
class h():
pass
x = g()
z = h()
",
@"def g(g, h):
x = g()
z = h()
def f():
class g():
pass
class h():
pass
g(g, h)
");
SuccessTest("@ .. pass",
@"@property
def f(): pass",
@"def g():
@property
def f(): pass
return f
f = g()");
}
[TestMethod, Priority(1)]
public void TestLeadingComment() {
SuccessTest("x = 41",
@"# fob
x = 41",
@"# fob
def g():
x = 41
return x
x = g()");
}
[TestMethod, Priority(1)]
public void AssignInIfStatementReadAfter() {
ExtractMethodTest(@"class C:
def fob(self):
if False: # fob
oar = player = Player()
else:
player.update()
", "oar = player = Player()", TestResult.Success(
@"class C:
def g(self):
oar = player = Player()
def fob(self):
if False: # fob
self.g()
else:
player.update()
"
), scopeName: "C");
ExtractMethodTest(@"class C:
def fob(self):
if False:
oar = player = Player()
else:
player.update()
", "oar = player = Player()", TestResult.Success(
@"class C:
def g(self):
oar = player = Player()
def fob(self):
if False:
self.g()
else:
player.update()
"
), scopeName: "C");
ExtractMethodTest(@"class C:
def fob(self):
if False:
oar = player = Player()
player.update()
", "oar = player = Player()", TestResult.Success(
@"class C:
def g(self):
oar = player = Player()
return player
def fob(self):
if False:
player = self.g()
player.update()
"
), scopeName: "C");
}
[TestMethod, Priority(1)]
public void ExtractMethodIndexExpr() {
ExtractMethodTest(@"class C:
def process_kinect_event(self, e):
for skeleton in e.skeletons:
fob[skeleton.dwTrackingID] = Player()
", "fob[skeleton.dwTrackingID] = Player()", TestResult.Success(
@"class C:
def g(self, skeleton):
fob[skeleton.dwTrackingID] = Player()
def process_kinect_event(self, e):
for skeleton in e.skeletons:
self.g(skeleton)
"
), scopeName: "C");
}
[TestMethod, Priority(1)]
public void TestExtractLambda() {
// lambda is present in the code
ExtractMethodTest(
@"def f():
pass
def x():
abc = lambda x: 42", "pass", TestResult.Success(
@"def g():
pass
def f():
g()
def x():
abc = lambda x: 42"));
// lambda is being extracted
ExtractMethodTest(
@"def f():
abc = lambda x: 42", "lambda x: 42", TestResult.Success(
@"def g():
return lambda x: 42
def f():
abc = g()"));
}
[TestMethod, Priority(1)]
public void TestExtractGenerator() {
var code = @"def f(imp = imp):
yield 42";
ExtractMethodTest(
code, () => new Span(code.IndexOf("= imp") + 2, 3), TestResult.Success(
@"def g():
return imp
def f(imp = g()):
yield 42"));
}
[TestMethod, Priority(1)]
public void TestExtractDefaultValue() {
var code = @"def f(imp = imp):
pass";
ExtractMethodTest(
code, () => new Span(code.IndexOf("= imp") + 2, 3), TestResult.Success(
@"def g():
return imp
def f(imp = g()):
pass"));
}
[TestMethod, Priority(1)]
public void TestFromImportStar() {
ExtractMethodTest(
@"def f():
from sys import *", "from sys import *", TestResult.Error(ErrorImportStar));
}
[TestMethod, Priority(1)]
public void TestExtractDefiniteAssignmentAfter() {
SuccessTest("x = 42",
@"def f():
x = 42
for x, y in []:
print x, y",
@"def g():
x = 42
def f():
g()
for x, y in []:
print x, y");
}
[TestMethod, Priority(1)]
public void TestExtractDefiniteAssignmentAfterStmtList() {
SuccessTest("x = 42",
@"def f():
x = 42; x = 100
for x, y in []:
print x, y",
@"def g():
x = 42
def f():
g(); x = 100
for x, y in []:
print x, y");
}
[TestMethod, Priority(1)]
public void TestExtractDefiniteAssignmentAfterStmtListRead() {
SuccessTest("x = 100",
@"def f():
x = 100; x
for x, y in []:
print (x, y)",
@"def g():
x = 100
return x
def f():
x = g(); x
for x, y in []:
print (x, y)");
}
[TestMethod, Priority(1)]
[TestCategory("10s")]
public void TestAllNodes() {
var prefixes = new string[] { " # fob\r\n", "" };
var suffixes = new string[] { " # oar", "" };
foreach (var suffix in suffixes) {
foreach (var prefix in prefixes) {
foreach (var testCase in TestExpressions.Expressions) {
if (testCase.StartsWith("yield")) {
// not currently supported
continue;
}
var text = prefix + testCase + suffix;
string expected = String.Format("{1}def g():\r\n return {0}\r\n\r\ng(){2}", testCase, prefix, suffix);
SuccessTest(new Span(prefix.Length, testCase.Length), text, expected);
}
}
}
var bannedStmts = new[] { "break", "continue", "return abc" };
var allStmts = TestExpressions.Statements2x
.Except(bannedStmts)
.Select(text => new { Text = text, Version = PythonLanguageVersion.V27 })
.Concat(
TestExpressions.Statements3x
.Select(text => new { Text = text, Version = PythonLanguageVersion.V33 }));
foreach (var suffix in suffixes) {
foreach (var prefix in prefixes) {
foreach (var stmtTest in allStmts) {
var text = prefix + stmtTest.Text + suffix;
var assignments = GetAssignments(text, stmtTest.Version);
string expected;
if (assignments.Length > 0 && stmtTest.Text != "del x") {
expected = String.Format(
"{1}def g():\r\n{0}\r\n return {3}\r\n\r\n{3} = g(){2}",
TestExpressions.IndentCode(stmtTest.Text, " "),
prefix,
suffix,
String.Join(", ", assignments)
);
} else {
expected = String.Format(
"{1}def g():\r\n{0}\r\n\r\ng(){2}",
TestExpressions.IndentCode(stmtTest.Text, " "),
prefix,
suffix
);
}
SuccessTest(new Span(prefix.Length, stmtTest.Text.Length), text, expected, null, stmtTest.Version.ToVersion());
}
}
}
}
private string[] GetAssignments(string testCase, PythonLanguageVersion version) {
var ast = Parser.CreateParser(new StringReader(testCase), version).ParseFile();
var walker = new TestAssignmentWalker();
ast.Walk(walker);
return walker._names.ToArray();
}
class TestAssignmentWalker : AssignmentWalker {
private readonly NameWalker _walker;
internal readonly List<string> _names = new List<string>();
public TestAssignmentWalker() {
_walker = new NameWalker(this);
}
public override AssignedNameWalker Define {
get { return _walker; }
}
class NameWalker : AssignedNameWalker {
private readonly TestAssignmentWalker _outer;
public NameWalker(TestAssignmentWalker outer) {
_outer = outer;
}
public override bool Walk(NameExpression node) {
_outer._names.Add(node.Name);
return true;
}
}
public override bool Walk(FunctionDefinition node) {
_names.Add(node.Name);
return base.Walk(node);
}
public override bool Walk(ClassDefinition node) {
_names.Add(node.Name);
return base.Walk(node);
}
public override bool Walk(ImportStatement node) {
var vars = node.Variables;
for (int i = 0; i < vars.Length; i++) {
if (vars[i] != null) {
_names.Add(vars[i].Name);
}
}
return base.Walk(node);
}
public override bool Walk(FromImportStatement node) {
var vars = node.Variables;
for (int i = 0; i < vars.Length; i++) {
if (vars[i] != null) {
_names.Add(vars[i].Name);
}
}
return base.Walk(node);
}
}
[TestMethod, Priority(1)]
public void TestExtractDefiniteAssignmentAfterStmtListMultipleAssign() {
SuccessTest("x = 100; x = 200",
@"def f():
x = 100; x = 200; x
for x, y in []:
print (x, y)",
@"def g():
x = 100; x = 200
return x
def f():
x = g(); x
for x, y in []:
print (x, y)");
}
[TestMethod, Priority(1)]
public void TestExtractFromClass() {
ExtractMethodTest(
@"class C:
abc = 42
oar = 100", "abc .. 100", TestResult.Error(ErrorExtractFromClass));
}
[TestMethod, Priority(1)]
public void TestExtractSuiteWhiteSpace() {
SuccessTest("x .. 200",
@"def f():
x = 100
y = 200",
@"def g():
x = 100
y = 200
def f():
g()");
SuccessTest("x .. 200",
@"def f():
a = 300
x = 100
y = 200",
@"def g():
x = 100
y = 200
def f():
a = 300
g()");
}
/// <summary>
/// Test cases that verify we correctly identify when not all paths contain return statements.
/// </summary>
[TestMethod, Priority(1)]
public void TestNotAllCodePathsReturn() {
TestMissingReturn("for i .. 23", @"def f(x):
for i in xrange(100):
break
return 42
else:
return 23
");
TestMissingReturn("if x .. Exception()", @"def f(x):
if x:
return 42
elif x:
raise Exception()
");
TestMissingReturn("if x .. 200", @"def f(x):
if x:
def abc():
return 42
elif x:
return 100
else:
return 200
");
TestMissingReturn("if x .. 100", @"def f(x):
if x:
return 42
elif x:
return 100
");
TestMissingReturn("if x .. pass", @"def f(x):
if x:
return 42
elif x:
return 100
else:
pass
");
TestMissingReturn("if True .. pass", @"def f():
abc = 100
if True:
return 100
else:
pass
print('hello')");
TestMissingReturn("if x .. aaa",
@"class C:
def f(self):
if x == 0:
return aaa");
}
[TestMethod, Priority(1)]
public void TestReturnWithOutputVars() {
TestReturnWithOutputs("if x .. 100", @"def f(x):
if x:
x = 200
return 42
else:
return 100
print(x)
");
}
[TestMethod, Priority(1)]
public void TestCannotRefactorYield() {
TestBadYield("yield 42", @"def f(x):
yield 42
");
TestBadYield("yield 42", @"def f(x):
for i in xrange(100):
yield 42
");
}
[TestMethod, Priority(1)]
public void TestContinueWithoutLoop() {
TestBadContinue("continue", @"def f(x):
for i in xrange(100):
continue
");
}
[TestMethod, Priority(1)]
public void TestBreakWithoutLoop() {
TestBadBreak("break", @"def f(x):
for i in xrange(100):
break
");
}
/// <summary>
/// Test cases which make sure we have the right ranges for each statement when doing extract method
/// and that we don't mess up the code before/after the statement.
/// </summary>
[TestMethod, Priority(1)]
public void StatementTests() {
SuccessTest("b",
@"def f():
return (a or
b or
c)",
@"def g():
return b
def f():
return (a or
g() or
c)");
SuccessTest("assert False",
@"x = 1
assert False
x = 2",
@"x = 1
def g():
assert False
g()
x = 2");
SuccessTest("x += 2",
@"x = 1
x += 2
x = 2",
@"x = 1
def g():
x += 2
g()
x = 2");
SuccessTest("x = 100",
@"x = 1
x = 100
x = 2",
@"x = 1
def g():
x = 100
g()
x = 2");
SuccessTest("class C: pass",
@"x = 1
class C: pass
x = 2",
@"x = 1
def g():
class C: pass
return C
C = g()
x = 2");
SuccessTest("del fob",
@"x = 1
del fob
x = 2",
@"x = 1
def g():
del fob
g()
x = 2");
SuccessTest("pass",
@"x = 1
pass
x = 2",
@"x = 1
def g():
pass
g()
x = 2");
SuccessTest("def f(): pass",
@"x = 1
def f(): pass
x = 2",
@"x = 1
def g():
def f(): pass
return f
f = g()
x = 2");
SuccessTest("for .. pass",
@"x = 1
for i in xrange(100):
pass
x = 2",
@"x = 1
def g():
for i in xrange(100):
pass
return i
i = g()
x = 2");
SuccessTest("if True: .. pass",
@"x = 1
if True:
pass
x = 2",
@"x = 1
def g():
if True:
pass
g()
x = 2");
SuccessTest("if True: .. pass",
@"x = 1
if True:
42
else:
pass
x = 2",
@"x = 1
def g():
if True:
42
else:
pass
g()
x = 2");
SuccessTest("if True: .. pass",
@"x = 1
if True:
42
elif False:
pass
x = 2",
@"x = 1
def g():
if True:
42
elif False:
pass
g()
x = 2");
SuccessTest("import sys",
@"x = 1
import sys
x = 2",
@"x = 1
def g():
import sys
return sys
sys = g()
x = 2");
SuccessTest("print 42",
@"x = 1
print 42
x = 2",
@"x = 1
def g():
print 42
g()
x = 2");
SuccessTest("raise Exception()",
@"x = 1
raise Exception()
x = 2",
@"x = 1
def g():
raise Exception()
g()
x = 2");
SuccessTest("return 100",
@"x = 1
return 100
x = 2",
@"x = 1
def g():
return 100
return g()
x = 2");
SuccessTest("try: .. pass",
@"x = 1
try:
42
except:
pass
x = 2",
@"x = 1
def g():
try:
42
except:
pass
g()
x = 2");
SuccessTest("try: .. pass",
@"x = 1
try:
42
finally:
pass
x = 2",
@"x = 1
def g():
try:
42
finally:
pass
g()
x = 2");
SuccessTest("try: .. pass",
@"x = 1
try:
42
except:
100
else:
pass
x = 2",
@"x = 1
def g():
try:
42
except:
100
else:
pass
g()
x = 2");
SuccessTest("while .. pass",
@"x = 1
while True:
pass
x = 2",
@"x = 1
def g():
while True:
pass
g()
x = 2");
SuccessTest("while .. pass",
@"x = 1
while True:
42
else:
pass
x = 2",
@"x = 1
def g():
while True:
42
else:
pass
g()
x = 2");
SuccessTest("with .. pass",
@"x = 1
with abc:
pass
x = 2",
@"x = 1
def g():
with abc:
pass
g()
x = 2");
SuccessTest("with .. pass",
@"x = 1
with abc as fob:
pass
x = 2",
@"x = 1
def g():
with abc as fob:
pass
g()
x = 2");
SuccessTest("with .. (name)",
@"def f():
name = 'hello'
with open('Fob', 'rb') as f:
print(name)
",
@"def g(name):
with open('Fob', 'rb') as f:
print(name)
def f():
name = 'hello'
g(name)
");
SuccessTest("x .. Oar()",
@"class C:
def f():
if True:
pass
else:
pass
x = Fob()
y = Oar()",
@"def g():
x = Fob()
y = Oar()
class C:
def f():
if True:
pass
else:
pass
g()");
}
[TestMethod, Priority(1)]
public void ClassTests() {
SuccessTest("x = fob",
@"class C(object):
'''Doc string'''
def abc(self, fob):
x = fob
print(x)",
@"class C(object):
'''Doc string'''
def g(self, fob):
x = fob
return x
def abc(self, fob):
x = self.g(fob)
print(x)", scopeName: "C");
SuccessTest("print(self.abc)",
@"class C:
def f(self):
print(self.abc)",
@"class C:
def g(self):
print(self.abc)
def f(self):
self.g()", scopeName:"C");
SuccessTest("print(self.abc, aaa)",
@"class C:
def f(self):
aaa = 42
print(self.abc, aaa)",
@"class C:
def g(self, aaa):
print(self.abc, aaa)
def f(self):
aaa = 42
self.g(aaa)", scopeName: "C");
SuccessTest("aaa = 42",
@"class C:
def f(self):
aaa = 42",
@"class C:
def g(self):
aaa = 42
def f(self):
self.g()", scopeName: "C");
SuccessTest("aaa = 42",
@"class C:
@staticmethod
def f():
aaa = 42",
@"class C:
@staticmethod
def g():
aaa = 42
@staticmethod
def f():
C.g()", scopeName: "C");
SuccessTest("aaa = 42",
@"class C:
@classmethod
def f(cls):
aaa = 42",
@"class C:
@classmethod
def g(cls):
aaa = 42
@classmethod
def f(cls):
cls.g()", scopeName: "C");
SuccessTest("aaa = 42",
@"class C:
def f(weird):
aaa = 42",
@"class C:
def g(weird):
aaa = 42
def f(weird):
weird.g()", scopeName: "C");
SuccessTest("print('hello')",
@"class C:
class D:
def f(self):
print('hello')",
@"class C:
class D:
def g(self):
print('hello')
def f(self):
self.g()", scopeName: "D");
}
[TestMethod, Priority(1)]
public void TestComprehensions() {
SuccessTest("i % 2 == 0", @"def f():
x = [i for i in range(100) if i % 2 == 0]", @"def g(i):
return i % 2 == 0
def f():
x = [i for i in range(100) if g(i)]");
SuccessTest("i % 2 == 0", @"def f():
x = (i for i in range(100) if i % 2 == 0)", @"def g(i):
return i % 2 == 0
def f():
x = (i for i in range(100) if g(i))");
SuccessTest("i % 2 == 0", @"def f():
x = {i for i in range(100) if i % 2 == 0}", @"def g(i):
return i % 2 == 0
def f():
x = {i for i in range(100) if g(i)}", version: new Version(3, 2));
SuccessTest("(k+v) % 2 == 0", @"def f():
x = {k:v for k,v in range(100) if (k+v) % 2 == 0}", @"def g(k, v):
return (k+v) % 2 == 0
def f():
x = {k:v for k,v in range(100) if g(k, v)}", version: new Version(3, 2));
}
[TestMethod, Priority(1)]
public void SuccessfulTests() {
SuccessTest("x .. 100",
@"def f():
z = 200
x = z
z = 42
y = 100
print(x, y)",
@"def g(z):
x = z
z = 42
y = 100
return x, y
def f():
z = 200
x, y = g(z)
print(x, y)");
SuccessTest("x .. 100",
@"def f():
x = 42
y = 100
print(x, y)",
@"def g():
x = 42
y = 100
return x, y
def f():
x, y = g()
print(x, y)");
SuccessTest("42",
@"def f():
x = 42",
@"def g():
return 42
def f():
x = g()");
SuccessTest("oar;baz",
@"def f():
fob;oar;baz;quox",
@"def g():
oar;baz
def f():
fob;g();quox");
SuccessTest("x() .. = 100",
@"x = 42
while True:
x()
x = 100",
@"x = 42
def g(x):
x()
x = 100
return x
while True:
x = g(x)", parameters: new[] { "x" });
SuccessTest("x = 2 .. x)",
@"def f():
x = 1
x = 2
print(x)",
@"def g():
x = 2
print(x)
def f():
x = 1
g()");
SuccessTest("for i in .. return 42",
@"def f():
for i in xrange(100):
break
return 42",
@"def g():
for i in xrange(100):
break
return 42
def f():
g()");
SuccessTest("if x .. 100",
@"def f(x):
if x:
return 42
return 100",
@"def g(x):
if x:
return 42
return 100
def f(x):
return g(x)");
SuccessTest("if x .. 200",
@"def f(x):
if x:
return 42
elif x:
return 100
else:
return 200",
@"def g(x):
if x:
return 42
elif x:
return 100
else:
return 200
def f(x):
return g(x)");
SuccessTest("if x .. 200",
@"def f(x):
if x:
return 42
elif x:
raise Exception()
else:
return 200",
@"def g(x):
if x:
return 42
elif x:
raise Exception()
else:
return 200
def f(x):
return g(x)");
SuccessTest("if x .. Exception()",
@"def f(x):
if x:
return 42
else:
raise Exception()",
@"def g(x):
if x:
return 42
else:
raise Exception()
def f(x):
return g(x)");
SuccessTest("print(x)",
@"def f():
x = 1
print(x)",
@"def g(x):
print(x)
def f():
x = 1
g(x)");
SuccessTest("x = 2 .. x)",
@"def f():
x = 1
x = 2
print(x)",
@"def g():
x = 2
print(x)
def f():
x = 1
g()");
SuccessTest("class C: pass",
@"def f():
class C: pass
print C",
@"def g():
class C: pass
return C
def f():
C = g()
print C");
SuccessTest("def x(): pass",
@"def f():
def x(): pass
print x",
@"def g():
def x(): pass
return x
def f():
x = g()
print x");
SuccessTest("import sys",
@"def f():
import sys
print sys",
@"def g():
import sys
return sys
def f():
sys = g()
print sys");
SuccessTest("import sys as oar",
@"def f():
import sys as oar
print oar",
@"def g():
import sys as oar
return oar
def f():
oar = g()
print oar");
SuccessTest("from sys import oar",
@"def f():
from sys import oar
print oar",
@"def g():
from sys import oar
return oar
def f():
oar = g()
print oar");
SuccessTest("from sys import oar as baz",
@"def f():
from sys import oar as baz
print baz",
@"def g():
from sys import oar as baz
return baz
def f():
baz = g()
print baz");
SuccessTest("return 42",
@"def f():
return 42",
@"def g():
return 42
def f():
return g()");
SuccessTest("return x",
@"def f():
x = 42
return x",
@"def g(x):
return x
def f():
x = 42
return g(x)");
SuccessTest("x = .. = 100",
@"def f():
x = 42
y = 100
return x, y",
@"def g():
x = 42
y = 100
return x, y
def f():
x, y = g()
return x, y");
SuccessTest("x()",
@"x = 42
while True:
x()
x = 100",
@"x = 42
def g(x):
return x()
while True:
g(x)
x = 100",
parameters: new[] { "x"});
SuccessTest("x()",
@"x = 42
while True:
x()
x = 100",
@"x = 42
def g():
return x()
while True:
g()
x = 100");
SuccessTest("x = 42",
@"x = 42
print(x)",
@"def g():
x = 42
return x
x = g()
print(x)");
SuccessTest("l = .. return r",
@"def f():
r = None
l = fob()
if l:
r = l[0]
return r",
@"def g(r):
l = fob()
if l:
r = l[0]
return r
def f():
r = None
return g(r)");
SuccessTest("42",
@"def f(x):
return (42)",
@"def g():
return 42
def f(x):
return (g())");
}
[TestMethod, Priority(1)]
public void ExtractAsyncFunction() {
// Ensure extracted bodies that use await generate async functions
var V35 = new Version(3, 5);
SuccessTest("x",
@"async def f():
return await x",
@"def g():
return x
async def f():
return await g()", version: V35);
SuccessTest("await x",
@"async def f():
return await x",
@"async def g():
return await x
async def f():
return await g()", version: V35);
}
private void SuccessTest(Span extract, string input, string result, string scopeName = null, Version version = null, string[] parameters = null) {
ExtractMethodTest(input, extract, TestResult.Success(result), scopeName: scopeName, version: version, parameters: parameters);
}
private void SuccessTest(string extract, string input, string result, string scopeName = null, Version version = null, string[] parameters = null) {
ExtractMethodTest(input, extract, TestResult.Success(result), scopeName: scopeName, version: version, parameters: parameters);
}
class TestResult {
public readonly bool IsError;
public readonly string Text;
public static TestResult Error(string message) {
return new TestResult(message, true);
}
public static TestResult Success(string code) {
return new TestResult(code, false);
}
public TestResult(string text, bool isError) {
Text = text;
IsError = isError;
}
}
private void TestMissingReturn(string extract, string input) {
ExtractMethodTest(input, extract, TestResult.Error(ErrorReturn));
}
private void TestReturnWithOutputs(string extract, string input) {
ExtractMethodTest(input, extract, TestResult.Error(ErrorReturnWithOutputs));
}
private void TestBadYield(string extract, string input) {
ExtractMethodTest(input, extract, TestResult.Error(ErrorYield));
}
private void TestBadContinue(string extract, string input) {
ExtractMethodTest(input, extract, TestResult.Error(ErrorContinue));
}
private void TestBadBreak(string extract, string input) {
ExtractMethodTest(input, extract, TestResult.Error(ErrorBreak));
}
private void ExtractMethodTest(string input, object extract, TestResult expected, string scopeName = null, string targetName = "g", Version version = null, params string[] parameters) {
Func<Span> textRange = () => {
return GetSelectionSpan(input, extract);
};
ExtractMethodTest(input, textRange, expected, scopeName, targetName, version, parameters);
}
internal static Span GetSelectionSpan(string input, object extract) {
string exStr = extract as string;
if (exStr != null) {
if (exStr.IndexOf(" .. ") != -1) {
var pieces = exStr.Split(new[] { " .. " }, 2, StringSplitOptions.None);
int start = input.IndexOf(pieces[0]);
int end = input.IndexOf(pieces[1]) + pieces[1].Length;
return Span.FromBounds(start, end);
} else {
int start = input.IndexOf(exStr);
int length = exStr.Length;
return new Span(start, length);
}
}
return (Span)extract;
}
private void ExtractMethodTest(string input, Func<Span> extract, TestResult expected, string scopeName = null, string targetName = "g", Version version = null, params string[] parameters) {
var fact = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version ?? new Version(2, 7));
var serviceProvider = PythonToolsTestUtilities.CreateMockServiceProvider(suppressTaskProvider: true);
using (var analyzer = new VsProjectAnalyzer(serviceProvider, fact)) {
var buffer = new MockTextBuffer(input, "Python", "C:\\fob.py");
var view = new MockTextView(buffer);
buffer.Properties.AddProperty(typeof(VsProjectAnalyzer), analyzer);
analyzer.MonitorTextBufferAsync(buffer).Wait();
var extractInput = new ExtractMethodTestInput(true, scopeName, targetName, parameters ?? new string[0]);
view.Selection.Select(
new SnapshotSpan(view.TextBuffer.CurrentSnapshot, extract()),
false
);
new MethodExtractor(serviceProvider, view).ExtractMethod(extractInput).Wait();
if (expected.IsError) {
Assert.AreEqual(expected.Text, extractInput.FailureReason);
Assert.AreEqual(input, view.TextBuffer.CurrentSnapshot.GetText());
} else {
Assert.AreEqual(null, extractInput.FailureReason);
Assert.AreEqual(expected.Text, view.TextBuffer.CurrentSnapshot.GetText());
}
}
}
class ExtractMethodTestInput : IExtractMethodInput {
private readonly bool _shouldExpand;
private readonly string _scopeName, _targetName;
private readonly string[] _parameters;
private string _failureReason;
public ExtractMethodTestInput(bool shouldExpand, string scopeName, string targetName, string[] parameters) {
_shouldExpand = shouldExpand;
_scopeName = scopeName;
_parameters = parameters;
_targetName = targetName;
}
public bool ShouldExpandSelection() {
return _shouldExpand;
}
public ExtractMethodRequest GetExtractionInfo(ExtractedMethodCreator previewer) {
AP.ScopeInfo scope = null;
if (_scopeName == null) {
scope = previewer.LastExtraction.scopes[0];
} else {
foreach (var foundScope in previewer.LastExtraction.scopes) {
if (foundScope.name == _scopeName) {
scope = foundScope;
break;
}
}
}
Assert.AreNotEqual(null, scope);
var requestView = new ExtractMethodRequestView(PythonToolsTestUtilities.CreateMockServiceProvider(), previewer);
requestView.TargetScope = requestView.TargetScopes.Single(s => s.Scope == scope);
requestView.Name = _targetName;
foreach (var cv in requestView.ClosureVariables) {
cv.IsClosure = !_parameters.Contains(cv.Name);
}
Assert.IsTrue(requestView.IsValid);
var request = requestView.GetRequest();
Assert.IsNotNull(request);
return request;
}
public void CannotExtract(string reason) {
_failureReason = reason;
}
public string FailureReason {
get {
return _failureReason;
}
}
}
}
}
| |
////////////////////////////////////////////////////////////////
// //
// Neoforce Controls //
// //
////////////////////////////////////////////////////////////////
// //
// File: Bevel.cs //
// //
// Version: 0.7 //
// //
// Date: 11/09/2010 //
// //
// Author: Tom Shane //
// //
////////////////////////////////////////////////////////////////
// //
// Copyright (c) by Tom Shane //
// //
////////////////////////////////////////////////////////////////
#region //// Using /////////////
using Microsoft.Xna.Framework;
////////////////////////////////////////////////////////////////////////////
using Microsoft.Xna.Framework.Graphics;
////////////////////////////////////////////////////////////////////////////
#endregion
namespace TomShane.Neoforce.Controls
{
#region //// Enums /////////////
////////////////////////////////////////////////////////////////////////////
public enum BevelStyle
{
None,
Flat,
Etched,
Bumped,
Lowered,
Raised
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public enum BevelBorder
{
None,
Left,
Top,
Right,
Bottom,
All
}
////////////////////////////////////////////////////////////////////////////
#endregion
public class Bevel: Control
{
#region //// Fields ////////////
////////////////////////////////////////////////////////////////////////////
private BevelBorder border = BevelBorder.All;
private BevelStyle style = BevelStyle.Etched;
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Properties ////////
////////////////////////////////////////////////////////////////////////////
public BevelBorder Border
{
get { return border; }
set
{
if (border != value)
{
border = value;
if (!Suspended) OnBorderChanged(new EventArgs());
}
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public BevelStyle Style
{
get { return style; }
set
{
if (style != value)
{
style = value;
if (!Suspended) OnStyleChanged(new EventArgs());
}
}
}
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Events ////////////
////////////////////////////////////////////////////////////////////////////
public event EventHandler BorderChanged;
public event EventHandler StyleChanged;
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Construstors //////
////////////////////////////////////////////////////////////////////////////
public Bevel(Manager manager): base(manager)
{
CanFocus = false;
Passive = true;
Width = 64;
Height = 64;
}
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Methods ///////////
////////////////////////////////////////////////////////////////////////////
public override void Init()
{
base.Init();
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected internal override void InitSkin()
{
base.InitSkin();
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected override void DrawControl(Renderer renderer, Rectangle rect, GameTime gameTime)
{
if (Border != BevelBorder.None && Style != BevelStyle.None)
{
if (Border != BevelBorder.All)
{
DrawPart(renderer, rect, Border, Style, false);
}
else
{
DrawPart(renderer, rect, BevelBorder.Left, Style, true);
DrawPart(renderer, rect, BevelBorder.Top, Style, true);
DrawPart(renderer, rect, BevelBorder.Right, Style, true);
DrawPart(renderer, rect, BevelBorder.Bottom, Style, true);
}
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void DrawPart(Renderer renderer, Rectangle rect, BevelBorder pos, BevelStyle style, bool all)
{
SkinLayer layer = Skin.Layers["Control"];
Color c1 = Utilities.ParseColor(layer.Attributes["LightColor"].Value);
Color c2 = Utilities.ParseColor(layer.Attributes["DarkColor"].Value);
Color c3 = Utilities.ParseColor(layer.Attributes["FlatColor"].Value);
if (Color != UndefinedColor) c3 = Color;
Texture2D img = Skin.Layers["Control"].Image.Resource;
int x1 = 0; int y1 = 0; int w1 = 0; int h1 = 0;
int x2 = 0; int y2 = 0; int w2 = 0; int h2 = 0;
if (style == BevelStyle.Bumped || style == BevelStyle.Etched)
{
if (all && (pos == BevelBorder.Top || pos == BevelBorder.Bottom))
{
rect = new Rectangle(rect.Left + 1, rect.Top, rect.Width - 2, rect.Height);
}
else if (all && (pos == BevelBorder.Left))
{
rect = new Rectangle(rect.Left, rect.Top, rect.Width, rect.Height - 1);
}
switch (pos)
{
case BevelBorder.Left:
{
x1 = rect.Left; y1 = rect.Top; w1 = 1; h1 = rect.Height;
x2 = x1 + 1; y2 = y1; w2 = w1; h2 = h1;
break;
}
case BevelBorder.Top:
{
x1 = rect.Left; y1 = rect.Top; w1 = rect.Width; h1 = 1;
x2 = x1; y2 = y1 + 1; w2 = w1; h2 = h1;
break;
}
case BevelBorder.Right:
{
x1 = rect.Left + rect.Width - 2; y1 = rect.Top; w1 = 1; h1 = rect.Height;
x2 = x1 + 1; y2 = y1; w2 = w1; h2 = h1;
break;
}
case BevelBorder.Bottom:
{
x1 = rect.Left; y1 = rect.Top + rect.Height - 2; w1 = rect.Width; h1 = 1;
x2 = x1; y2 = y1 + 1; w2 = w1; h2 = h1;
break;
}
}
}
else
{
switch (pos)
{
case BevelBorder.Left:
{
x1 = rect.Left; y1 = rect.Top; w1 = 1; h1 = rect.Height;
break;
}
case BevelBorder.Top:
{
x1 = rect.Left; y1 = rect.Top; w1 = rect.Width; h1 = 1;
break;
}
case BevelBorder.Right:
{
x1 = rect.Left + rect.Width - 1; y1 = rect.Top; w1 = 1; h1 = rect.Height;
break;
}
case BevelBorder.Bottom:
{
x1 = rect.Left; y1 = rect.Top + rect.Height - 1; w1 = rect.Width; h1 = 1;
break;
}
}
}
switch (Style)
{
case BevelStyle.Bumped:
{
renderer.Draw(img, new Rectangle(x1, y1, w1, h1), c1);
renderer.Draw(img, new Rectangle(x2, y2, w2, h2), c2);
break;
}
case BevelStyle.Etched:
{
renderer.Draw(img, new Rectangle(x1, y1, w1, h1), c2);
renderer.Draw(img, new Rectangle(x2, y2, w2, h2), c1);
break;
}
case BevelStyle.Raised:
{
Color c = c1;
if (pos == BevelBorder.Left || pos == BevelBorder.Top) c = c1;
else c = c2;
renderer.Draw(img, new Rectangle(x1, y1, w1, h1), c);
break;
}
case BevelStyle.Lowered:
{
Color c = c1;
if (pos == BevelBorder.Left || pos == BevelBorder.Top) c = c2;
else c = c1;
renderer.Draw(img, new Rectangle(x1, y1, w1, h1), c);
break;
}
default:
{
renderer.Draw(img, new Rectangle(x1, y1, w1, h1), c3);
break;
}
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected virtual void OnBorderChanged(EventArgs e)
{
if (BorderChanged != null) BorderChanged.Invoke(this, e);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected virtual void OnStyleChanged(EventArgs e)
{
if (StyleChanged != null) StyleChanged.Invoke(this, e);
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
}
| |
using System;
using System.Data;
using Codentia.Common.Data;
using Codentia.Common.Helper;
using Codentia.Common.Logging;
using Codentia.Common.Logging.BL;
using Codentia.Common.Membership.Providers;
namespace Codentia.Common.Membership
{
/// <summary>
/// This class exposes methods to create, read, update data related to Email Addresses
/// </summary>
public static class ContactData
{
/// <summary>
/// Check if a specified email address exists or not
/// </summary>
/// <param name="emailAddress">emailAddress to check</param>
/// <returns>Does Exist</returns>
public static bool EmailAddressExists(string emailAddress)
{
return EmailAddressExists(Guid.Empty, emailAddress);
}
/// <summary>
/// Check if a specified email address exists or not
/// </summary>
/// <param name="txnId">Transaction Id of ADO.Net Transaction</param>
/// <param name="emailAddress">emailAddress to check</param>
/// <returns>Does Exist</returns>
public static bool EmailAddressExists(Guid txnId, string emailAddress)
{
ParameterCheckHelper.CheckIsValidEmailAddress(emailAddress, 255, "emailAddress");
DbParameter[] spParams =
{
new DbParameter("@EmailAddress", DbType.StringFixedLength, 255, emailAddress),
new DbParameter("@Exists", DbType.Boolean, ParameterDirection.Output, false)
};
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.EmailAddress_ExistsByAddress", spParams, txnId);
return Convert.ToBoolean(spParams[1].Value);
}
/// <summary>
/// Check if a specified email address Id exists or not
/// </summary>
/// <param name="emailAddressId">emailAddressId to check</param>
/// <returns>Does Exist</returns>
public static bool EmailAddressExists(int emailAddressId)
{
return EmailAddressExists(Guid.Empty, emailAddressId);
}
/// <summary>
/// Check if a specified email address Id exists or not
/// </summary>
/// <param name="txnId">Transaction Id of ADO.Net Transaction</param>
/// <param name="emailAddressId">emailAddressId to check</param>
/// <returns>Does Exist</returns>
public static bool EmailAddressExists(Guid txnId, int emailAddressId)
{
ParameterCheckHelper.CheckIsValidId(emailAddressId, "emailAddressId");
DbParameter[] spParams =
{
new DbParameter("@EmailAddressId", DbType.Int32, emailAddressId),
new DbParameter("@Exists", DbType.Boolean, ParameterDirection.Output, false)
};
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.EmailAddress_ExistsById", spParams, txnId);
return Convert.ToBoolean(spParams[1].Value);
}
/// <summary>
/// CreateEmailAddress and return the new id
/// </summary>
/// <param name="emailAddress">The email address.</param>
/// <returns>
/// The emailAddressId
/// </returns>
public static int CreateEmailAddress(string emailAddress)
{
return CreateEmailAddress(Guid.Empty, emailAddress);
}
/// <summary>
/// CreateEmailAddress and return the new id (in a transaction)
/// </summary>
/// <param name="txnId">Transaction Id of ADO.Net Transaction</param>
/// <param name="emailAddress">The email address.</param>
/// <returns>
/// The emailAddressId
/// </returns>
public static int CreateEmailAddress(Guid txnId, string emailAddress)
{
int emailAddressId;
ParameterCheckHelper.CheckIsValidEmailAddress(emailAddress, 256, "emailAddress");
if (EmailAddressExists(txnId, emailAddress))
{
throw new ArgumentException(string.Format("emailAddress: {0} already exists", emailAddress));
}
DbParameter[] spParams =
{
new DbParameter("@EmailAddress", DbType.StringFixedLength, 256, emailAddress),
new DbParameter("@EmailAddressId", DbType.Int32, ParameterDirection.Output, 0)
};
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.EmailAddress_Create", spParams, txnId);
emailAddressId = Convert.ToInt32(spParams[1].Value);
LogManager.Instance.AddToLog(LogMessageType.Information, "EmailAddressData", string.Format("CreateEmailAddress: emailAddress={0}", emailAddress));
return emailAddressId;
}
/// <summary>
/// Retrieve the SystemUser (if any) associated to an email address
/// </summary>
/// <param name="emailAddressId">email addressId</param>
/// <returns>The systemUserId</returns>
public static int GetSystemUserIdForEmailAddress(int emailAddressId)
{
return GetSystemUserIdForEmailAddress(Guid.Empty, emailAddressId);
}
/// <summary>
/// Retrieve the SystemUser (if any) associated to an email address
/// </summary>
/// <param name="txnId">Transaction Id of ADO.Net Transaction</param>
/// <param name="emailAddressId">email addressId</param>
/// <returns>The systemUserId</returns>
public static int GetSystemUserIdForEmailAddress(Guid txnId, int emailAddressId)
{
if (!EmailAddressExists(txnId, emailAddressId))
{
throw new ArgumentException(string.Format("emailAddressId: {0} does not exist", emailAddressId));
}
DbParameter[] spParams =
{
new DbParameter("@EmailAddressId", DbType.Int32, emailAddressId),
new DbParameter("@SystemUserId", DbType.Int32, ParameterDirection.Output, 0)
};
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.EmailAddress_GetSystemUserId", spParams, txnId);
int systemUserId = 0;
if (spParams[1].Value != DBNull.Value)
{
systemUserId = Convert.ToInt32(spParams[1].Value);
}
return systemUserId;
}
/// <summary>
/// Gets the email address data.
/// </summary>
/// <param name="emailAddress">The email address.</param>
/// <returns>DataTable - EmailAddress</returns>
public static DataTable GetEmailAddressData(string emailAddress)
{
return GetEmailAddressData(Guid.Empty, emailAddress);
}
/// <summary>
/// Retrieve email address data (by address) in a transaction
/// </summary>
/// <param name="txnId">Transaction Id of ADO.Net Transaction</param>
/// <param name="emailAddress">The email address</param>
/// <returns>DataTable - Email Address</returns>
public static DataTable GetEmailAddressData(Guid txnId, string emailAddress)
{
ParameterCheckHelper.CheckIsValidString(emailAddress, "emailAddress", false);
DbParameter[] spParams =
{
new DbParameter("@EmailAddress", DbType.StringFixedLength, 255, emailAddress)
};
DataTable result = DbInterface.ExecuteProcedureDataTable(CESqlMembershipProvider.ProviderDbDataSource, "dbo.EmailAddress_GetByAddress", spParams, txnId);
if (result == null || result.Rows.Count == 0)
{
throw new ArgumentException(string.Format("emailAddress: {0} does not exist", emailAddress));
}
return result;
}
/// <summary>
/// Retrieve email address data (by Id)
/// </summary>
/// <param name="emailAddressId">The emailAddressId</param>
/// <returns>DataTable - EmailAddress</returns>
public static DataTable GetEmailAddressData(int emailAddressId)
{
return GetEmailAddressData(Guid.Empty, emailAddressId);
}
/// <summary>
/// Gets the email address data.
/// </summary>
/// <param name="txnId">The TXN id.</param>
/// <param name="emailAddressId">The email address id.</param>
/// <returns>DataTable - EmailAddress</returns>
public static DataTable GetEmailAddressData(Guid txnId, int emailAddressId)
{
ParameterCheckHelper.CheckIsValidId(emailAddressId, "emailAddressId");
if (!EmailAddressExists(txnId, emailAddressId))
{
throw new ArgumentException(string.Format("emailAddressId: {0} does not exist", emailAddressId));
}
DbParameter[] spParams =
{
new DbParameter("@EmailAddressId", DbType.Int32, emailAddressId)
};
return DbInterface.ExecuteProcedureDataTable(CESqlMembershipProvider.ProviderDbDataSource, "dbo.EmailAddress_GetById", spParams, txnId);
}
/// <summary>
/// Confirm Email Address (from a confirmation email link)
/// </summary>
/// <param name="emailAddress">email address to confirm</param>
/// <param name="confirmGuid">Guid from parameter string</param>
/// <returns>bool - true = successful, false - unsuccessful</returns>
public static bool Confirm(string emailAddress, Guid confirmGuid)
{
ParameterCheckHelper.CheckIsValidString(emailAddress, "emailAddress", 255, false);
ParameterCheckHelper.CheckIsValidGuid(confirmGuid, "confirmGuid");
DataTable dt = ContactData.GetEmailAddressData(confirmGuid);
if (dt.Rows.Count == 0)
{
throw new ArgumentException(string.Format("confirmGuid: {0} does not exist", confirmGuid));
}
else
{
if (emailAddress != Convert.ToString(dt.Rows[0]["EmailAddress"]))
{
throw new ArgumentException(string.Format("confirmGuid: {0} exists for another emailaddress", confirmGuid));
}
}
DbParameter[] spParams =
{
new DbParameter("@EmailAddress", DbType.StringFixedLength, 255, emailAddress),
new DbParameter("@ConfirmGuid", DbType.Guid, confirmGuid),
new DbParameter("@IsConfirmed", DbType.Boolean, ParameterDirection.Output, false)
};
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.EmailAddress_Confirm", spParams);
LogManager.Instance.AddToLog(LogMessageType.Information, "EmailAddressData", string.Format("ConfirmEmailAddress: emailAddress={0}, confirmGuid={1}", emailAddress, confirmGuid));
return Convert.ToBoolean(spParams[2].Value);
}
/// <summary>
/// Retrieve email address data (by Cookie)
/// </summary>
/// <param name="emailAddressCookie">The emailAddressCookie</param>
/// <returns>DataTable - EmailAddress</returns>
public static DataTable GetEmailAddressData(Guid emailAddressCookie)
{
ParameterCheckHelper.CheckIsValidGuid(emailAddressCookie, "emailAddressCookie");
DbParameter[] spParams =
{
new DbParameter("@Cookie", DbType.Guid, emailAddressCookie)
};
DataTable systemUserData = DbInterface.ExecuteProcedureDataTable(CESqlMembershipProvider.ProviderDbDataSource, "dbo.EmailAddress_GetByCookie", spParams);
return systemUserData;
}
/// <summary>
/// Create a new PhoneNumber record (or return extant, matching id if already created)
/// Always updated as part of another process so needs a transaction Id
/// </summary>
/// <param name="txnId">Transaction Id of ADO.Net Transaction</param>
/// <param name="phoneNumber">PhoneNumber to create entry for</param>
/// <returns>The phoneNumberId</returns>
public static int CreatePhoneNumber(Guid txnId, string phoneNumber)
{
ParameterCheckHelper.CheckIsValidString(phoneNumber, "phoneNumber", false);
phoneNumber = phoneNumber.Replace("(", string.Empty);
phoneNumber = phoneNumber.Replace(")", string.Empty);
phoneNumber = phoneNumber.Replace(" ", string.Empty);
ParameterCheckHelper.CheckStringIsValidPhoneNumber(phoneNumber, 13, "phoneNumber");
DbParameter[] spParams =
{
new DbParameter("@PhoneNumber", DbType.StringFixedLength, 13, phoneNumber),
new DbParameter("@PhoneNumberId", DbType.Int32, ParameterDirection.Output, 0)
};
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.PhoneNumber_Create", spParams, txnId);
return Convert.ToInt32(spParams[1].Value);
}
/// <summary>
/// Retrieve an existing PhoneNumber entry.
/// </summary>
/// <param name="phoneNumberId">The phonenumberId</param>
/// <returns>string - phone number</returns>
public static string GetPhoneNumber(int phoneNumberId)
{
string phoneNumber;
ParameterCheckHelper.CheckIsValidId(phoneNumberId, "phoneNumberId");
DbParameter[] spParams =
{
new DbParameter("@PhoneNumberId", DbType.Int32, phoneNumberId),
new DbParameter("@PhoneNumber", DbType.StringFixedLength, 11, ParameterDirection.Output, DBNull.Value)
};
DbInterface.ExecuteProcedureNoReturn(CESqlMembershipProvider.ProviderDbDataSource, "dbo.PhoneNumber_GetById", spParams);
phoneNumber = Convert.ToString(spParams[1].Value);
if (string.IsNullOrEmpty(phoneNumber))
{
throw new ArgumentException(string.Format("phoneNumberId: {0} does not exist", phoneNumberId));
}
return phoneNumber;
}
/// <summary>
/// Retrieve all addresses associated to an email Address
/// </summary>
/// <param name="emailAddressId">email Address Id</param>
/// <returns>DataTable - EmailAddress</returns>
public static DataTable GetAddressesForEmailAddress(int emailAddressId)
{
ParameterCheckHelper.CheckIsValidId(emailAddressId, "emailAddressId");
if (!EmailAddressExists(emailAddressId))
{
throw new ArgumentException(string.Format("emailAddressId: {0} does not exist", emailAddressId));
}
DbParameter[] spParams =
{
new DbParameter("@EmailAddressId", DbType.Int32, emailAddressId),
new DbParameter("@AssemblyVersion", DbType.String, 10, Abstraction.Version)
};
return DbInterface.ExecuteProcedureDataTable(CESqlMembershipProvider.ProviderDbDataSource, "dbo.EmailAddress_GetAddresses", spParams);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace M2SA.AppGenome.Threading.Internal
{
#region PriorityQueue class
/// <summary>
/// PriorityQueue class
/// This class is not thread safe because we use external lock
/// </summary>
public sealed class PriorityQueue : IEnumerable
{
#region Private members
/// <summary>
/// The number of queues, there is one for each type of priority
/// </summary>
private const int _queuesCount = WorkItemPriority.Highest-WorkItemPriority.Lowest+1;
/// <summary>
/// Work items queues. There is one for each type of priority
/// </summary>
private readonly LinkedList<IHasWorkItemPriority>[] _queues = new LinkedList<IHasWorkItemPriority>[_queuesCount];
/// <summary>
/// The total number of work items within the queues
/// </summary>
private int _workItemsCount;
/// <summary>
/// Use with IEnumerable interface
/// </summary>
private int _version;
#endregion
#region Contructor
/// <summary>
///
/// </summary>
public PriorityQueue()
{
for(int i = 0; i < _queues.Length; ++i)
{
_queues[i] = new LinkedList<IHasWorkItemPriority>();
}
}
#endregion
#region Methods
/// <summary>
/// Enqueue a work item.
/// </summary>
/// <param name="workItem">A work item</param>
public void Enqueue(IHasWorkItemPriority workItem)
{
Debug.Assert(null != workItem);
if (null == workItem)
throw new ArgumentNullException("workItem");
int queueIndex = _queuesCount-(int)workItem.WorkItemPriority-1;
Debug.Assert(queueIndex >= 0);
Debug.Assert(queueIndex < _queuesCount);
_queues[queueIndex].AddLast(workItem);
++_workItemsCount;
++_version;
}
/// <summary>
/// Dequeque a work item.
/// </summary>
/// <returns>Returns the next work item</returns>
public IHasWorkItemPriority Dequeue()
{
IHasWorkItemPriority workItem = null;
if(_workItemsCount > 0)
{
int queueIndex = GetNextNonEmptyQueue(-1);
Debug.Assert(queueIndex >= 0);
workItem = _queues[queueIndex].First.Value;
_queues[queueIndex].RemoveFirst();
Debug.Assert(null != workItem);
--_workItemsCount;
++_version;
}
return workItem;
}
/// <summary>
/// Find the next non empty queue starting at queue queueIndex+1
/// </summary>
/// <param name="queueIndex">The index-1 to start from</param>
/// <returns>
/// The index of the next non empty queue or -1 if all the queues are empty
/// </returns>
private int GetNextNonEmptyQueue(int queueIndex)
{
for(int i = queueIndex+1; i < _queuesCount; ++i)
{
if(_queues[i].Count > 0)
{
return i;
}
}
return -1;
}
/// <summary>
/// The number of work items
/// </summary>
public int Count
{
get
{
return _workItemsCount;
}
}
/// <summary>
/// Clear all the work items
/// </summary>
public void Clear()
{
if (_workItemsCount > 0)
{
foreach(LinkedList<IHasWorkItemPriority> queue in _queues)
{
queue.Clear();
}
_workItemsCount = 0;
++_version;
}
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator to iterate over the work items
/// </summary>
/// <returns>Returns an enumerator</returns>
public IEnumerator GetEnumerator()
{
return new PriorityQueueEnumerator(this);
}
#endregion
#region PriorityQueueEnumerator
/// <summary>
/// The class the implements the enumerator
/// </summary>
private class PriorityQueueEnumerator : IEnumerator
{
private readonly PriorityQueue _priorityQueue;
private int _version;
private int _queueIndex;
private IEnumerator _enumerator;
public PriorityQueueEnumerator(PriorityQueue priorityQueue)
{
_priorityQueue = priorityQueue;
_version = _priorityQueue._version;
_queueIndex = _priorityQueue.GetNextNonEmptyQueue(-1);
if (_queueIndex >= 0)
{
_enumerator = _priorityQueue._queues[_queueIndex].GetEnumerator();
}
else
{
_enumerator = null;
}
}
#region IEnumerator Members
public void Reset()
{
_version = _priorityQueue._version;
_queueIndex = _priorityQueue.GetNextNonEmptyQueue(-1);
if (_queueIndex >= 0)
{
_enumerator = _priorityQueue._queues[_queueIndex].GetEnumerator();
}
else
{
_enumerator = null;
}
}
public object Current
{
get
{
Debug.Assert(null != _enumerator);
return _enumerator.Current;
}
}
public bool MoveNext()
{
if (null == _enumerator)
{
return false;
}
if(_version != _priorityQueue._version)
{
throw new InvalidOperationException("The collection has been modified");
}
if (!_enumerator.MoveNext())
{
_queueIndex = _priorityQueue.GetNextNonEmptyQueue(_queueIndex);
if(-1 == _queueIndex)
{
return false;
}
_enumerator = _priorityQueue._queues[_queueIndex].GetEnumerator();
_enumerator.MoveNext();
return true;
}
return true;
}
#endregion
}
#endregion
}
#endregion
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Dataload
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Datastream;
using NUnit.Framework;
/// <summary>
/// Data streamer tests.
/// </summary>
public sealed class DataStreamerTest
{
/** Cache name. */
private const string CacheName = "partitioned";
/** Node. */
private IIgnite _grid;
/** Node 2. */
private IIgnite _grid2;
/** Cache. */
private ICache<int, int?> _cache;
/// <summary>
/// Initialization routine.
/// </summary>
[TestFixtureSetUp]
public void InitClient()
{
_grid = Ignition.Start(TestUtils.GetTestConfiguration());
_grid2 = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = "grid1"
});
_cache = _grid.CreateCache<int, int?>(CacheName);
}
/// <summary>
/// Fixture teardown.
/// </summary>
[TestFixtureTearDown]
public void StopGrids()
{
Ignition.StopAll(true);
}
/// <summary>
///
/// </summary>
[SetUp]
public void BeforeTest()
{
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
for (int i = 0; i < 100; i++)
_cache.Remove(i);
}
[TearDown]
public void AfterTest()
{
TestUtils.AssertHandleRegistryIsEmpty(1000, _grid);
}
/// <summary>
/// Test data streamer property configuration. Ensures that at least no exceptions are thrown.
/// </summary>
[Test]
public void TestPropertyPropagation()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
Assert.AreEqual(CacheName, ldr.CacheName);
Assert.AreEqual(TimeSpan.Zero, ldr.AutoFlushInterval);
ldr.AutoFlushInterval = TimeSpan.FromMinutes(5);
Assert.AreEqual(5, ldr.AutoFlushInterval.TotalMinutes);
#pragma warning disable 618 // Type or member is obsolete
Assert.AreEqual(5 * 60 * 1000, ldr.AutoFlushFrequency);
ldr.AutoFlushFrequency = 9000;
Assert.AreEqual(9000, ldr.AutoFlushFrequency);
Assert.AreEqual(9, ldr.AutoFlushInterval.TotalSeconds);
#pragma warning restore 618 // Type or member is obsolete
Assert.IsFalse(ldr.AllowOverwrite);
ldr.AllowOverwrite = true;
Assert.IsTrue(ldr.AllowOverwrite);
ldr.AllowOverwrite = false;
Assert.IsFalse(ldr.AllowOverwrite);
Assert.IsFalse(ldr.SkipStore);
ldr.SkipStore = true;
Assert.IsTrue(ldr.SkipStore);
ldr.SkipStore = false;
Assert.IsFalse(ldr.SkipStore);
Assert.AreEqual(DataStreamerDefaults.DefaultPerNodeBufferSize, ldr.PerNodeBufferSize);
ldr.PerNodeBufferSize = 1;
Assert.AreEqual(1, ldr.PerNodeBufferSize);
ldr.PerNodeBufferSize = 2;
Assert.AreEqual(2, ldr.PerNodeBufferSize);
Assert.AreEqual(DataStreamerDefaults.DefaultPerThreadBufferSize, ldr.PerThreadBufferSize);
ldr.PerThreadBufferSize = 1;
Assert.AreEqual(1, ldr.PerThreadBufferSize);
ldr.PerThreadBufferSize = 2;
Assert.AreEqual(2, ldr.PerThreadBufferSize);
Assert.AreEqual(0, ldr.PerNodeParallelOperations);
var ops = DataStreamerDefaults.DefaultParallelOperationsMultiplier *
IgniteConfiguration.DefaultThreadPoolSize;
ldr.PerNodeParallelOperations = ops;
Assert.AreEqual(ops, ldr.PerNodeParallelOperations);
ldr.PerNodeParallelOperations = 2;
Assert.AreEqual(2, ldr.PerNodeParallelOperations);
Assert.AreEqual(DataStreamerDefaults.DefaultTimeout, ldr.Timeout);
ldr.Timeout = TimeSpan.MaxValue;
Assert.AreEqual(TimeSpan.MaxValue, ldr.Timeout);
ldr.Timeout = TimeSpan.FromSeconds(1.5);
Assert.AreEqual(1.5, ldr.Timeout.TotalSeconds);
}
}
/// <summary>
/// Tests removal without <see cref="IDataStreamer{TK,TV}.AllowOverwrite"/>.
/// </summary>
[Test]
public void TestRemoveNoOverwrite()
{
_cache.Put(1, 1);
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.Remove(1);
}
Assert.IsTrue(_cache.ContainsKey(1));
}
/// <summary>
/// Test data add/remove.
/// </summary>
[Test]
public void TestAddRemove()
{
IDataStreamer<int, int> ldr;
using (ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
Assert.IsFalse(ldr.Task.IsCompleted);
ldr.AllowOverwrite = true;
// Additions.
var task = ldr.GetCurrentBatchTask();
ldr.Add(1, 1);
ldr.Flush();
Assert.AreEqual(1, _cache.Get(1));
Assert.IsTrue(task.IsCompleted);
Assert.IsFalse(ldr.Task.IsCompleted);
task = ldr.GetCurrentBatchTask();
ldr.Add(new KeyValuePair<int, int>(2, 2));
ldr.Flush();
Assert.AreEqual(2, _cache.Get(2));
Assert.IsTrue(task.IsCompleted);
task = ldr.GetCurrentBatchTask();
ldr.Add(new [] { new KeyValuePair<int, int>(3, 3), new KeyValuePair<int, int>(4, 4) });
ldr.Flush();
Assert.AreEqual(3, _cache.Get(3));
Assert.AreEqual(4, _cache.Get(4));
Assert.IsTrue(task.IsCompleted);
// Removal.
task = ldr.GetCurrentBatchTask();
ldr.Remove(1);
ldr.Flush();
Assert.IsFalse(_cache.ContainsKey(1));
Assert.IsTrue(task.IsCompleted);
// Mixed.
ldr.Add(5, 5);
ldr.Remove(2);
ldr.Add(new KeyValuePair<int, int>(7, 7));
ldr.Add(6, 6);
ldr.Remove(4);
ldr.Add(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(9, 9), new KeyValuePair<int, int>(10, 10) });
ldr.Add(new KeyValuePair<int, int>(8, 8));
ldr.Remove(3);
ldr.Add(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(11, 11), new KeyValuePair<int, int>(12, 12) });
ldr.Flush();
for (int i = 2; i < 5; i++)
Assert.IsFalse(_cache.ContainsKey(i));
for (int i = 5; i < 13; i++)
Assert.AreEqual(i, _cache.Get(i));
}
Assert.IsTrue(ldr.Task.Wait(5000));
}
/// <summary>
/// Test data add/remove.
/// </summary>
[Test]
public void TestAddRemoveObsolete()
{
#pragma warning disable 618 // Type or member is obsolete
IDataStreamer<int, int> ldr;
using (ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
Assert.IsFalse(ldr.Task.IsCompleted);
ldr.AllowOverwrite = true;
// Additions.
var task = ldr.AddData(1, 1);
ldr.Flush();
Assert.AreEqual(1, _cache.Get(1));
Assert.IsTrue(task.IsCompleted);
Assert.IsFalse(ldr.Task.IsCompleted);
task = ldr.AddData(new KeyValuePair<int, int>(2, 2));
ldr.Flush();
Assert.AreEqual(2, _cache.Get(2));
Assert.IsTrue(task.IsCompleted);
task = ldr.AddData(new [] { new KeyValuePair<int, int>(3, 3), new KeyValuePair<int, int>(4, 4) });
ldr.Flush();
Assert.AreEqual(3, _cache.Get(3));
Assert.AreEqual(4, _cache.Get(4));
Assert.IsTrue(task.IsCompleted);
// Removal.
task = ldr.RemoveData(1);
ldr.Flush();
Assert.IsFalse(_cache.ContainsKey(1));
Assert.IsTrue(task.IsCompleted);
// Mixed.
ldr.AddData(5, 5);
ldr.RemoveData(2);
ldr.AddData(new KeyValuePair<int, int>(7, 7));
ldr.AddData(6, 6);
ldr.RemoveData(4);
ldr.AddData(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(9, 9), new KeyValuePair<int, int>(10, 10) });
ldr.AddData(new KeyValuePair<int, int>(8, 8));
ldr.RemoveData(3);
ldr.AddData(new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(11, 11), new KeyValuePair<int, int>(12, 12) });
ldr.Flush();
for (int i = 2; i < 5; i++)
Assert.IsFalse(_cache.ContainsKey(i));
for (int i = 5; i < 13; i++)
Assert.AreEqual(i, _cache.Get(i));
}
Assert.IsTrue(ldr.Task.Wait(5000));
#pragma warning restore 618 // Type or member is obsolete
}
/// <summary>
/// Tests object graphs with loops.
/// </summary>
[Test]
public void TestObjectGraphs()
{
var obj1 = new Container();
var obj2 = new Container();
var obj3 = new Container();
var obj4 = new Container();
obj1.Inner = obj2;
obj2.Inner = obj1;
obj3.Inner = obj1;
obj4.Inner = new Container();
using (var ldr = _grid.GetDataStreamer<int, Container>(CacheName))
{
ldr.AllowOverwrite = true;
ldr.Add(1, obj1);
ldr.Add(2, obj2);
ldr.Add(3, obj3);
ldr.Add(4, obj4);
}
var cache = _grid.GetCache<int, Container>(CacheName);
var res = cache[1];
Assert.AreEqual(res, res.Inner.Inner);
Assert.IsNotNull(cache[2].Inner);
Assert.IsNotNull(cache[2].Inner.Inner);
Assert.IsNotNull(cache[3].Inner);
Assert.IsNotNull(cache[3].Inner.Inner);
Assert.IsNotNull(cache[4].Inner);
Assert.IsNull(cache[4].Inner.Inner);
}
/// <summary>
/// Test "tryFlush".
/// </summary>
[Test]
public void TestTryFlushObsolete()
{
#pragma warning disable 618 // Type or member is obsolete
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
var fut = ldr.AddData(1, 1);
ldr.TryFlush();
fut.Wait();
Assert.AreEqual(1, _cache.Get(1));
}
#pragma warning restore 618 // Type or member is obsolete
}
/// <summary>
/// Test FlushAsync.
/// </summary>
[Test]
public void TestFlushAsync()
{
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.Add(1, 1);
ldr.FlushAsync().Wait();
Assert.AreEqual(1, _cache.Get(1));
}
}
/// <summary>
/// Test buffer size adjustments.
/// </summary>
[Test]
public void TestBufferSize()
{
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
const int timeout = 5000;
var part1 = GetPrimaryPartitionKeys(_grid, 4);
var part2 = GetPrimaryPartitionKeys(_grid2, 4);
ldr.Add(part1[0], part1[0]);
var task = ldr.GetCurrentBatchTask();
Thread.Sleep(100);
Assert.IsFalse(task.IsCompleted);
ldr.PerNodeBufferSize = 2;
ldr.PerThreadBufferSize = 1;
ldr.Add(part2[0], part2[0]);
ldr.Add(part1[1], part1[1]);
ldr.Add(part2[1], part2[1]);
Assert.IsTrue(task.Wait(timeout));
Assert.AreEqual(part1[0], _cache.Get(part1[0]));
Assert.AreEqual(part1[1], _cache.Get(part1[1]));
Assert.AreEqual(part2[0], _cache.Get(part2[0]));
Assert.AreEqual(part2[1], _cache.Get(part2[1]));
var task2 = ldr.GetCurrentBatchTask();
ldr.Add(new[]
{
new KeyValuePair<int, int>(part1[2], part1[2]),
new KeyValuePair<int, int>(part1[3], part1[3]),
new KeyValuePair<int, int>(part2[2], part2[2]),
new KeyValuePair<int, int>(part2[3], part2[3])
});
Assert.IsTrue(task2.Wait(timeout));
Assert.AreEqual(part1[2], _cache.Get(part1[2]));
Assert.AreEqual(part1[3], _cache.Get(part1[3]));
Assert.AreEqual(part2[2], _cache.Get(part2[2]));
Assert.AreEqual(part2[3], _cache.Get(part2[3]));
}
}
/// <summary>
/// Gets the primary partition keys.
/// </summary>
private static int[] GetPrimaryPartitionKeys(IIgnite ignite, int count)
{
var affinity = ignite.GetAffinity(CacheName);
var localNode = ignite.GetCluster().GetLocalNode();
var part = affinity.GetPrimaryPartitions(localNode).First();
return Enumerable.Range(0, int.MaxValue)
.Where(k => affinity.GetPartition(k) == part)
.Take(count)
.ToArray();
}
/// <summary>
/// Test close.
/// </summary>
[Test]
public void TestClose()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
var fut = ldr.GetCurrentBatchTask();
ldr.Add(1, 1);
ldr.Close(false);
Assert.IsTrue(fut.Wait(5000));
Assert.AreEqual(1, _cache.Get(1));
}
}
/// <summary>
/// Test close with cancellation.
/// </summary>
[Test]
public void TestCancel()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
var fut = ldr.GetCurrentBatchTask();
ldr.Add(1, 1);
ldr.Close(true);
Assert.IsTrue(fut.Wait(5000));
Assert.IsFalse(_cache.ContainsKey(1));
}
}
/// <summary>
/// Tests that streamer gets collected when there are no references to it.
/// </summary>
[Test]
public void TestFinalizer()
{
// Create streamer reference in a different thread to defeat Debug mode quirks.
var streamerRef = Task.Factory.StartNew
(() => new WeakReference(_grid.GetDataStreamer<int, int>(CacheName))).Result;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.IsNull(streamerRef.Target);
}
/// <summary>
/// Test auto-flush feature.
/// </summary>
[Test]
public void TestAutoFlushObsolete()
{
#pragma warning disable 618 // Type or member is obsolete
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
// Test auto flush turning on.
var fut = ldr.AddData(1, 1);
Thread.Sleep(100);
Assert.IsFalse(fut.IsCompleted);
ldr.AutoFlushFrequency = 1000;
fut.Wait();
// Test forced flush after frequency change.
fut = ldr.AddData(2, 2);
ldr.AutoFlushFrequency = long.MaxValue;
fut.Wait();
// Test another forced flush after frequency change.
fut = ldr.AddData(3, 3);
ldr.AutoFlushFrequency = 1000;
fut.Wait();
// Test flush before stop.
fut = ldr.AddData(4, 4);
ldr.AutoFlushFrequency = 0;
fut.Wait();
// Test flush after second turn on.
fut = ldr.AddData(5, 5);
ldr.AutoFlushFrequency = 1000;
fut.Wait();
Assert.AreEqual(1, _cache.Get(1));
Assert.AreEqual(2, _cache.Get(2));
Assert.AreEqual(3, _cache.Get(3));
Assert.AreEqual(4, _cache.Get(4));
Assert.AreEqual(5, _cache.Get(5));
}
#pragma warning restore 618 // Type or member is obsolete
}
/// <summary>
/// Test auto-flush feature.
/// </summary>
[Test]
public void TestAutoFlush()
{
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
// Test auto flush turning on.
var fut = ldr.GetCurrentBatchTask();
ldr.Add(1, 1);
Thread.Sleep(100);
Assert.IsFalse(fut.IsCompleted);
ldr.AutoFlushInterval = TimeSpan.FromSeconds(1);
fut.Wait();
// Test forced flush after frequency change.
fut = ldr.GetCurrentBatchTask();
ldr.Add(2, 2);
ldr.AutoFlushInterval = TimeSpan.MaxValue;
fut.Wait();
// Test another forced flush after frequency change.
fut = ldr.GetCurrentBatchTask();
ldr.Add(3, 3);
ldr.AutoFlushInterval = TimeSpan.FromSeconds(1);
fut.Wait();
// Test flush before stop.
fut = ldr.GetCurrentBatchTask();
ldr.Add(4, 4);
ldr.AutoFlushInterval = TimeSpan.Zero;
fut.Wait();
// Test flush after second turn on.
fut = ldr.GetCurrentBatchTask();
ldr.Add(5, 5);
ldr.AutoFlushInterval = TimeSpan.FromSeconds(1);
fut.Wait();
Assert.AreEqual(1, _cache.Get(1));
Assert.AreEqual(2, _cache.Get(2));
Assert.AreEqual(3, _cache.Get(3));
Assert.AreEqual(4, _cache.Get(4));
Assert.AreEqual(5, _cache.Get(5));
}
}
/// <summary>
/// Test multithreaded behavior.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestMultithreaded()
{
int entriesPerThread = 100000;
int threadCnt = 8;
for (int i = 0; i < 5; i++)
{
_cache.Clear();
Assert.AreEqual(0, _cache.GetSize());
Stopwatch watch = new Stopwatch();
watch.Start();
using (IDataStreamer<int, int> ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.PerNodeBufferSize = 1024;
int ctr = 0;
TestUtils.RunMultiThreaded(() =>
{
int threadIdx = Interlocked.Increment(ref ctr);
int startIdx = (threadIdx - 1) * entriesPerThread;
int endIdx = startIdx + entriesPerThread;
for (int j = startIdx; j < endIdx; j++)
{
// ReSharper disable once AccessToDisposedClosure
ldr.Add(j, j);
if (j % 100000 == 0)
Console.WriteLine("Put [thread=" + threadIdx + ", cnt=" + j + ']');
}
}, threadCnt);
}
Console.WriteLine("Iteration " + i + ": " + watch.ElapsedMilliseconds);
watch.Reset();
for (int j = 0; j < threadCnt * entriesPerThread; j++)
Assert.AreEqual(j, j);
}
}
/// <summary>
/// Tests custom receiver.
/// </summary>
[Test]
public void TestStreamReceiver()
{
TestStreamReceiver(new StreamReceiverBinarizable());
TestStreamReceiver(new StreamReceiverSerializable());
}
/// <summary>
/// Tests StreamVisitor.
/// </summary>
[Test]
public void TestStreamVisitor()
{
#if !NETCOREAPP // Serializing delegates is not supported on this platform.
TestStreamReceiver(new StreamVisitor<int, int>((c, e) => c.Put(e.Key, e.Value + 1)));
#endif
}
/// <summary>
/// Tests StreamTransformer.
/// </summary>
[Test]
public void TestStreamTransformer()
{
TestStreamReceiver(new StreamTransformer<int, int, int, int>(new EntryProcessorSerializable()));
TestStreamReceiver(new StreamTransformer<int, int, int, int>(new EntryProcessorBinarizable()));
}
[Test]
public void TestStreamTransformerIsInvokedForDuplicateKeys()
{
var cache = _grid.GetOrCreateCache<string, long>("c");
using (var streamer = _grid.GetDataStreamer<string, long>(cache.Name))
{
streamer.AllowOverwrite = true;
streamer.Receiver = new StreamTransformer<string, long, object, object>(new CountingEntryProcessor());
var words = Enumerable.Repeat("a", 3).Concat(Enumerable.Repeat("b", 2));
foreach (var word in words)
{
streamer.Add(word, 1L);
}
}
Assert.AreEqual(3, cache.Get("a"));
Assert.AreEqual(2, cache.Get("b"));
}
/// <summary>
/// Tests specified receiver.
/// </summary>
private void TestStreamReceiver(IStreamReceiver<int, int> receiver)
{
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.AllowOverwrite = true;
ldr.Receiver = new StreamReceiverBinarizable();
ldr.Receiver = receiver; // check double assignment
Assert.AreEqual(ldr.Receiver, receiver);
for (var i = 0; i < 100; i++)
ldr.Add(i, i);
ldr.Flush();
for (var i = 0; i < 100; i++)
Assert.AreEqual(i + 1, _cache.Get(i));
}
}
/// <summary>
/// Tests the stream receiver in keepBinary mode.
/// </summary>
[Test]
public void TestStreamReceiverKeepBinary()
{
// ReSharper disable once LocalVariableHidesMember
var cache = _grid.GetCache<int, BinarizableEntry>(CacheName);
using (var ldr0 = _grid.GetDataStreamer<int, int>(CacheName))
using (var ldr = ldr0.WithKeepBinary<int, IBinaryObject>())
{
ldr.Receiver = new StreamReceiverKeepBinary();
ldr.AllowOverwrite = true;
for (var i = 0; i < 100; i++)
ldr.Add(i, _grid.GetBinary().ToBinary<IBinaryObject>(new BinarizableEntry {Val = i}));
ldr.Flush();
for (var i = 0; i < 100; i++)
Assert.AreEqual(i + 1, cache.Get(i).Val);
// Repeating WithKeepBinary call: valid args.
Assert.AreSame(ldr, ldr.WithKeepBinary<int, IBinaryObject>());
// Invalid type args.
var ex = Assert.Throws<InvalidOperationException>(() => ldr.WithKeepBinary<string, IBinaryObject>());
Assert.AreEqual(
"Can't change type of binary streamer. WithKeepBinary has been called on an instance of " +
"binary streamer with incompatible generic arguments.", ex.Message);
}
}
/// <summary>
/// Streamer test with destroyed cache.
/// </summary>
[Test]
public void TestDestroyCache()
{
var cache = _grid.CreateCache<int, int>(TestUtils.TestName);
var streamer = _grid.GetDataStreamer<int, int>(cache.Name);
streamer.Add(1, 2);
streamer.FlushAsync().Wait();
_grid.DestroyCache(cache.Name);
streamer.Add(2, 3);
var ex = Assert.Throws<AggregateException>(() => streamer.Flush()).GetBaseException();
Assert.IsNotNull(ex);
Assert.AreEqual("class org.apache.ignite.IgniteCheckedException: DataStreamer data loading failed.",
ex.Message);
Assert.Throws<CacheException>(() => streamer.Close(true));
}
/// <summary>
/// Streamer test with destroyed cache.
/// </summary>
[Test]
public void TestDestroyCacheObsolete()
{
#pragma warning disable 618 // Type or member is obsolete
var cache = _grid.CreateCache<int, int>(TestUtils.TestName);
var streamer = _grid.GetDataStreamer<int, int>(cache.Name);
var task = streamer.AddData(1, 2);
streamer.Flush();
task.Wait();
_grid.DestroyCache(cache.Name);
streamer.AddData(2, 3);
var ex = Assert.Throws<AggregateException>(() => streamer.Flush()).GetBaseException();
Assert.IsNotNull(ex);
Assert.AreEqual("class org.apache.ignite.IgniteCheckedException: DataStreamer data loading failed.",
ex.Message);
Assert.Throws<CacheException>(() => streamer.Close(true));
#pragma warning restore 618 // Type or member is obsolete
}
/// <summary>
/// Tests that streaming binary objects with a thin client results in those objects being
/// available through SQL in the cache's table.
/// </summary>
[Test]
public void TestBinaryStreamerCreatesSqlRecord()
{
var cacheCfg = new CacheConfiguration
{
Name = "TestBinaryStreamerCreatesSqlRecord",
SqlSchema = "persons",
QueryEntities = new[]
{
new QueryEntity
{
ValueTypeName = "Person",
Fields = new List<QueryField>
{
new QueryField
{
Name = "Name",
FieldType = typeof(string),
},
new QueryField
{
Name = "Age",
FieldType = typeof(int)
}
}
}
}
};
var cacheClientBinary = _grid.GetOrCreateCache<int, IBinaryObject>(cacheCfg)
.WithKeepBinary<int, IBinaryObject>();
// Prepare a binary object.
var jane = _grid.GetBinary().GetBuilder("Person")
.SetStringField("Name", "Jane")
.SetIntField("Age", 43)
.Build();
const int key = 1;
// Stream the binary object to the server.
using (var streamer = _grid.GetDataStreamer<int, IBinaryObject>(cacheCfg.Name))
{
streamer.Add(key, jane);
streamer.Flush();
}
// Check that SQL works.
var query = new SqlFieldsQuery("SELECT Name, Age FROM \"PERSONS\".PERSON");
var fullResultAfterClientStreamer = cacheClientBinary.Query(query).GetAll();
Assert.IsNotNull(fullResultAfterClientStreamer);
Assert.AreEqual(1, fullResultAfterClientStreamer.Count);
Assert.AreEqual("Jane", fullResultAfterClientStreamer[0][0]);
Assert.AreEqual(43, fullResultAfterClientStreamer[0][1]);
}
#if NETCOREAPP
/// <summary>
/// Tests async streamer usage.
/// Using async cache and streamer operations within the streamer means that we end up on different threads.
/// Streamer is thread-safe and is expected to handle this well.
/// </summary>
[Test]
public async Task TestStreamerAsyncAwait()
{
using (var ldr = _grid.GetDataStreamer<int, int>(CacheName))
{
ldr.AllowOverwrite = true;
ldr.Add(Enumerable.Range(1, 500).ToDictionary(x => x, x => -x));
Assert.IsFalse(await _cache.ContainsKeysAsync(new[] {1, 2}));
var flushTask = ldr.FlushAsync();
Assert.IsFalse(flushTask.IsCompleted);
await flushTask;
Assert.AreEqual(-1, await _cache.GetAsync(1));
Assert.AreEqual(-2, await _cache.GetAsync(2));
// Remove.
var batchTask = ldr.GetCurrentBatchTask();
Assert.IsFalse(batchTask.IsCompleted);
Assert.IsFalse(batchTask.IsFaulted);
ldr.Remove(1);
var flushTask2 = ldr.FlushAsync();
Assert.AreSame(batchTask, flushTask2);
await flushTask2;
Assert.IsTrue(batchTask.IsCompleted);
Assert.IsFalse(await _cache.ContainsKeyAsync(1));
// Empty buffer flush is allowed.
await ldr.FlushAsync();
await ldr.FlushAsync();
}
}
#endif
/// <summary>
/// Test binarizable receiver.
/// </summary>
private class StreamReceiverBinarizable : IStreamReceiver<int, int>
{
/** <inheritdoc /> */
public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries)
{
cache.PutAll(entries.ToDictionary(x => x.Key, x => x.Value + 1));
}
}
/// <summary>
/// Test binary receiver.
/// </summary>
[Serializable]
private class StreamReceiverKeepBinary : IStreamReceiver<int, IBinaryObject>
{
/** <inheritdoc /> */
public void Receive(ICache<int, IBinaryObject> cache, ICollection<ICacheEntry<int, IBinaryObject>> entries)
{
var binary = cache.Ignite.GetBinary();
cache.PutAll(entries.ToDictionary(x => x.Key, x =>
binary.ToBinary<IBinaryObject>(new BinarizableEntry
{
Val = x.Value.Deserialize<BinarizableEntry>().Val + 1
})));
}
}
/// <summary>
/// Test serializable receiver.
/// </summary>
[Serializable]
private class StreamReceiverSerializable : IStreamReceiver<int, int>
{
/** <inheritdoc /> */
public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries)
{
cache.PutAll(entries.ToDictionary(x => x.Key, x => x.Value + 1));
}
}
/// <summary>
/// Test entry processor.
/// </summary>
[Serializable]
private class EntryProcessorSerializable : ICacheEntryProcessor<int, int, int, int>
{
/** <inheritdoc /> */
public int Process(IMutableCacheEntry<int, int> entry, int arg)
{
entry.Value = entry.Key + 1;
return 0;
}
}
/// <summary>
/// Test entry processor.
/// </summary>
private class EntryProcessorBinarizable : ICacheEntryProcessor<int, int, int, int>, IBinarizable
{
/** <inheritdoc /> */
public int Process(IMutableCacheEntry<int, int> entry, int arg)
{
entry.Value = entry.Key + 1;
return 0;
}
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
// No-op.
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
// No-op.
}
}
/// <summary>
/// Binarizable entry.
/// </summary>
private class BinarizableEntry
{
public int Val { get; set; }
}
/// <summary>
/// Container class.
/// </summary>
private class Container
{
public Container Inner;
}
private class CountingEntryProcessor : ICacheEntryProcessor<string, long, object, object>
{
public object Process(IMutableCacheEntry<string, long> e, object arg)
{
e.Value++;
return null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml;
using Bloom.ToPalaso;
using L10NSharp;
using SIL.Reporting;
using SIL.Xml;
namespace Bloom.Book
{
/// <summary>
/// Most editable elements in Bloom are multilingual. They have a wrapping <div> and then inner divs which are visible or not,
/// depending on various settings. This class manages creating those inner divs, and marking them with classes that turn on
/// visibility or move the element around the page, depending on the stylesheet in use.
///
/// Also, page <div/>s are marked with one of these classes: bloom-monolingual, bloom-bilingual, and bloom-trilingual
///
/// <div class="bloom-translationGroup" data-default-langauges='V, N1'>
/// <div class="bloom-editable" contenteditable="true" lang="en">The Mother said...</div>
/// <div class="bloom-editable" contenteditable="true" lang="tpi">Mama i tok:</div>
/// <div class="bloom-editable contenteditable="true" lang="xyz">abada fakwan</div>
/// </div>
/// </summary>
public static class TranslationGroupManager
{
/// <summary>
/// For each group of editable elements in the div which have lang attributes (normally, a .bloom-translationGroup div),
/// make a new element with the lang code of the vernacular (normally, a .bloom-editable).
/// Also enable/disable editing as warranted (e.g. in shell mode or not)
/// </summary>
public static void PrepareElementsInPageOrDocument(XmlNode pageOrDocumentNode, BookData bookData)
{
GenerateEditableDivsWithPreTranslatedContent(pageOrDocumentNode);
foreach (var code in bookData.GetBasicBookLanguageCodes())
PrepareElementsOnPageOneLanguage(pageOrDocumentNode, code);
FixGroupStyleSettings(pageOrDocumentNode);
}
/// <summary>
/// Normally, the connection between bloom-translationGroups and the dataDiv is that each bloom-editable child
/// (which has an @lang) pulls the corresponding string from the dataDiv. This happens in BookData.
///
/// That works except in the case of xmatter which a) start empty and b) only normally get filled with
/// .bloom-editable's for the current languages. Then, when bloom would normally show a source bubble listing
/// the string in other languages, well there's nothing to show (the bubble can't pull from dataDiv).
/// So our solution here is to pre-pack the translationGroup with bloom-editable's for each of the languages
/// in the data-div.
/// The original (an possibly only) instance of this is with book titles. See bl-1210.
/// </summary>
public static void PrepareDataBookTranslationGroups(XmlNode pageOrDocumentNode, IEnumerable<string> languageCodes)
{
//At first, I set out to select all translationGroups that have child .bloomEditables that have data-book attributes
//however this has implications on other fields, noticeably the acknowledgments. So in order to get this fixed
//and not open another can of worms, I've reduce the scope of this
//fix to just the bookTitle, so I'm going with findOnlyBookTitleFields for now
//var findAllDataBookFields = "descendant-or-self::*[contains(@class,'bloom-translationGroup') and descendant::div[@data-book and contains(@class,'bloom-editable')]]";
var findOnlyBookTitleFields = "descendant-or-self::*[contains(@class,'bloom-translationGroup') and descendant::div[@data-book='bookTitle' and contains(@class,'bloom-editable')]]";
foreach (XmlElement groupElement in
pageOrDocumentNode.SafeSelectNodes(findOnlyBookTitleFields))
{
foreach (var lang in languageCodes)
{
MakeElementWithLanguageForOneGroup(groupElement, lang);
}
}
}
/// <summary>
/// Returns the sequence of bloom-editable divs that would normally be created as the content of an empty bloom-translationGroup,
/// given the current collection and book settings, with the classes that would normally be set on them prior to editing to make the right ones visible etc.
/// </summary>
public static string GetDefaultTranslationGroupContent(XmlNode pageOrDocumentNode, Book currentBook)
{
// First get a XMLDocument so that we can start creating elements using it.
XmlDocument ownerDocument = pageOrDocumentNode?.OwnerDocument;
if (ownerDocument == null) // the OwnerDocument child can be null if pageOrDocumentNode is a document itself
{
if (pageOrDocumentNode is XmlDocument)
{
ownerDocument = pageOrDocumentNode as XmlDocument;
}
else
{
return "";
}
}
// We want to use the usual routines that insert the required bloom-editables and classes into existing translation groups.
// To make this work we make a temporary translation group
// Since one of the routines expects the TG to be a descendant of the element passed to it, we make another layer of temporary wrapper around the translation group as well
var containerElement = ownerDocument.CreateElement("div");
containerElement.SetAttribute("class", "bloom-translationGroup");
var wrapper = ownerDocument.CreateElement("div");
wrapper.AppendChild(containerElement);
PrepareElementsInPageOrDocument(containerElement, currentBook.BookData);
TranslationGroupManager.UpdateContentLanguageClasses(wrapper, currentBook.BookData, currentBook.Language1IsoCode,
currentBook.Language2IsoCode, currentBook.Language3IsoCode);
return containerElement.InnerXml;
}
private static void GenerateEditableDivsWithPreTranslatedContent(XmlNode elementOrDom)
{
foreach (XmlElement editableDiv in elementOrDom.SafeSelectNodes(".//*[contains(@class,'bloom-editable') and @data-generate-translations and @data-i18n]"))
{
var englishText = editableDiv.InnerText;
var l10nId = editableDiv.Attributes["data-i18n"].Value;
if (String.IsNullOrWhiteSpace(l10nId))
continue;
foreach (var uiLanguage in LocalizationManager.GetAvailableLocalizedLanguages())
{
var translation = LocalizationManager.GetDynamicStringOrEnglish("Bloom", l10nId, englishText, null, uiLanguage);
if (translation == englishText)
continue;
var newEditableDiv = elementOrDom.OwnerDocument.CreateElement("div");
newEditableDiv.SetAttribute("class", "bloom-editable");
newEditableDiv.SetAttribute("lang", LanguageLookupModelExtensions.GetGeneralCode(uiLanguage));
newEditableDiv.InnerText = translation;
editableDiv.ParentNode.AppendChild(newEditableDiv);
}
editableDiv.RemoveAttribute("data-generate-translations");
editableDiv.RemoveAttribute("data-i18n");
}
}
/// <summary>
/// This is used when a book is first created from a source; without it, if the shell maker left the book as trilingual when working on it,
/// then every time someone created a new book based on it, it too would be trilingual.
/// </summary>
/// <remarks>
/// This method explicitly used the CollectionSettings languages in creating a new book.
/// </remarks>
public static void SetInitialMultilingualSetting(BookData bookData, int oneTwoOrThreeContentLanguages)
{
//var multilingualClass = new string[]{"bloom-monolingual", "bloom-bilingual","bloom-trilingual"}[oneTwoOrThreeContentLanguages-1];
if (oneTwoOrThreeContentLanguages < 3)
bookData.RemoveAllForms("contentLanguage3");
if (oneTwoOrThreeContentLanguages < 2)
bookData.RemoveAllForms("contentLanguage2");
var language1 = bookData.CollectionSettings.Language1;
bookData.Set("contentLanguage1", XmlString.FromUnencoded(language1.Iso639Code), false);
bookData.Set("contentLanguage1Rtl", XmlString.FromUnencoded(language1.IsRightToLeft.ToString()), false);
if (oneTwoOrThreeContentLanguages > 1)
{
var language2 = bookData.CollectionSettings.Language2;
bookData.Set("contentLanguage2", XmlString.FromUnencoded(language2.Iso639Code), false);
bookData.Set("contentLanguage2Rtl", XmlString.FromUnencoded(language2.IsRightToLeft.ToString()), false);
}
var language3 = bookData.CollectionSettings.Language3;
if (oneTwoOrThreeContentLanguages > 2 && !String.IsNullOrEmpty(language3.Iso639Code))
{
bookData.Set("contentLanguage3", XmlString.FromUnencoded(language3.Iso639Code), false);
bookData.Set("contentLanguage3Rtl", XmlString.FromUnencoded(language3.IsRightToLeft.ToString()), false);
}
}
/// <summary>
/// We stick various classes on editable things to control order and visibility
/// </summary>
public static void UpdateContentLanguageClasses(XmlNode elementOrDom, BookData bookData,
string language1IsoCode, string language2IsoCode, string language3IsoCode)
{
var multilingualClass = "bloom-monolingual";
var contentLanguages = new Dictionary<string, string>();
contentLanguages.Add(language1IsoCode, "bloom-content1");
if (!String.IsNullOrEmpty(language2IsoCode) && language1IsoCode != language2IsoCode)
{
multilingualClass = "bloom-bilingual";
contentLanguages.Add(language2IsoCode, "bloom-content2");
}
if (!String.IsNullOrEmpty(language3IsoCode) && language1IsoCode != language3IsoCode &&
language2IsoCode != language3IsoCode)
{
multilingualClass = "bloom-trilingual";
contentLanguages.Add(language3IsoCode, "bloom-content3");
Debug.Assert(!String.IsNullOrEmpty(language2IsoCode), "shouldn't have a content3 lang with no content2 lang");
}
//Stick a class in the page div telling the stylesheet how many languages we are displaying (only makes sense for content pages, in Jan 2012).
foreach (
XmlElement pageDiv in
elementOrDom.SafeSelectNodes(
"descendant-or-self::div[contains(@class,'bloom-page') and not(contains(@class,'bloom-frontMatter')) and not(contains(@class,'bloom-backMatter'))]")
)
{
HtmlDom.RemoveClassesBeginingWith(pageDiv, "bloom-monolingual");
HtmlDom.RemoveClassesBeginingWith(pageDiv, "bloom-bilingual");
HtmlDom.RemoveClassesBeginingWith(pageDiv, "bloom-trilingual");
HtmlDom.AddClassIfMissing(pageDiv, multilingualClass);
}
// This is the "code" part of the visibility system: https://goo.gl/EgnSJo
foreach (XmlElement group in GetTranslationGroups(elementOrDom))
{
var dataDefaultLanguages = HtmlDom.GetAttributeValue(@group, "data-default-languages").Split(new char[] { ',', ' ' },
StringSplitOptions.RemoveEmptyEntries);
//nb: we don't necessarily care that a div is editable or not
foreach (XmlElement e in @group.SafeSelectNodes(".//textarea | .//div"))
{
UpdateContentLanguageClassesOnElement(e, contentLanguages, bookData, language2IsoCode, language3IsoCode, dataDefaultLanguages);
}
}
// Also correct bloom-contentX fields in the bloomDataDiv, which are not listed under translation groups
foreach (XmlElement coverImageDescription in elementOrDom.SafeSelectNodes(".//*[@id='bloomDataDiv']/*[@data-book='coverImageDescription']"))
{
string[] dataDefaultLanguages = new string[] { " auto" }; // bloomDataDiv contents don't have dataDefaultLanguages on them, so just go with "auto"
//nb: we don't necessarily care that a div is editable or not
foreach (XmlElement e in coverImageDescription.SafeSelectNodes(".//textarea | .//div"))
{
UpdateContentLanguageClassesOnElement(e, contentLanguages, bookData, language2IsoCode, language3IsoCode, dataDefaultLanguages);
}
}
}
public static XmlElement[] GetTranslationGroups(XmlNode elementOrDom, bool omitBoxHeaders = true)
{
var groups = elementOrDom
.SafeSelectNodes(".//div[contains(@class, 'bloom-translationGroup')]")
.Cast<XmlElement>();
if (omitBoxHeaders)
{
groups = groups.Where(g => !g.Attributes["class"].Value.Contains("box-header-off"));
}
return groups.ToArray();
}
private static void UpdateContentLanguageClassesOnElement(XmlElement e, Dictionary<string, string> contentLanguages, BookData bookData, string contentLanguageIso2, string contentLanguageIso3, string[] dataDefaultLanguages)
{
HtmlDom.RemoveClassesBeginingWith(e, "bloom-content");
var lang = e.GetAttribute("lang");
//These bloom-content* classes are used by some stylesheet rules, primarily to boost the font-size of some languages.
//Enhance: this is too complex; the semantics of these overlap with each other and with bloom-visibility-code-on, and with data-language-order.
//It would be better to have non-overlapping things; 1 for order, 1 for visibility, one for the lang's role in this collection.
string orderClass;
if (contentLanguages.TryGetValue(lang, out orderClass))
{
HtmlDom.AddClass(e, orderClass); //bloom-content1, bloom-content2, bloom-content3
}
//Enhance: it's even more likely that we can get rid of these by replacing them with bloom-content2, bloom-content3
if (lang == bookData.MetadataLanguage1IsoCode)
{
HtmlDom.AddClass(e, "bloom-contentNational1");
}
// It's not clear that this class should be applied to blocks where lang == bookData.Language3IsoCode.
// I (JohnT) added lang == bookData.MetadataLanguage2IsoCode while dealing with BL-10893
// but am reluctant to remove the old code as something might depend on it. I believe it is (nearly?)
// always true that if we have Language3IsoCode at all, it will be equal to MetadataLanguage2IsoCode,
// so at least for now it probably makes no difference. In our next major reworking of language codes,
// hopefully we can make this distinction clearer and remove Language3IsoCode here.
if (lang == bookData.Language3IsoCode || lang == bookData.MetadataLanguage2IsoCode)
{
HtmlDom.AddClass(e, "bloom-contentNational2");
}
HtmlDom.RemoveClassesBeginingWith(e, "bloom-visibility-code");
if (ShouldNormallyShowEditable(lang, dataDefaultLanguages, contentLanguageIso2, contentLanguageIso3, bookData))
{
HtmlDom.AddClass(e, "bloom-visibility-code-on");
}
UpdateRightToLeftSetting(bookData, e, lang);
}
private static void UpdateRightToLeftSetting(BookData bookData, XmlElement e, string lang)
{
HtmlDom.RemoveRtlDir(e);
if((lang == bookData.Language1IsoCode && bookData.Language1.IsRightToLeft) ||
(lang == bookData.Language2IsoCode && bookData.Language2.IsRightToLeft) ||
(lang == bookData.Language3IsoCode && bookData.Language3.IsRightToLeft) ||
(lang == bookData.MetadataLanguage1IsoCode && bookData.MetadataLanguage1.IsRightToLeft))
{
HtmlDom.AddRtlDir(e);
}
}
/// <summary>
/// Here, "normally" means unless the user overrides via a .bloom-visibility-user-on/off
/// </summary>
internal static bool ShouldNormallyShowEditable(string lang, string[] dataDefaultLanguages,
string contentLanguageIso2, string contentLanguageIso3, // these are effected by the multilingual settings for this book
BookData bookData) // use to get the collection's current N1 and N2 in xmatter or other template pages that specify default languages
{
// Note: There is code in bloom-player that is modeled after this code.
// If this function changes, you should check in bloom-player's bloom-player-core.tsx file, function shouldNormallyShowEditable().
// It may benefit from being updated too.
if (dataDefaultLanguages == null || dataDefaultLanguages.Length == 0
|| String.IsNullOrWhiteSpace(dataDefaultLanguages[0])
|| dataDefaultLanguages[0].Equals("auto",StringComparison.InvariantCultureIgnoreCase))
{
return lang == bookData.Language1.Iso639Code || lang == contentLanguageIso2 || lang == contentLanguageIso3;
}
else
{
// Note there are (perhaps unfortunately) two different labeling systems, but they have a more-or-less 1-to-1 correspondence:
// The V/N1/N2 system feels natural in vernacular book contexts
// The L1/L2/L3 system is more natural in source book contexts.
// But, the new model makes L2 and L3 mean the second and third checked languages, while N1 and N2 are the
// second and third metadata languages, currently locked to the collection L2 and L3.
// V and L1 both mean the first checked language.
// Changes here should result in consistent ones in Book.IsLanguageWanted and BookData.GatherDataItemsFromXElement
// and RuntimeInformationInjector.AddUIDictionaryToDom and I18ApiHandleI18nRequest
return (lang == bookData.Language1.Iso639Code && dataDefaultLanguages.Contains("V")) ||
(lang == bookData.Language1.Iso639Code && dataDefaultLanguages.Contains("L1")) ||
(lang == bookData.MetadataLanguage1IsoCode && dataDefaultLanguages.Contains("N1")) ||
(lang == bookData.Language2IsoCode && dataDefaultLanguages.Contains("L2")) ||
(lang == bookData.MetadataLanguage2IsoCode && dataDefaultLanguages.Contains("N2")) ||
(lang == bookData.Language3IsoCode && dataDefaultLanguages.Contains("L3")) ||
dataDefaultLanguages.Contains(lang); // a literal language id, e.g. "en" (used by template starter)
}
}
private static int GetOrderOfThisLanguageInTheTextBlock(string editableIso, string vernacularIso, string contentLanguageIso2, string contentLanguageIso3)
{
if (editableIso == vernacularIso)
return 1;
if (editableIso == contentLanguageIso2)
return 2;
if (editableIso == contentLanguageIso3)
return 3;
return -1;
}
private static void PrepareElementsOnPageOneLanguage(XmlNode pageDiv, string isoCode)
{
foreach (
XmlElement groupElement in
pageDiv.SafeSelectNodes("descendant-or-self::*[contains(@class,'bloom-translationGroup')]"))
{
MakeElementWithLanguageForOneGroup(groupElement, isoCode);
//remove any elements in the translationgroup which don't have a lang (but ignore any label elements, which we're using for annotating groups)
foreach (
XmlElement elementWithoutLanguage in
groupElement.SafeSelectNodes("textarea[not(@lang)] | div[not(@lang) and not(self::label)]"))
{
elementWithoutLanguage.ParentNode.RemoveChild(elementWithoutLanguage);
}
}
//any editable areas which still don't have a language, set them to the vernacular (this is used for simple templates (non-shell pages))
foreach (
XmlElement element in
pageDiv.SafeSelectNodes( //NB: the jscript will take items with bloom-editable and set the contentEdtable to true.
"descendant-or-self::textarea[not(@lang)] | descendant-or-self::*[(contains(@class, 'bloom-editable') or @contentEditable='true' or @contenteditable='true') and not(@lang)]")
)
{
element.SetAttribute("lang", isoCode);
}
foreach (XmlElement e in pageDiv.SafeSelectNodes("descendant-or-self::*[starts-with(text(),'{')]"))
{
foreach (var node in e.ChildNodes)
{
XmlText t = node as XmlText;
if (t != null && t.Value.StartsWith("{"))
t.Value = "";
//otherwise html tidy will throw away spans (at least) that are empty, so we never get a chance to fill in the values.
}
}
}
/// <summary>
/// If the group element contains more than one child div in the given language, remove or
/// merge the duplicates.
/// </summary>
/// <remarks>
/// We've had at least one user end up with duplicate vernacular divs in a shell book. (She
/// was using Bloom 4.3 to translate a shell book created with Bloom 3.7.) I haven't been
/// able to reproduce the effect or isolate the cause, but this fixes things.
/// See https://issues.bloomlibrary.org/youtrack/issue/BL-6923.
/// </remarks>
internal static void FixDuplicateLanguageDivs(XmlElement groupElement, string isoCode)
{
XmlNodeList list = groupElement.SafeSelectNodes("./div[@lang='" + isoCode + "']");
if (list.Count > 1)
{
var count = list.Count;
foreach (XmlNode div in list)
{
var innerText = div.InnerText.Trim();
if (String.IsNullOrEmpty(innerText))
{
Logger.WriteEvent($"An empty duplicate div for {isoCode} has been removed from a translation group.");
groupElement.RemoveChild(div);
--count;
if (count == 1)
break;
}
}
if (count > 1)
{
Logger.WriteEvent($"Duplicate divs for {isoCode} have been merged in a translation group.");
list = groupElement.SafeSelectNodes("./div[@lang='" + isoCode + "']");
XmlNode first = list[0];
for (int i = 1; i < list.Count; ++i)
{
var newline = groupElement.OwnerDocument.CreateTextNode(Environment.NewLine);
first.AppendChild(newline);
foreach (XmlNode node in list[i].ChildNodes)
first.AppendChild(node);
groupElement.RemoveChild(list[i]);
}
}
}
}
/// <summary>
/// Shift any translationGroup level style setting to child editable divs that lack a style.
/// This is motivated by the fact HTML/CSS underlining cannot be turned off in child nodes.
/// So if underlining is enabled for Normal, everything everywhere would be underlined
/// regardless of style or immediate character formatting. If a style sets underlining
/// on, then immediate character formatting cannot turn it off anywhere in a text box that
/// uses that style. See https://silbloom.myjetbrains.com/youtrack/issue/BL-6282.
/// </summary>
private static void FixGroupStyleSettings(XmlNode pageDiv)
{
foreach (
XmlElement groupElement in
pageDiv.SafeSelectNodes("descendant-or-self::*[contains(@class,'bloom-translationGroup')]"))
{
var groupStyle = HtmlDom.GetStyle(groupElement);
if (String.IsNullOrEmpty(groupStyle))
continue;
// Copy the group's style setting to any child div with the bloom-editable class that lacks one.
// Then remove the group style if it does have any child divs with the bloom-editable class.
bool hasInternalEditableDiv = false;
foreach (XmlElement element in groupElement.SafeSelectNodes("child::div[contains(@class, 'bloom-editable')]"))
{
var divStyle = HtmlDom.GetStyle(element);
if (String.IsNullOrEmpty(divStyle))
HtmlDom.AddClass(element, groupStyle);
hasInternalEditableDiv = true;
}
if (hasInternalEditableDiv)
HtmlDom.RemoveClass(groupElement, groupStyle);
}
}
/// <summary>
/// For each group (meaning they have a common parent) of editable items, we
/// need to make sure there are the correct set of copies, with appropriate @lang attributes
/// </summary>
public static XmlElement MakeElementWithLanguageForOneGroup(XmlElement groupElement, string isoCode)
{
if (groupElement.GetAttribute("class").Contains("STOP"))
{
Console.Write("stop");
}
XmlNodeList editableChildrenOfTheGroup =
groupElement.SafeSelectNodes("*[self::textarea or contains(@class,'bloom-editable')]");
var elementsAlreadyInThisLanguage = from XmlElement x in editableChildrenOfTheGroup
where x.GetAttribute("lang") == isoCode
select x;
if (elementsAlreadyInThisLanguage.Any())
//don't mess with this set, it already has a vernacular (this will happen when we're editing a shellbook, not just using it to make a vernacular edition)
return elementsAlreadyInThisLanguage.First();
if (groupElement.SafeSelectNodes("ancestor-or-self::*[contains(@class,'bloom-translationGroup')]").Count == 0)
return null;
var prototype = editableChildrenOfTheGroup[0] as XmlElement;
XmlElement newElementInThisLanguage;
if (prototype == null) //this was an empty translation-group (unusual, but we can cope)
{
newElementInThisLanguage = groupElement.OwnerDocument.CreateElement("div");
newElementInThisLanguage.SetAttribute("class", "bloom-editable");
newElementInThisLanguage.SetAttribute("contenteditable", "true");
if (groupElement.HasAttribute("data-placeholder"))
{
newElementInThisLanguage.SetAttribute("data-placeholder", groupElement.GetAttribute("data-placeholder"));
}
groupElement.AppendChild(newElementInThisLanguage);
}
else //this is the normal situation, where we're just copying the first element
{
//what we want to do is copy everything in the element, except that which is specific to a language.
//so classes on the element, non-text children (like images), etc. should be copied
newElementInThisLanguage = (XmlElement) prototype.ParentNode.InsertAfter(prototype.Clone(), prototype);
//if there is an id, get rid of it, because we don't want 2 elements with the same id
newElementInThisLanguage.RemoveAttribute("id");
// Since we change the ID, the corresponding mp3 will change, which means the duration is no longer valid
newElementInThisLanguage.RemoveAttribute("data-duration");
// No need to copy over the audio-sentence markup
// Various code expects elements with class audio-sentence to have an ID.
// Both will be added when and if we do audio recording (in whole-text-box mode) on the new div.
// Until then it makes things more consistent if we make sure elements without ids
// don't have this class.
// Also, if audio recording markup is done using one audio-sentence span per sentence, we won't copy it. (Because we strip all out the text underneath this node)
// So, it's more consistent to treat all scenarios the same way (don't copy the audio-sentence markup)
HtmlDom.RemoveClass(newElementInThisLanguage, "audio-sentence");
// Nor any need to copy over other audio markup
// We want to clear up all the audio markup so it's not left in an inconsistent state
// where the Talking Book JS code thinks it's been initialized already, but actually all the audio-sentence markup has been stripped out :(
// See BL-8215
newElementInThisLanguage.RemoveAttribute("data-audiorecordingmode");
newElementInThisLanguage.RemoveAttribute("data-audiorecordingendtimes");
HtmlDom.RemoveClass(newElementInThisLanguage, "bloom-postAudioSplit");
//OK, now any text in there will belong to the prototype language, so remove it, while retaining everything else
StripOutText(newElementInThisLanguage);
}
newElementInThisLanguage.SetAttribute("lang", isoCode);
return newElementInThisLanguage;
}
/// <summary>
/// Remove nodes that are either pure text or exist only to contain text, including BR and P
/// Elements with a "bloom-cloneToOtherLanguages" class are preserved
/// </summary>
/// <param name="element"></param>
private static void StripOutText(XmlNode element)
{
var listToRemove = new List<XmlNode>();
foreach (XmlNode node in element.SelectNodes("descendant-or-self::*[(self::p or self::br or self::u or self::b or self::i) and not(contains(@class,'bloom-cloneToOtherLanguages'))]"))
{
listToRemove.Add(node);
}
// clean up any remaining texts that weren't enclosed
foreach (XmlNode node in element.SelectNodes("descendant-or-self::*[not(contains(@class,'bloom-cloneToOtherLanguages'))]/text()"))
{
listToRemove.Add(node);
}
RemoveXmlChildren(listToRemove);
}
private static void RemoveXmlChildren(List<XmlNode> removalList)
{
foreach (var node in removalList)
{
if(node.ParentNode != null)
node.ParentNode.RemoveChild(node);
}
}
/// <summary>
/// Sort the list of translation groups into the order their audio should be spoken,
/// which is also the order used for Spreadsheet import/export. Ones that have tabindex are
/// sorted by that. Ones that don't sort after ones that do, in the order
/// they occur in the input list (that is, the sort is stable, typically preserving
/// document order if that is how the input list was generated).
/// </summary>
/// <param name="groups"></param>
/// <returns></returns>
public static List<XmlElement> SortTranslationGroups(IEnumerable<XmlElement> groups)
{
// This is better than making the list and then using List's Sort method,
// because it is guaranteed to be a stable sort, keeping things with the same
// (or no) tabindex in the original, typically document, order.
return groups.OrderBy(GetTabIndex).ToList();
}
private static int GetTabIndex(XmlElement x)
{
if (Int32.TryParse(x.Attributes["tabindex"]?.Value ?? "x", out int val))
return val;
return Int32.MaxValue;
}
/// <summary>
/// bloom-translationGroup elements on the page in audio-reading order.
/// </summary>
public static List<XmlElement> SortedGroupsOnPage(XmlElement page, bool omitBoxHeaders = false)
{
return TranslationGroupManager.SortTranslationGroups(GetTranslationGroups(page, omitBoxHeaders));
}
}
}
| |
// Copyright 2017, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api;
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.Monitoring.V3;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Monitoring.V3.Snippets
{
public class GeneratedMetricServiceClientSnippets
{
public async Task ListMonitoredResourceDescriptorsAsync()
{
// Snippet: ListMonitoredResourceDescriptorsAsync(ProjectName,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response =
metricServiceClient.ListMonitoredResourceDescriptorsAsync(name);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MonitoredResourceDescriptor item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListMonitoredResourceDescriptorsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MonitoredResourceDescriptor item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MonitoredResourceDescriptor> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MonitoredResourceDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListMonitoredResourceDescriptors()
{
// Snippet: ListMonitoredResourceDescriptors(ProjectName,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
// Make the request
PagedEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response =
metricServiceClient.ListMonitoredResourceDescriptors(name);
// Iterate over all response items, lazily performing RPCs as required
foreach (MonitoredResourceDescriptor item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListMonitoredResourceDescriptorsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MonitoredResourceDescriptor item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MonitoredResourceDescriptor> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MonitoredResourceDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public async Task ListMonitoredResourceDescriptorsAsync_RequestObject()
{
// Snippet: ListMonitoredResourceDescriptorsAsync(ListMonitoredResourceDescriptorsRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest
{
ProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response =
metricServiceClient.ListMonitoredResourceDescriptorsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MonitoredResourceDescriptor item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListMonitoredResourceDescriptorsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MonitoredResourceDescriptor item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MonitoredResourceDescriptor> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MonitoredResourceDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListMonitoredResourceDescriptors_RequestObject()
{
// Snippet: ListMonitoredResourceDescriptors(ListMonitoredResourceDescriptorsRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest
{
ProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response =
metricServiceClient.ListMonitoredResourceDescriptors(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (MonitoredResourceDescriptor item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListMonitoredResourceDescriptorsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MonitoredResourceDescriptor item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MonitoredResourceDescriptor> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MonitoredResourceDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public async Task GetMonitoredResourceDescriptorAsync()
{
// Snippet: GetMonitoredResourceDescriptorAsync(MonitoredResourceDescriptorName,CallSettings)
// Additional: GetMonitoredResourceDescriptorAsync(MonitoredResourceDescriptorName,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
MonitoredResourceDescriptorName name = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]");
// Make the request
MonitoredResourceDescriptor response = await metricServiceClient.GetMonitoredResourceDescriptorAsync(name);
// End snippet
}
public void GetMonitoredResourceDescriptor()
{
// Snippet: GetMonitoredResourceDescriptor(MonitoredResourceDescriptorName,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
MonitoredResourceDescriptorName name = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]");
// Make the request
MonitoredResourceDescriptor response = metricServiceClient.GetMonitoredResourceDescriptor(name);
// End snippet
}
public async Task GetMonitoredResourceDescriptorAsync_RequestObject()
{
// Snippet: GetMonitoredResourceDescriptorAsync(GetMonitoredResourceDescriptorRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest
{
MonitoredResourceDescriptorName = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"),
};
// Make the request
MonitoredResourceDescriptor response = await metricServiceClient.GetMonitoredResourceDescriptorAsync(request);
// End snippet
}
public void GetMonitoredResourceDescriptor_RequestObject()
{
// Snippet: GetMonitoredResourceDescriptor(GetMonitoredResourceDescriptorRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest
{
MonitoredResourceDescriptorName = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"),
};
// Make the request
MonitoredResourceDescriptor response = metricServiceClient.GetMonitoredResourceDescriptor(request);
// End snippet
}
public async Task ListMetricDescriptorsAsync()
{
// Snippet: ListMetricDescriptorsAsync(ProjectName,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> response =
metricServiceClient.ListMetricDescriptorsAsync(name);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MetricDescriptor item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListMetricDescriptorsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MetricDescriptor item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MetricDescriptor> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MetricDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListMetricDescriptors()
{
// Snippet: ListMetricDescriptors(ProjectName,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
// Make the request
PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> response =
metricServiceClient.ListMetricDescriptors(name);
// Iterate over all response items, lazily performing RPCs as required
foreach (MetricDescriptor item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListMetricDescriptorsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MetricDescriptor item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MetricDescriptor> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MetricDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public async Task ListMetricDescriptorsAsync_RequestObject()
{
// Snippet: ListMetricDescriptorsAsync(ListMetricDescriptorsRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ListMetricDescriptorsRequest request = new ListMetricDescriptorsRequest
{
ProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> response =
metricServiceClient.ListMetricDescriptorsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MetricDescriptor item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListMetricDescriptorsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MetricDescriptor item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MetricDescriptor> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MetricDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListMetricDescriptors_RequestObject()
{
// Snippet: ListMetricDescriptors(ListMetricDescriptorsRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ListMetricDescriptorsRequest request = new ListMetricDescriptorsRequest
{
ProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> response =
metricServiceClient.ListMetricDescriptors(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (MetricDescriptor item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListMetricDescriptorsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MetricDescriptor item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MetricDescriptor> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MetricDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public async Task GetMetricDescriptorAsync()
{
// Snippet: GetMetricDescriptorAsync(MetricDescriptorName,CallSettings)
// Additional: GetMetricDescriptorAsync(MetricDescriptorName,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
// Make the request
MetricDescriptor response = await metricServiceClient.GetMetricDescriptorAsync(name);
// End snippet
}
public void GetMetricDescriptor()
{
// Snippet: GetMetricDescriptor(MetricDescriptorName,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
// Make the request
MetricDescriptor response = metricServiceClient.GetMetricDescriptor(name);
// End snippet
}
public async Task GetMetricDescriptorAsync_RequestObject()
{
// Snippet: GetMetricDescriptorAsync(GetMetricDescriptorRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
GetMetricDescriptorRequest request = new GetMetricDescriptorRequest
{
MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
// Make the request
MetricDescriptor response = await metricServiceClient.GetMetricDescriptorAsync(request);
// End snippet
}
public void GetMetricDescriptor_RequestObject()
{
// Snippet: GetMetricDescriptor(GetMetricDescriptorRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
GetMetricDescriptorRequest request = new GetMetricDescriptorRequest
{
MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
// Make the request
MetricDescriptor response = metricServiceClient.GetMetricDescriptor(request);
// End snippet
}
public async Task CreateMetricDescriptorAsync()
{
// Snippet: CreateMetricDescriptorAsync(ProjectName,MetricDescriptor,CallSettings)
// Additional: CreateMetricDescriptorAsync(ProjectName,MetricDescriptor,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
MetricDescriptor metricDescriptor = new MetricDescriptor();
// Make the request
MetricDescriptor response = await metricServiceClient.CreateMetricDescriptorAsync(name, metricDescriptor);
// End snippet
}
public void CreateMetricDescriptor()
{
// Snippet: CreateMetricDescriptor(ProjectName,MetricDescriptor,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
MetricDescriptor metricDescriptor = new MetricDescriptor();
// Make the request
MetricDescriptor response = metricServiceClient.CreateMetricDescriptor(name, metricDescriptor);
// End snippet
}
public async Task CreateMetricDescriptorAsync_RequestObject()
{
// Snippet: CreateMetricDescriptorAsync(CreateMetricDescriptorRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
ProjectName = new ProjectName("[PROJECT]"),
MetricDescriptor = new MetricDescriptor(),
};
// Make the request
MetricDescriptor response = await metricServiceClient.CreateMetricDescriptorAsync(request);
// End snippet
}
public void CreateMetricDescriptor_RequestObject()
{
// Snippet: CreateMetricDescriptor(CreateMetricDescriptorRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
ProjectName = new ProjectName("[PROJECT]"),
MetricDescriptor = new MetricDescriptor(),
};
// Make the request
MetricDescriptor response = metricServiceClient.CreateMetricDescriptor(request);
// End snippet
}
public async Task DeleteMetricDescriptorAsync()
{
// Snippet: DeleteMetricDescriptorAsync(MetricDescriptorName,CallSettings)
// Additional: DeleteMetricDescriptorAsync(MetricDescriptorName,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
// Make the request
await metricServiceClient.DeleteMetricDescriptorAsync(name);
// End snippet
}
public void DeleteMetricDescriptor()
{
// Snippet: DeleteMetricDescriptor(MetricDescriptorName,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
// Make the request
metricServiceClient.DeleteMetricDescriptor(name);
// End snippet
}
public async Task DeleteMetricDescriptorAsync_RequestObject()
{
// Snippet: DeleteMetricDescriptorAsync(DeleteMetricDescriptorRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest
{
MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
// Make the request
await metricServiceClient.DeleteMetricDescriptorAsync(request);
// End snippet
}
public void DeleteMetricDescriptor_RequestObject()
{
// Snippet: DeleteMetricDescriptor(DeleteMetricDescriptorRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest
{
MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
// Make the request
metricServiceClient.DeleteMetricDescriptor(request);
// End snippet
}
public async Task ListTimeSeriesAsync()
{
// Snippet: ListTimeSeriesAsync(ProjectName,string,TimeInterval,ListTimeSeriesRequest.Types.TimeSeriesView,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
string filter = "";
TimeInterval interval = new TimeInterval();
ListTimeSeriesRequest.Types.TimeSeriesView view = ListTimeSeriesRequest.Types.TimeSeriesView.Full;
// Make the request
PagedAsyncEnumerable<ListTimeSeriesResponse, TimeSeries> response =
metricServiceClient.ListTimeSeriesAsync(name, filter, interval, view);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TimeSeries item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTimeSeriesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TimeSeries item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TimeSeries> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TimeSeries item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListTimeSeries()
{
// Snippet: ListTimeSeries(ProjectName,string,TimeInterval,ListTimeSeriesRequest.Types.TimeSeriesView,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
string filter = "";
TimeInterval interval = new TimeInterval();
ListTimeSeriesRequest.Types.TimeSeriesView view = ListTimeSeriesRequest.Types.TimeSeriesView.Full;
// Make the request
PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
metricServiceClient.ListTimeSeries(name, filter, interval, view);
// Iterate over all response items, lazily performing RPCs as required
foreach (TimeSeries item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTimeSeriesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TimeSeries item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TimeSeries> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TimeSeries item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public async Task ListTimeSeriesAsync_RequestObject()
{
// Snippet: ListTimeSeriesAsync(ListTimeSeriesRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ListTimeSeriesRequest request = new ListTimeSeriesRequest
{
ProjectName = new ProjectName("[PROJECT]"),
Filter = "",
Interval = new TimeInterval(),
View = ListTimeSeriesRequest.Types.TimeSeriesView.Full,
};
// Make the request
PagedAsyncEnumerable<ListTimeSeriesResponse, TimeSeries> response =
metricServiceClient.ListTimeSeriesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TimeSeries item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTimeSeriesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TimeSeries item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TimeSeries> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TimeSeries item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public void ListTimeSeries_RequestObject()
{
// Snippet: ListTimeSeries(ListTimeSeriesRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ListTimeSeriesRequest request = new ListTimeSeriesRequest
{
ProjectName = new ProjectName("[PROJECT]"),
Filter = "",
Interval = new TimeInterval(),
View = ListTimeSeriesRequest.Types.TimeSeriesView.Full,
};
// Make the request
PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
metricServiceClient.ListTimeSeries(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (TimeSeries item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTimeSeriesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TimeSeries item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TimeSeries> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TimeSeries item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
public async Task CreateTimeSeriesAsync()
{
// Snippet: CreateTimeSeriesAsync(ProjectName,IEnumerable<TimeSeries>,CallSettings)
// Additional: CreateTimeSeriesAsync(ProjectName,IEnumerable<TimeSeries>,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
IEnumerable<TimeSeries> timeSeries = new List<TimeSeries>();
// Make the request
await metricServiceClient.CreateTimeSeriesAsync(name, timeSeries);
// End snippet
}
public void CreateTimeSeries()
{
// Snippet: CreateTimeSeries(ProjectName,IEnumerable<TimeSeries>,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
IEnumerable<TimeSeries> timeSeries = new List<TimeSeries>();
// Make the request
metricServiceClient.CreateTimeSeries(name, timeSeries);
// End snippet
}
public async Task CreateTimeSeriesAsync_RequestObject()
{
// Snippet: CreateTimeSeriesAsync(CreateTimeSeriesRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
ProjectName = new ProjectName("[PROJECT]"),
TimeSeries = { },
};
// Make the request
await metricServiceClient.CreateTimeSeriesAsync(request);
// End snippet
}
public void CreateTimeSeries_RequestObject()
{
// Snippet: CreateTimeSeries(CreateTimeSeriesRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
ProjectName = new ProjectName("[PROJECT]"),
TimeSeries = { },
};
// Make the request
metricServiceClient.CreateTimeSeries(request);
// End snippet
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.Intrinsics;
namespace System.Runtime.Intrinsics.X86
{
/// <summary>
/// This class provides access to Intel SSE hardware instructions via intrinsics
/// </summary>
[CLSCompliant(false)]
public static class Sse
{
public static bool IsSupported { get { return false; } }
/// <summary>
/// __m128 _mm_add_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> Add(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_and_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> And(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_andnot_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> AndNot(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_cmpeq_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> CompareEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_cmpgt_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> CompareGreaterThan(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_cmpge_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> CompareGreaterThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_cmplt_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> CompareLessThan(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_cmple_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> CompareLessThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_cmpneq_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> CompareNotEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_cmpngt_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> CompareNotGreaterThan(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_cmpnge_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> CompareNotGreaterThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_cmpnlt_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> CompareNotLessThan(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_cmpnle_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> CompareNotLessThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_cmpord_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> CompareOrdered(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_cmpunord_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> CompareUnordered(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_div_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> Divide(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_loadu_ps (float const* mem_address)
/// </summary>
public static unsafe Vector128<float> Load(float* address) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_load_ps (float const* mem_address)
/// </summary>
public static unsafe Vector128<float> LoadAligned(float* address) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_max_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> Max(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_min_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> Min(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_movehl_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> MoveHighToLow(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_movelh_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> MoveLowToHigh(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_mul_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> Multiply(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_or_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> Or(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_rcp_ps (__m128 a)
/// </summary>
public static Vector128<float> Reciprocal(Vector128<float> value) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_rsqrt_ps (__m128 a)
/// </summary>
public static Vector128<float> ReciprocalSquareRoot(Vector128<float> value) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_set_ps (float e3, float e2, float e1, float e0)
/// </summary>
public static Vector128<float> Set(float e3, float e2, float e1, float e0) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_set1_ps (float a)
/// </summary>
public static Vector128<float> Set1(float value) { throw new NotImplementedException(); }
/// <summary>
/// __m128d _mm_setzero_ps (void)
/// </summary>
public static Vector128<float> SetZero() { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_castpd_ps (__m128d a)
/// __m128i _mm_castpd_si128 (__m128d a)
/// __m128d _mm_castps_pd (__m128 a)
/// __m128i _mm_castps_si128 (__m128 a)
/// __m128d _mm_castsi128_pd (__m128i a)
/// __m128 _mm_castsi128_ps (__m128i a)
/// </summary>
public static Vector128<U> StaticCast<T, U>(Vector128<T> value) where T : struct where U : struct { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_shuffle_ps (__m128 a, __m128 b, unsigned int control)
/// </summary>
public static Vector128<float> Shuffle(Vector128<float> left, Vector128<float> right, byte control) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_sqrt_ps (__m128 a)
/// </summary>
public static Vector128<float> Sqrt(Vector128<float> value) { throw new NotImplementedException(); }
/// <summary>
/// void _mm_store_ps (float* mem_addr, __m128 a)
/// </summary>
public static unsafe void StoreAligned(float* address, Vector128<float> source) { throw new NotImplementedException(); }
/// <summary>
/// void _mm_stream_ps (float* mem_addr, __m128 a)
/// </summary>
public static unsafe void StoreAlignedNonTemporal(float* address, Vector128<float> source) { throw new NotImplementedException(); }
/// <summary>
/// void _mm_storeu_ps (float* mem_addr, __m128 a)
/// </summary>
public static unsafe void Store(float* address, Vector128<float> source) { throw new NotImplementedException(); }
/// <summary>
/// __m128d _mm_sub_ps (__m128d a, __m128d b)
/// </summary>
public static Vector128<float> Subtract(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_unpackhi_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> UnpackHigh(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_unpacklo_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> UnpackLow(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
/// <summary>
/// __m128 _mm_xor_ps (__m128 a, __m128 b)
/// </summary>
public static Vector128<float> Xor(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
}
}
| |
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 Samples.WebApi.PolicyService.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;
}
}
}
| |
using System;
using System.Web.UI;
using Rainbow.Framework.DataTypes;
namespace Rainbow.Framework
{
/// <summary>
/// This class holds a single setting in the hashtable,
/// providing information about datatype, costrains.
/// </summary>
public class SettingItem : IComparable
{
private BaseDataType _datatype;
private int _minValue;
private int _maxValue;
private int _order = 0;
private bool _required = false;
//by Manu
private string m_description = string.Empty;
private string m_englishName = string.Empty;
private SettingItemGroup m_Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
// Jes1111
/// <summary>
/// Allows grouping of settings in SettingsTable - use
/// Rainbow.Framework.Configuration.SettingItemGroup enum (convert to string)
/// </summary>
/// <value>The group.</value>
public SettingItemGroup Group
{
get { return m_Group; }
set { m_Group = value; }
}
/// <summary>
/// It provides a description in plain English for
/// Group Key (readonly)
/// </summary>
/// <value>The group description.</value>
public string GroupDescription
{
get
{
switch (m_Group)
{
case SettingItemGroup.NONE:
return "Generic settings";
case SettingItemGroup.THEME_LAYOUT_SETTINGS:
return "Theme and layout settings";
case SettingItemGroup.SECURITY_USER_SETTINGS:
return "Users and Security settings";
case SettingItemGroup.CULTURE_SETTINGS:
return "Culture settings";
case SettingItemGroup.BUTTON_DISPLAY_SETTINGS:
return "Buttons and Display settings";
case SettingItemGroup.MODULE_SPECIAL_SETTINGS:
return "Specific Module settings";
case SettingItemGroup.META_SETTINGS:
return "Meta settings";
case SettingItemGroup.MISC_SETTINGS:
return "Miscellaneous settings";
case SettingItemGroup.NAVIGATION_SETTINGS:
return "Navigation settings";
case SettingItemGroup.CUSTOM_USER_SETTINGS:
return "Custom User Settings";
}
return "Settings";
}
}
/// <summary>
/// Provide help for parameter.
/// Should be a brief, descriptive text that explains what
/// this setting should do.
/// </summary>
/// <value>The description.</value>
public string Description
{
get { return m_description; }
set { m_description = value; }
}
/// <summary>
/// It is the name of the parameter in plain english.
/// </summary>
/// <value>The name of the english.</value>
public string EnglishName
{
get { return m_englishName; }
set { m_englishName = value; }
}
/// <summary>
/// SettingItem
/// </summary>
/// <param name="dt">The dt.</param>
/// <param name="value">The value.</param>
public SettingItem(BaseDataType dt, string value)
{
_datatype = dt;
_datatype.Value = value;
}
/// <summary>
/// SettingItem
/// </summary>
/// <param name="dt">The dt.</param>
public SettingItem(BaseDataType dt)
{
_datatype = dt;
}
/// <summary>
/// ToString converter operator
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static implicit operator string(SettingItem value)
{
return (value.ToString());
}
/// <summary>
/// ToString
/// </summary>
/// <returns>
/// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </returns>
public override string ToString()
{
if (_datatype.Value != null)
return _datatype.Value;
else
return string.Empty;
}
/// <summary>
/// Value
/// </summary>
/// <value>The value.</value>
public string Value
{
get { return _datatype.Value; }
set { _datatype.Value = value; }
}
/// <summary>
/// FullPath
/// </summary>
/// <value>The full path.</value>
public string FullPath
{
get { return _datatype.FullPath; }
}
/// <summary>
/// Required
/// </summary>
/// <value><c>true</c> if required; otherwise, <c>false</c>.</value>
public bool Required
{
get { return _required; }
set { _required = value; }
}
/// <summary>
/// DataType
/// </summary>
/// <value>The type of the data.</value>
public PropertiesDataType DataType
{
get { return _datatype.Type; }
}
/// <summary>
/// EditControl
/// </summary>
/// <value>The edit control.</value>
public Control EditControl
{
get { return _datatype.EditControl; }
set { _datatype.EditControl = value; }
}
/// <summary>
/// MinValue
/// </summary>
/// <value>The min value.</value>
public int MinValue
{
get { return _minValue; }
set { _minValue = value; }
}
/// <summary>
/// MaxValue
/// </summary>
/// <value>The max value.</value>
public int MaxValue
{
get { return _maxValue; }
set { _maxValue = value; }
}
/// <summary>
/// DataSource
/// </summary>
/// <value>The data source.</value>
public object DataSource
{
get { return _datatype.DataSource; }
}
/// <summary>
/// Display Order - use Rainbow.Framework.Configuration.SettingItemGroup enum
/// (add integer in range 1-999)
/// </summary>
/// <value>The order.</value>
public int Order
{
get { return _order; }
set { _order = value; }
}
/// <summary>
/// Public comparer
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public int CompareTo(object value)
{
if (value == null) return 1;
//Modified by Hongwei Shen(hongwei.shen@gmail.com) 10/9/2005
// the "value" should be casted to SettingItem instead of ModuleItem
// int compareOrder = ((ModuleItem) value).Order;
int compareOrder = ((SettingItem) value).Order;
// end of modification
if (Order == compareOrder) return 0;
if (Order < compareOrder) return -1;
if (Order > compareOrder) return 1;
return 0;
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.VirtualAddressBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBVirtualAddressVirtualAddressStatistics))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonULong64))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBObjectStatus))]
public partial class LocalLBVirtualAddress : iControlInterface {
public LocalLBVirtualAddress() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// delete_virtual_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
public void delete_virtual_address(
string [] virtual_addresses
) {
this.Invoke("delete_virtual_address", new object [] {
virtual_addresses});
}
public System.IAsyncResult Begindelete_virtual_address(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_virtual_address", new object[] {
virtual_addresses}, callback, asyncState);
}
public void Enddelete_virtual_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBVirtualAddressVirtualAddressStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((LocalLBVirtualAddressVirtualAddressStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public LocalLBVirtualAddressVirtualAddressStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBVirtualAddressVirtualAddressStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_arp_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_arp_state(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_arp_state", new object [] {
virtual_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_arp_state(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_arp_state", new object[] {
virtual_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_arp_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonULong64 [] get_connection_limit(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_connection_limit", new object [] {
virtual_addresses});
return ((CommonULong64 [])(results[0]));
}
public System.IAsyncResult Beginget_connection_limit(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_limit", new object[] {
virtual_addresses}, callback, asyncState);
}
public CommonULong64 [] Endget_connection_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonULong64 [])(results[0]));
}
//-----------------------------------------------------------------------
// get_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_enabled_state(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_enabled_state", new object [] {
virtual_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_enabled_state(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_enabled_state", new object[] {
virtual_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_is_floating_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_is_floating_state(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_is_floating_state", new object [] {
virtual_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_is_floating_state(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_is_floating_state", new object[] {
virtual_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_is_floating_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_object_status
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBObjectStatus [] get_object_status(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_object_status", new object [] {
virtual_addresses});
return ((LocalLBObjectStatus [])(results[0]));
}
public System.IAsyncResult Beginget_object_status(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_object_status", new object[] {
virtual_addresses}, callback, asyncState);
}
public LocalLBObjectStatus [] Endget_object_status(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBObjectStatus [])(results[0]));
}
//-----------------------------------------------------------------------
// get_route_advertisement_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_route_advertisement_state(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_route_advertisement_state", new object [] {
virtual_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_route_advertisement_state(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_route_advertisement_state", new object[] {
virtual_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_route_advertisement_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBVirtualAddressVirtualAddressStatistics get_statistics(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_statistics", new object [] {
virtual_addresses});
return ((LocalLBVirtualAddressVirtualAddressStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
virtual_addresses}, callback, asyncState);
}
public LocalLBVirtualAddressVirtualAddressStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBVirtualAddressVirtualAddressStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_status_dependency_scope
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBVirtualAddressStatusDependency [] get_status_dependency_scope(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_status_dependency_scope", new object [] {
virtual_addresses});
return ((LocalLBVirtualAddressStatusDependency [])(results[0]));
}
public System.IAsyncResult Beginget_status_dependency_scope(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_status_dependency_scope", new object[] {
virtual_addresses}, callback, asyncState);
}
public LocalLBVirtualAddressStatusDependency [] Endget_status_dependency_scope(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBVirtualAddressStatusDependency [])(results[0]));
}
//-----------------------------------------------------------------------
// get_unit_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_unit_id(
string [] virtual_addresses
) {
object [] results = this.Invoke("get_unit_id", new object [] {
virtual_addresses});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_unit_id(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_unit_id", new object[] {
virtual_addresses}, callback, asyncState);
}
public long [] Endget_unit_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
public void reset_statistics(
string [] virtual_addresses
) {
this.Invoke("reset_statistics", new object [] {
virtual_addresses});
}
public System.IAsyncResult Beginreset_statistics(string [] virtual_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
virtual_addresses}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_arp_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
public void set_arp_state(
string [] virtual_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_arp_state", new object [] {
virtual_addresses,
states});
}
public System.IAsyncResult Beginset_arp_state(string [] virtual_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_arp_state", new object[] {
virtual_addresses,
states}, callback, asyncState);
}
public void Endset_arp_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
public void set_connection_limit(
string [] virtual_addresses,
CommonULong64 [] limits
) {
this.Invoke("set_connection_limit", new object [] {
virtual_addresses,
limits});
}
public System.IAsyncResult Beginset_connection_limit(string [] virtual_addresses,CommonULong64 [] limits, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_limit", new object[] {
virtual_addresses,
limits}, callback, asyncState);
}
public void Endset_connection_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
public void set_enabled_state(
string [] virtual_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_enabled_state", new object [] {
virtual_addresses,
states});
}
public System.IAsyncResult Beginset_enabled_state(string [] virtual_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_enabled_state", new object[] {
virtual_addresses,
states}, callback, asyncState);
}
public void Endset_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_is_floating_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
public void set_is_floating_state(
string [] virtual_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_is_floating_state", new object [] {
virtual_addresses,
states});
}
public System.IAsyncResult Beginset_is_floating_state(string [] virtual_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_is_floating_state", new object[] {
virtual_addresses,
states}, callback, asyncState);
}
public void Endset_is_floating_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_route_advertisement_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
public void set_route_advertisement_state(
string [] virtual_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_route_advertisement_state", new object [] {
virtual_addresses,
states});
}
public System.IAsyncResult Beginset_route_advertisement_state(string [] virtual_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_route_advertisement_state", new object[] {
virtual_addresses,
states}, callback, asyncState);
}
public void Endset_route_advertisement_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_status_dependency_scope
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
public void set_status_dependency_scope(
string [] virtual_addresses,
LocalLBVirtualAddressStatusDependency [] scopes
) {
this.Invoke("set_status_dependency_scope", new object [] {
virtual_addresses,
scopes});
}
public System.IAsyncResult Beginset_status_dependency_scope(string [] virtual_addresses,LocalLBVirtualAddressStatusDependency [] scopes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_status_dependency_scope", new object[] {
virtual_addresses,
scopes}, callback, asyncState);
}
public void Endset_status_dependency_scope(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_unit_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/VirtualAddress",
RequestNamespace="urn:iControl:LocalLB/VirtualAddress", ResponseNamespace="urn:iControl:LocalLB/VirtualAddress")]
public void set_unit_id(
string [] virtual_addresses,
long [] unit_ids
) {
this.Invoke("set_unit_id", new object [] {
virtual_addresses,
unit_ids});
}
public System.IAsyncResult Beginset_unit_id(string [] virtual_addresses,long [] unit_ids, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_unit_id", new object[] {
virtual_addresses,
unit_ids}, callback, asyncState);
}
public void Endset_unit_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.VirtualAddress.VirtualAddressStatisticEntry", Namespace = "urn:iControl")]
public partial class LocalLBVirtualAddressVirtualAddressStatisticEntry
{
private string virtual_addressField;
public string virtual_address
{
get { return this.virtual_addressField; }
set { this.virtual_addressField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.VirtualAddress.VirtualAddressStatistics", Namespace = "urn:iControl")]
public partial class LocalLBVirtualAddressVirtualAddressStatistics
{
private LocalLBVirtualAddressVirtualAddressStatisticEntry [] statisticsField;
public LocalLBVirtualAddressVirtualAddressStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Diagnostics;
using Test.Utilities;
using Xunit;
namespace Microsoft.Maintainability.Analyzers.UnitTests
{
public class DoNotIgnoreMethodResultsTests : DiagnosticAnalyzerTestBase
{
#region Unit tests for no analyzer diagnostic
[Fact]
[WorkItem(462, "https://github.com/dotnet/roslyn-analyzers/issues/462")]
public void UsedInvocationResult()
{
VerifyCSharp(@"
using System.Runtime.InteropServices;
public class C
{
private static void M(string x, out int y)
{
// Object creation
var c = new C();
// String creation
var xUpper = x.ToUpper();
// Try parse
if (!int.TryParse(x, out y))
{
return;
}
var result = NativeMethod();
}
[DllImport(""user32.dll"")]
private static extern int NativeMethod();
}
");
VerifyBasic(@"
Imports System.Runtime.InteropServices
Public Class C
Private Shared Sub M(x As String, ByRef y As Integer)
' Object creation
Dim c = New C()
' String creation
Dim xUpper = x.ToUpper()
' Try parse
If Not Integer.TryParse(x, y) Then
Return
End If
Dim result = NativeMethod()
End Sub
<DllImport(""user32.dll"")> _
Private Shared Function NativeMethod() As Integer
End Function
End Class
");
}
#endregion
#region Unit tests for analyzer diagnostic(s)
[Fact]
[WorkItem(462, "https://github.com/dotnet/roslyn-analyzers/issues/462")]
public void UnusedStringCreation()
{
VerifyCSharp(@"
using System;
using System.Globalization;
class C
{
public void DoesNotAssignStringToVariable()
{
Console.WriteLine(this);
string sample = ""Sample"";
sample.ToLower(CultureInfo.InvariantCulture);
return;
}
}
",
GetCSharpStringCreationResultAt(11, 9, "DoesNotAssignStringToVariable", "ToLower"));
VerifyBasic(@"
Imports System
Imports System.Globalization
Class C
Public Sub DoesNotAssignStringToVariable()
Console.WriteLine(Me)
Dim sample As String = ""Sample""
sample.ToLower(CultureInfo.InvariantCulture)
Return
End Sub
End Class
",
GetBasicStringCreationResultAt(9, 9, "DoesNotAssignStringToVariable", "ToLower"));
}
[Fact]
[WorkItem(462, "https://github.com/dotnet/roslyn-analyzers/issues/462")]
public void UnusedObjectCreation()
{
VerifyCSharp(@"
using System;
using System.Globalization;
class C
{
public void DoesNotAssignObjectToVariable()
{
new C();
}
}
",
GetCSharpObjectCreationResultAt(9, 9, "DoesNotAssignObjectToVariable", "C"));
// Following code produces syntax error for VB, so no object creation diagnostic.
VerifyBasic(@"
Imports System
Imports System.Globalization
Class C
Public Sub DoesNotAssignObjectToVariable()
New C() ' error BC30035: Syntax error
End Sub
End Class
", TestValidationMode.AllowCompileErrors);
}
[Fact]
[WorkItem(462, "https://github.com/dotnet/roslyn-analyzers/issues/462")]
public void UnusedTryParseResult()
{
VerifyCSharp(@"
using System.Runtime.InteropServices;
public class C
{
private static void M(string x, out int y)
{
// Try parse
int.TryParse(x, out y);
}
}
",
GetCSharpTryParseResultAt(9, 9, "M", "TryParse"));
VerifyBasic(@"
Imports System.Runtime.InteropServices
Public Class C
Private Shared Sub M(x As String, ByRef y As Integer)
' Try parse
Integer.TryParse(x, y)
End Sub
End Class
",
GetBasicTryParseResultAt(7, 9, "M", "TryParse"));
}
[Fact]
[WorkItem(462, "https://github.com/dotnet/roslyn-analyzers/issues/462")]
public void UnusedPInvokeResult()
{
VerifyCSharp(@"
using System.Runtime.InteropServices;
public class C
{
private static void M(string x, out int y)
{
y = 1;
NativeMethod();
}
[DllImport(""user32.dll"")]
private static extern int NativeMethod();
}
",
GetCSharpHResultOrErrorCodeResultAt(9, 9, "M", "NativeMethod"));
VerifyBasic(@"
Imports System.Runtime.InteropServices
Public Class C
Private Shared Sub M(x As String, ByRef y As Integer)
NativeMethod()
End Sub
<DllImport(""user32.dll"")> _
Private Shared Function NativeMethod() As Integer
End Function
End Class
",
GetBasicHResultOrErrorCodeResultAt(6, 9, "M", "NativeMethod"));
}
[Fact(Skip = "746")]
[WorkItem(746, "https://github.com/dotnet/roslyn-analyzers/issues/746")]
public void UnusedComImportPreserveSig()
{
VerifyCSharp(@"
using System.Runtime.InteropServices;
public class C
{
private static void M(IComClass cc)
{
cc.NativeMethod();
}
}
[ComImport]
[Guid(""060DDE7F-A9CD-4669-A443-B6E25AF44E7C"")]
public interface IComClass
{
[PreserveSig]
int NativeMethod();
}
",
GetCSharpHResultOrErrorCodeResultAt(8, 9, "M", "NativeMethod"));
VerifyBasic(@"
Imports System.Runtime.InteropServices
Public Class C
Private Shared Sub M(cc As IComClass)
cc.NativeMethod()
End Sub
End Class
<ComImport> _
<Guid(""060DDE7F-A9CD-4669-A443-B6E25AF44E7C"")> _
Public Interface IComClass
<PreserveSig> _
Function NativeMethod() As Integer
End Interface
",
GetBasicHResultOrErrorCodeResultAt(6, 9, "M", "NativeMethod"));
}
#endregion
#region Helpers
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new DoNotIgnoreMethodResultsAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new DoNotIgnoreMethodResultsAnalyzer();
}
private static DiagnosticResult GetCSharpStringCreationResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageStringCreation, containingMethodName, invokedMethodName);
return GetCSharpResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetBasicStringCreationResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageStringCreation, containingMethodName, invokedMethodName);
return GetBasicResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetCSharpObjectCreationResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageObjectCreation, containingMethodName, invokedMethodName);
return GetCSharpResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetCSharpTryParseResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageTryParse, containingMethodName, invokedMethodName);
return GetCSharpResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetBasicTryParseResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageTryParse, containingMethodName, invokedMethodName);
return GetBasicResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetCSharpHResultOrErrorCodeResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageHResultOrErrorCode, containingMethodName, invokedMethodName);
return GetCSharpResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetBasicHResultOrErrorCodeResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageHResultOrErrorCode, containingMethodName, invokedMethodName);
return GetBasicResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias PDB;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.DiaSymReader;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
using PDB::Roslyn.Test.MetadataUtilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class Scope
{
internal readonly int StartOffset;
internal readonly int EndOffset;
internal readonly ImmutableArray<string> Locals;
internal Scope(int startOffset, int endOffset, ImmutableArray<string> locals, bool isEndInclusive)
{
this.StartOffset = startOffset;
this.EndOffset = endOffset + (isEndInclusive ? 1 : 0);
this.Locals = locals;
}
internal int Length
{
get { return this.EndOffset - this.StartOffset + 1; }
}
internal bool Contains(int offset)
{
return (offset >= this.StartOffset) && (offset < this.EndOffset);
}
}
internal static class ExpressionCompilerTestHelpers
{
internal static CompileResult CompileAssignment(
this EvaluationContextBase context,
string target,
string expr,
out string error,
CompilationTestData testData = null,
DiagnosticFormatter formatter = null)
{
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileAssignment(
target,
expr,
ImmutableArray<Alias>.Empty,
formatter ?? DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
// This is a crude way to test the language, but it's convenient to share this test helper.
var isCSharp = context.GetType().Namespace.IndexOf("csharp", StringComparison.OrdinalIgnoreCase) >= 0;
var expectedFlags = error != null
? DkmClrCompilationResultFlags.None
: isCSharp
? DkmClrCompilationResultFlags.PotentialSideEffect
: DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult;
Assert.Equal(expectedFlags, resultProperties.Flags);
Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category);
Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType);
Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType);
Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags);
return result;
}
internal static CompileResult CompileAssignment(
this EvaluationContextBase context,
string target,
string expr,
ImmutableArray<Alias> aliases,
DiagnosticFormatter formatter,
out ResultProperties resultProperties,
out string error,
out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities,
CultureInfo preferredUICulture,
CompilationTestData testData)
{
var diagnostics = DiagnosticBag.GetInstance();
var result = context.CompileAssignment(target, expr, aliases, diagnostics, out resultProperties, testData);
if (diagnostics.HasAnyErrors())
{
bool useReferencedModulesOnly;
error = context.GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, EvaluationContextBase.SystemCoreIdentity, out useReferencedModulesOnly, out missingAssemblyIdentities);
}
else
{
error = null;
missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty;
}
diagnostics.Free();
return result;
}
internal static ReadOnlyCollection<byte> CompileGetLocals(
this EvaluationContextBase context,
ArrayBuilder<LocalAndMethod> locals,
bool argumentsOnly,
out string typeName,
CompilationTestData testData,
DiagnosticDescription[] expectedDiagnostics = null)
{
var diagnostics = DiagnosticBag.GetInstance();
var result = context.CompileGetLocals(
locals,
argumentsOnly,
ImmutableArray<Alias>.Empty,
diagnostics,
out typeName,
testData);
diagnostics.Verify(expectedDiagnostics ?? DiagnosticDescription.None);
diagnostics.Free();
return result;
}
internal static CompileResult CompileExpression(
this EvaluationContextBase context,
string expr,
out string error,
CompilationTestData testData = null,
DiagnosticFormatter formatter = null)
{
ResultProperties resultProperties;
return CompileExpression(context, expr, out resultProperties, out error, testData, formatter);
}
internal static CompileResult CompileExpression(
this EvaluationContextBase context,
string expr,
out ResultProperties resultProperties,
out string error,
CompilationTestData testData = null,
DiagnosticFormatter formatter = null)
{
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
expr,
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray<Alias>.Empty,
formatter ?? DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
return result;
}
static internal CompileResult CompileExpression(
this EvaluationContextBase evaluationContext,
string expr,
DkmEvaluationFlags compilationFlags,
ImmutableArray<Alias> aliases,
out string error,
CompilationTestData testData = null,
DiagnosticFormatter formatter = null)
{
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = evaluationContext.CompileExpression(
expr,
compilationFlags,
aliases,
formatter ?? DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
return result;
}
/// <summary>
/// Compile C# expression and emit assembly with evaluation method.
/// </summary>
/// <returns>
/// Result containing generated assembly, type and method names, and any format specifiers.
/// </returns>
static internal CompileResult CompileExpression(
this EvaluationContextBase evaluationContext,
string expr,
DkmEvaluationFlags compilationFlags,
ImmutableArray<Alias> aliases,
DiagnosticFormatter formatter,
out ResultProperties resultProperties,
out string error,
out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities,
CultureInfo preferredUICulture,
CompilationTestData testData)
{
var diagnostics = DiagnosticBag.GetInstance();
var result = evaluationContext.CompileExpression(expr, compilationFlags, aliases, diagnostics, out resultProperties, testData);
if (diagnostics.HasAnyErrors())
{
bool useReferencedModulesOnly;
error = evaluationContext.GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, EvaluationContextBase.SystemCoreIdentity, out useReferencedModulesOnly, out missingAssemblyIdentities);
}
else
{
error = null;
missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty;
}
diagnostics.Free();
return result;
}
internal static CompileResult CompileExpressionWithRetry(
ImmutableArray<MetadataBlock> metadataBlocks,
EvaluationContextBase context,
ExpressionCompiler.CompileDelegate<CompileResult> compile,
DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
out string errorMessage)
{
return ExpressionCompiler.CompileWithRetry(
metadataBlocks,
DiagnosticFormatter.Instance,
(blocks, useReferencedModulesOnly) => context,
compile,
getMetaDataBytesPtr,
out errorMessage);
}
internal static CompileResult CompileExpressionWithRetry(
ImmutableArray<MetadataBlock> metadataBlocks,
string expr,
ExpressionCompiler.CreateContextDelegate createContext,
DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
out string errorMessage,
out CompilationTestData testData)
{
var r = ExpressionCompiler.CompileWithRetry(
metadataBlocks,
DiagnosticFormatter.Instance,
createContext,
(context, diagnostics) =>
{
var td = new CompilationTestData();
ResultProperties resultProperties;
var compileResult = context.CompileExpression(
expr,
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray<Alias>.Empty,
diagnostics,
out resultProperties,
td);
return new CompileExpressionResult(compileResult, td);
},
getMetaDataBytesPtr,
out errorMessage);
testData = r.TestData;
return r.CompileResult;
}
private struct CompileExpressionResult
{
internal readonly CompileResult CompileResult;
internal readonly CompilationTestData TestData;
internal CompileExpressionResult(CompileResult compileResult, CompilationTestData testData)
{
this.CompileResult = compileResult;
this.TestData = testData;
}
}
internal static TypeDefinition GetTypeDef(this MetadataReader reader, string typeName)
{
return reader.TypeDefinitions.Select(reader.GetTypeDefinition).First(t => reader.StringComparer.Equals(t.Name, typeName));
}
internal static MethodDefinition GetMethodDef(this MetadataReader reader, TypeDefinition typeDef, string methodName)
{
return typeDef.GetMethods().Select(reader.GetMethodDefinition).First(m => reader.StringComparer.Equals(m.Name, methodName));
}
internal static MethodDefinitionHandle GetMethodDefHandle(this MetadataReader reader, TypeDefinition typeDef, string methodName)
{
return typeDef.GetMethods().First(h => reader.StringComparer.Equals(reader.GetMethodDefinition(h).Name, methodName));
}
internal static void CheckTypeParameters(this MetadataReader reader, GenericParameterHandleCollection genericParameters, params string[] expectedNames)
{
var actualNames = genericParameters.Select(reader.GetGenericParameter).Select(tp => reader.GetString(tp.Name)).ToArray();
Assert.True(expectedNames.SequenceEqual(actualNames));
}
internal static AssemblyName GetAssemblyName(this byte[] exeBytes)
{
using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes)))
{
var metadataReader = reader.GetMetadataReader();
var def = metadataReader.GetAssemblyDefinition();
var name = metadataReader.GetString(def.Name);
return new AssemblyName() { Name = name, Version = def.Version };
}
}
internal static Guid GetModuleVersionId(this byte[] exeBytes)
{
using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes)))
{
return reader.GetMetadataReader().GetModuleVersionId();
}
}
internal static ImmutableArray<string> GetLocalNames(this ISymUnmanagedReader symReader, int methodToken, int methodVersion = 1)
{
var method = symReader.GetMethodByVersion(methodToken, methodVersion);
if (method == null)
{
return ImmutableArray<string>.Empty;
}
var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
method.GetAllScopes(scopes);
var names = ArrayBuilder<string>.GetInstance();
foreach (var scope in scopes)
{
var locals = scope.GetLocals();
foreach (var local in locals)
{
var name = local.GetName();
int slot;
local.GetAddressField1(out slot);
while (names.Count <= slot)
{
names.Add(null);
}
names[slot] = name;
}
}
scopes.Free();
return names.ToImmutableAndFree();
}
internal static void VerifyIL(
this ImmutableArray<byte> assembly,
string qualifiedName,
string expectedIL,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
var parts = qualifiedName.Split('.');
if (parts.Length != 2)
{
throw new NotImplementedException();
}
using (var module = new PEModule(new PEReader(assembly), metadataOpt: IntPtr.Zero, metadataSizeOpt: 0))
{
var reader = module.MetadataReader;
var typeDef = reader.GetTypeDef(parts[0]);
var methodName = parts[1];
var methodHandle = reader.GetMethodDefHandle(typeDef, methodName);
var methodBody = module.GetMethodBodyOrThrow(methodHandle);
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
var writer = new StringWriter(pooled.Builder);
var visualizer = new MetadataVisualizer(reader, writer);
visualizer.VisualizeMethodBody(methodBody, methodHandle, emitHeader: false);
var actualIL = pooled.ToStringAndFree();
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine);
}
}
internal static bool EmitAndGetReferences(
this Compilation compilation,
out byte[] exeBytes,
out byte[] pdbBytes,
out ImmutableArray<MetadataReference> references)
{
using (var pdbStream = new MemoryStream())
{
using (var exeStream = new MemoryStream())
{
var result = compilation.Emit(
peStream: exeStream,
pdbStream: pdbStream,
xmlDocumentationStream: null,
win32Resources: null,
manifestResources: null,
options: EmitOptions.Default,
testData: null,
getHostDiagnostics: null,
cancellationToken: default(CancellationToken));
if (!result.Success)
{
result.Diagnostics.Verify();
exeBytes = null;
pdbBytes = null;
references = default(ImmutableArray<MetadataReference>);
return false;
}
exeBytes = exeStream.ToArray();
pdbBytes = pdbStream.ToArray();
}
}
// Determine the set of references that were actually used
// and ignore any references that were dropped in emit.
HashSet<string> referenceNames;
using (var metadata = ModuleMetadata.CreateFromImage(exeBytes))
{
var reader = metadata.MetadataReader;
referenceNames = new HashSet<string>(reader.AssemblyReferences.Select(h => GetAssemblyReferenceName(reader, h)));
}
references = ImmutableArray.CreateRange(compilation.References.Where(r => IsReferenced(r, referenceNames)));
return true;
}
internal static ImmutableArray<Scope> GetScopes(this ISymUnmanagedReader symReader, int methodToken, int methodVersion, bool isEndInclusive)
{
var method = symReader.GetMethodByVersion(methodToken, methodVersion);
if (method == null)
{
return ImmutableArray<Scope>.Empty;
}
var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
method.GetAllScopes(scopes);
var result = scopes.SelectAsArray(s => new Scope(s.GetStartOffset(), s.GetEndOffset(), s.GetLocals().SelectAsArray(l => l.GetName()), isEndInclusive));
scopes.Free();
return result;
}
internal static Scope GetInnermostScope(this ImmutableArray<Scope> scopes, int offset)
{
Scope result = null;
foreach (var scope in scopes)
{
if (scope.Contains(offset))
{
if ((result == null) || (result.Length > scope.Length))
{
result = scope;
}
}
}
return result;
}
private static string GetAssemblyReferenceName(MetadataReader reader, AssemblyReferenceHandle handle)
{
var reference = reader.GetAssemblyReference(handle);
return reader.GetString(reference.Name);
}
private static bool IsReferenced(MetadataReference reference, HashSet<string> referenceNames)
{
var assemblyMetadata = ((PortableExecutableReference)reference).GetMetadata() as AssemblyMetadata;
if (assemblyMetadata == null)
{
// Netmodule. Assume it is referenced.
return true;
}
var name = assemblyMetadata.GetAssembly().Identity.Name;
return referenceNames.Contains(name);
}
/// <summary>
/// Verify the set of module metadata blocks
/// contains all blocks referenced by the set.
/// </summary>
internal static void VerifyAllModules(this ImmutableArray<ModuleInstance> modules)
{
var blocks = modules.SelectAsArray(m => m.MetadataBlock).SelectAsArray(b => ModuleMetadata.CreateFromMetadata(b.Pointer, b.Size));
var names = new HashSet<string>(blocks.Select(b => b.Name));
foreach (var block in blocks)
{
foreach (var name in block.GetModuleNames())
{
Assert.True(names.Contains(name));
}
}
}
internal static ModuleMetadata GetModuleMetadata(this MetadataReference reference)
{
var metadata = ((MetadataImageReference)reference).GetMetadata();
var assemblyMetadata = metadata as AssemblyMetadata;
Assert.True((assemblyMetadata == null) || (assemblyMetadata.GetModules().Length == 1));
return (assemblyMetadata == null) ? (ModuleMetadata)metadata : assemblyMetadata.GetModules()[0];
}
internal static ModuleInstance ToModuleInstance(
this MetadataReference reference,
byte[] fullImage,
object symReader,
bool includeLocalSignatures = true)
{
var moduleMetadata = reference.GetModuleMetadata();
var moduleId = moduleMetadata.Module.GetModuleVersionIdOrThrow();
// The Expression Compiler expects metadata only, no headers or IL.
var metadataBytes = moduleMetadata.Module.PEReaderOpt.GetMetadata().GetContent().ToArray();
return new ModuleInstance(
reference,
moduleMetadata,
moduleId,
fullImage,
metadataBytes,
symReader,
includeLocalSignatures && (fullImage != null));
}
internal static AssemblyIdentity GetAssemblyIdentity(this MetadataReference reference)
{
var moduleMetadata = reference.GetModuleMetadata();
var reader = moduleMetadata.MetadataReader;
return reader.ReadAssemblyIdentityOrThrow();
}
internal static Guid GetModuleVersionId(this MetadataReference reference)
{
var moduleMetadata = reference.GetModuleMetadata();
var reader = moduleMetadata.MetadataReader;
return reader.GetModuleVersionIdOrThrow();
}
internal static void VerifyLocal<TMethodSymbol>(
this CompilationTestData testData,
string typeName,
LocalAndMethod localAndMethod,
string expectedMethodName,
string expectedLocalName,
string expectedLocalDisplayName,
DkmClrCompilationResultFlags expectedFlags,
Action<TMethodSymbol> verifyTypeParameters,
string expectedILOpt,
bool expectedGeneric,
string expectedValueSourcePath,
int expectedValueSourceLine)
where TMethodSymbol : IMethodSymbol
{
Assert.Equal(expectedLocalName, localAndMethod.LocalName);
Assert.Equal(expectedLocalDisplayName, localAndMethod.LocalDisplayName);
Assert.True(expectedMethodName.StartsWith(localAndMethod.MethodName, StringComparison.Ordinal), expectedMethodName + " does not start with " + localAndMethod.MethodName); // Expected name may include type arguments and parameters.
Assert.Equal(expectedFlags, localAndMethod.Flags);
var methodData = testData.GetMethodData(typeName + "." + expectedMethodName);
verifyTypeParameters((TMethodSymbol)methodData.Method);
if (expectedILOpt != null)
{
string actualIL = methodData.GetMethodIL();
AssertEx.AssertEqualToleratingWhitespaceDifferences(
expectedILOpt,
actualIL,
escapeQuotes: true,
expectedValueSourcePath: expectedValueSourcePath,
expectedValueSourceLine: expectedValueSourceLine);
}
Assert.Equal(((Cci.IMethodDefinition)methodData.Method).CallingConvention, expectedGeneric ? Cci.CallingConvention.Generic : Cci.CallingConvention.Default);
}
internal static ISymUnmanagedReader ConstructSymReaderWithImports(byte[] exeBytes, string methodName, params string[] importStrings)
{
using (var peReader = new PEReader(ImmutableArray.Create(exeBytes)))
{
var metadataReader = peReader.GetMetadataReader();
var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, methodName));
var methodToken = metadataReader.GetToken(methodHandle);
return new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes>
{
{ methodToken, new MethodDebugInfoBytes.Builder(new [] { importStrings }).Build() },
}.ToImmutableDictionary());
}
}
internal const uint NoILOffset = 0xffffffff;
internal static readonly MetadataReference IntrinsicAssemblyReference = GetIntrinsicAssemblyReference();
internal static ImmutableArray<MetadataReference> AddIntrinsicAssembly(this ImmutableArray<MetadataReference> references)
{
var builder = ArrayBuilder<MetadataReference>.GetInstance();
builder.AddRange(references);
builder.Add(IntrinsicAssemblyReference);
return builder.ToImmutableAndFree();
}
private static MetadataReference GetIntrinsicAssemblyReference()
{
var source =
@".assembly extern mscorlib { }
.class public Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods
{
.method public static object GetObjectAtAddress(uint64 address)
{
ldnull
throw
}
.method public static class [mscorlib]System.Exception GetException()
{
ldnull
throw
}
.method public static class [mscorlib]System.Exception GetStowedException()
{
ldnull
throw
}
.method public static object GetReturnValue(int32 index)
{
ldnull
throw
}
.method public static void CreateVariable(class [mscorlib]System.Type 'type', string name, valuetype [mscorlib]System.Guid customTypeInfoPayloadTypeId, uint8[] customTypeInfoPayload)
{
ldnull
throw
}
.method public static object GetObjectByAlias(string name)
{
ldnull
throw
}
.method public static !!T& GetVariableAddress<T>(string name)
{
ldnull
throw
}
}";
return CommonTestBase.CompileIL(source);
}
/// <summary>
/// Return MetadataReferences to the .winmd assemblies
/// for the given namespaces.
/// </summary>
internal static ImmutableArray<MetadataReference> GetRuntimeWinMds(params string[] namespaces)
{
var paths = new HashSet<string>();
foreach (var @namespace in namespaces)
{
foreach (var path in WindowsRuntimeMetadata.ResolveNamespace(@namespace, null))
{
paths.Add(path);
}
}
return ImmutableArray.CreateRange(paths.Select(GetAssembly));
}
private const string Version1_3CLRString = "WindowsRuntime 1.3;CLR v4.0.30319";
private const string Version1_3String = "WindowsRuntime 1.3";
private const string Version1_4String = "WindowsRuntime 1.4";
private static readonly int s_versionStringLength = Version1_3CLRString.Length;
private static readonly byte[] s_version1_3CLRBytes = ToByteArray(Version1_3CLRString, s_versionStringLength);
private static readonly byte[] s_version1_3Bytes = ToByteArray(Version1_3String, s_versionStringLength);
private static readonly byte[] s_version1_4Bytes = ToByteArray(Version1_4String, s_versionStringLength);
private static byte[] ToByteArray(string str, int length)
{
var bytes = new byte[length];
for (int i = 0; i < str.Length; i++)
{
bytes[i] = (byte)str[i];
}
return bytes;
}
internal static byte[] ToVersion1_3(byte[] bytes)
{
return ToVersion(bytes, s_version1_3CLRBytes, s_version1_3Bytes);
}
internal static byte[] ToVersion1_4(byte[] bytes)
{
return ToVersion(bytes, s_version1_3CLRBytes, s_version1_4Bytes);
}
private static byte[] ToVersion(byte[] bytes, byte[] from, byte[] to)
{
int n = bytes.Length;
var copy = new byte[n];
Array.Copy(bytes, copy, n);
int index = IndexOf(copy, from);
Array.Copy(to, 0, copy, index, to.Length);
return copy;
}
private static int IndexOf(byte[] a, byte[] b)
{
int m = b.Length;
int n = a.Length - m;
for (int x = 0; x < n; x++)
{
var matches = true;
for (int y = 0; y < m; y++)
{
if (a[x + y] != b[y])
{
matches = false;
break;
}
}
if (matches)
{
return x;
}
}
return -1;
}
private static MetadataReference GetAssembly(string path)
{
var bytes = File.ReadAllBytes(path);
var metadata = ModuleMetadata.CreateFromImage(bytes);
return metadata.GetReference(filePath: path);
}
internal static uint GetOffset(int methodToken, ISymUnmanagedReader symReader, int atLineNumber = -1)
{
int ilOffset;
if (symReader == null)
{
ilOffset = 0;
}
else
{
var symMethod = symReader.GetMethod(methodToken);
if (symMethod == null)
{
ilOffset = 0;
}
else
{
var sequencePoints = symMethod.GetSequencePoints();
ilOffset = atLineNumber < 0
? sequencePoints.Where(sp => sp.StartLine != SequencePointList.HiddenSequencePointLine).Select(sp => sp.Offset).FirstOrDefault()
: sequencePoints.First(sp => sp.StartLine == atLineNumber).Offset;
}
}
Assert.InRange(ilOffset, 0, int.MaxValue);
return (uint)ilOffset;
}
internal static string GetMethodOrTypeSignatureParts(string signature, out string[] parameterTypeNames)
{
var parameterListStart = signature.IndexOf('(');
if (parameterListStart < 0)
{
parameterTypeNames = null;
return signature;
}
var parameters = signature.Substring(parameterListStart + 1, signature.Length - parameterListStart - 2);
var methodName = signature.Substring(0, parameterListStart);
parameterTypeNames = (parameters.Length == 0) ?
new string[0] :
parameters.Split(',');
return methodName;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Serilog.Sinks.Amazon.Kinesis.Common;
using Serilog.Sinks.Amazon.Kinesis.Logging;
namespace Serilog.Sinks.Amazon.Kinesis
{
abstract class HttpLogShipperBase<TRecord, TResponse>
{
protected ILog Logger { get; }
private readonly ILogReaderFactory _logReaderFactory;
private readonly IPersistedBookmarkFactory _persistedBookmarkFactory;
private readonly ILogShipperFileManager _fileManager;
protected readonly int _batchPostingLimit;
protected readonly string _bookmarkFilename;
protected readonly string _candidateSearchPath;
protected readonly string _logFolder;
protected readonly string _streamName;
protected HttpLogShipperBase(
ILogShipperOptions options,
ILogReaderFactory logReaderFactory,
IPersistedBookmarkFactory persistedBookmarkFactory,
ILogShipperFileManager fileManager
)
{
if (options == null) throw new ArgumentNullException(nameof(options));
if (logReaderFactory == null) throw new ArgumentNullException(nameof(logReaderFactory));
if (persistedBookmarkFactory == null) throw new ArgumentNullException(nameof(persistedBookmarkFactory));
if (fileManager == null) throw new ArgumentNullException(nameof(fileManager));
Logger = LogProvider.GetLogger(GetType());
_logReaderFactory = logReaderFactory;
_persistedBookmarkFactory = persistedBookmarkFactory;
_fileManager = fileManager;
_batchPostingLimit = options.BatchPostingLimit;
_streamName = options.StreamName;
_bookmarkFilename = Path.GetFullPath(options.BufferBaseFilename + ".bookmark");
_logFolder = Path.GetDirectoryName(_bookmarkFilename);
_candidateSearchPath = Path.GetFileName(options.BufferBaseFilename) + "*.json";
Logger.InfoFormat("Candidate search path is {0}", _candidateSearchPath);
Logger.InfoFormat("Log folder is {0}", _logFolder);
}
protected abstract TRecord PrepareRecord(MemoryStream stream);
protected abstract TResponse SendRecords(List<TRecord> records, out bool successful);
protected abstract void HandleError(TResponse response, int originalRecordCount);
public event EventHandler<LogSendErrorEventArgs> LogSendError;
protected void OnLogSendError(LogSendErrorEventArgs e)
{
var handler = LogSendError;
if (handler != null)
{
handler(this, e);
}
}
private IPersistedBookmark TryCreateBookmark()
{
try
{
return _persistedBookmarkFactory.Create(_bookmarkFilename);
}
catch (IOException ex)
{
Logger.TraceException("Bookmark cannot be opened.", ex);
return null;
}
}
protected void ShipLogs()
{
try
{
// Locking the bookmark ensures that though there may be multiple instances of this
// class running, only one will ship logs at a time.
using (var bookmark = TryCreateBookmark())
{
if (bookmark == null)
return;
ShipLogs(bookmark);
}
}
catch (IOException ex)
{
Logger.WarnException("Error shipping logs", ex);
}
catch (Exception ex)
{
Logger.ErrorException("Error shipping logs", ex);
OnLogSendError(new LogSendErrorEventArgs(string.Format("Error in shipping logs to '{0}' stream", _streamName), ex));
}
}
private void ShipLogs(IPersistedBookmark bookmark)
{
do
{
string currentFilePath = bookmark.FileName;
Logger.TraceFormat("Bookmark is currently at offset {0} in '{1}'", bookmark.Position, currentFilePath);
var fileSet = GetFileSet();
if (currentFilePath == null)
{
currentFilePath = fileSet.FirstOrDefault();
Logger.InfoFormat("New log file is {0}", currentFilePath);
bookmark.UpdateFileNameAndPosition(currentFilePath, 0L);
}
else if (fileSet.All(f => CompareFileNames(f, currentFilePath) != 0))
{
currentFilePath = fileSet.FirstOrDefault(f => CompareFileNames(f, currentFilePath) >= 0);
Logger.InfoFormat("New log file is {0}", currentFilePath);
bookmark.UpdateFileNameAndPosition(currentFilePath, 0L);
}
// delete all previous files - we will not read them anyway
if (currentFilePath == null)
{
foreach (var fileToDelete in fileSet)
{
TryDeleteFile(fileToDelete);
}
}
else
{
foreach (var fileToDelete in fileSet.TakeWhile(f => CompareFileNames(f, currentFilePath) < 0))
{
TryDeleteFile(fileToDelete);
}
}
if (currentFilePath == null)
{
Logger.InfoFormat("No log file is found. Nothing to do.");
break;
}
// now we are interested in current file and all after it.
fileSet =
fileSet.SkipWhile(f => CompareFileNames(f, currentFilePath) < 0)
.ToArray();
var initialPosition = bookmark.Position;
List<TRecord> records;
do
{
var batch = ReadRecordBatch(currentFilePath, bookmark.Position, _batchPostingLimit);
records = batch.Item2;
if (records.Count > 0)
{
bool successful;
var response = SendRecords(records, out successful);
if (!successful)
{
Logger.ErrorFormat("SendRecords failed for {0} records.", records.Count);
HandleError(response, records.Count);
return;
}
}
var newPosition = batch.Item1;
if (initialPosition < newPosition)
{
Logger.TraceFormat("Advancing bookmark from {0} to {1} on {2}", initialPosition, newPosition, currentFilePath);
bookmark.UpdatePosition(newPosition);
}
else if (initialPosition > newPosition)
{
newPosition = 0;
Logger.WarnFormat("File {2} has been truncated or re-created, bookmark reset from {0} to {1}", initialPosition, newPosition, currentFilePath);
bookmark.UpdatePosition(newPosition);
}
} while (records.Count >= _batchPostingLimit);
if (initialPosition == bookmark.Position)
{
Logger.TraceFormat("Found no records to process");
// Only advance the bookmark if there is next file in the queue
// and no other process has the current file locked, and its length is as we found it.
if (fileSet.Length > 1)
{
Logger.TraceFormat("BufferedFilesCount: {0}; checking if can advance to the next file", fileSet.Length);
var weAreAtEndOfTheFileAndItIsNotLockedByAnotherThread = WeAreAtEndOfTheFileAndItIsNotLockedByAnotherThread(currentFilePath, bookmark.Position);
if (weAreAtEndOfTheFileAndItIsNotLockedByAnotherThread)
{
Logger.TraceFormat("Advancing bookmark from '{0}' to '{1}'", currentFilePath, fileSet[1]);
bookmark.UpdateFileNameAndPosition(fileSet[1], 0);
}
else
{
break;
}
}
else
{
Logger.TraceFormat("This is a single log file, and we are in the end of it. Nothing to do.");
break;
}
}
} while (true);
}
private Tuple<long, List<TRecord>> ReadRecordBatch(string currentFilePath, long position, int maxRecords)
{
var records = new List<TRecord>(maxRecords);
long positionSent;
using (var reader = _logReaderFactory.Create(currentFilePath, position))
{
do
{
var stream = reader.ReadLine();
if (stream.Length == 0)
{
break;
}
records.Add(PrepareRecord(stream));
} while (records.Count < maxRecords);
positionSent = reader.Position;
}
return Tuple.Create(positionSent, records);
}
private bool TryDeleteFile(string fileToDelete)
{
try
{
_fileManager.LockAndDeleteFile(fileToDelete);
Logger.InfoFormat("Log file deleted: {0}", fileToDelete);
return true;
}
catch (Exception ex)
{
Logger.WarnException("Exception deleting file: {0}", ex, fileToDelete);
return false;
}
}
private bool WeAreAtEndOfTheFileAndItIsNotLockedByAnotherThread(string file, long nextLineBeginsAtOffset)
{
try
{
return _fileManager.GetFileLengthExclusiveAccess(file) <= nextLineBeginsAtOffset;
}
catch (IOException ex)
{
Logger.TraceException("Swallowed I/O exception while testing locked status of {0}", ex, file);
}
catch (Exception ex)
{
Logger.ErrorException("Unexpected exception while testing locked status of {0}", ex, file);
}
return false;
}
private string[] GetFileSet()
{
var fileSet = _fileManager.GetFiles(_logFolder, _candidateSearchPath)
.OrderBy(n => n, StringComparer.OrdinalIgnoreCase)
.ToArray();
Logger.TraceFormat("FileSet contains: {0}", string.Join(";", fileSet));
return fileSet;
}
private static int CompareFileNames(string fileName1, string fileName2)
{
return string.Compare(fileName1, fileName2, StringComparison.OrdinalIgnoreCase);
}
}
}
| |
// 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.Globalization
{
/// <summary>
/// JapaneseCalendar is based on Gregorian calendar. The month and day values are the same as
/// Gregorian calendar. However, the year value is an offset to the Gregorian
/// year based on the era.
///
/// This system is adopted by Emperor Meiji in 1868. The year value is counted based on the reign of an emperor,
/// and the era begins on the day an emperor ascends the throne and continues until his death.
/// The era changes at 12:00AM.
///
/// For example, the current era is Reiwa. It started on 2019/5/1 A.D. Therefore, Gregorian year 2019 is also Reiwa 1st.
/// 2019/5/1 A.D. is also Reiwa 1st 5/1.
///
/// Any date in the year during which era is changed can be reckoned in either era. For example,
/// 2019/1/1 can be 1/1 Reiwa 1st year or 1/1 Heisei 31st year.
///
/// Note:
/// The DateTime can be represented by the JapaneseCalendar are limited to two factors:
/// 1. The min value and max value of DateTime class.
/// 2. The available era information.
/// </summary>
/// <remarks>
/// Calendar support range:
/// Calendar Minimum Maximum
/// ========== ========== ==========
/// Gregorian 1868/09/08 9999/12/31
/// Japanese Meiji 01/01 Reiwa 7981/12/31
/// </remarks>
public partial class JapaneseCalendar : Calendar
{
private static readonly DateTime s_calendarMinValue = new DateTime(1868, 9, 8);
public override DateTime MinSupportedDateTime => s_calendarMinValue;
public override DateTime MaxSupportedDateTime => DateTime.MaxValue;
public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar;
// Using a field initializer rather than a static constructor so that the whole class can be lazy
// init.
private static volatile EraInfo[]? s_japaneseEraInfo;
// m_EraInfo must be listed in reverse chronological order. The most recent era
// should be the first element.
// That is, m_EraInfo[0] contains the most recent era.
//
// We know about 4 built-in eras, however users may add additional era(s) from the
// registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
// we don't read the registry and instead we call WinRT to get the needed informatio
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
internal static EraInfo[] GetEraInfo()
{
// See if we need to build it
return s_japaneseEraInfo ??
(s_japaneseEraInfo = GetJapaneseEras()) ??
// See if we have to use the built-in eras
(s_japaneseEraInfo = new EraInfo[]
{
new EraInfo(5, 2019, 5, 1, 2018, 1, GregorianCalendar.MaxYear - 2018, "\x4ee4\x548c", "\x4ee4", "R"),
new EraInfo(4, 1989, 1, 8, 1988, 1, 2019 - 1988, "\x5e73\x6210", "\x5e73", "H"),
new EraInfo(3, 1926, 12, 25, 1925, 1, 1989 - 1925, "\x662d\x548c", "\x662d", "S"),
new EraInfo(2, 1912, 7, 30, 1911, 1, 1926 - 1911, "\x5927\x6b63", "\x5927", "T"),
new EraInfo(1, 1868, 1, 1, 1867, 1, 1912 - 1867, "\x660e\x6cbb", "\x660e", "M")
});
}
internal static volatile Calendar? s_defaultInstance;
internal GregorianCalendarHelper _helper;
internal static Calendar GetDefaultInstance()
{
return s_defaultInstance ?? (s_defaultInstance = new JapaneseCalendar());
}
public JapaneseCalendar()
{
try
{
new CultureInfo("ja-JP");
}
catch (ArgumentException e)
{
throw new TypeInitializationException(this.GetType().ToString(), e);
}
_helper = new GregorianCalendarHelper(this, GetEraInfo());
}
internal override CalendarId ID => CalendarId.JAPAN;
public override DateTime AddMonths(DateTime time, int months)
{
return _helper.AddMonths(time, months);
}
public override DateTime AddYears(DateTime time, int years)
{
return _helper.AddYears(time, years);
}
public override int GetDaysInMonth(int year, int month, int era)
{
return _helper.GetDaysInMonth(year, month, era);
}
public override int GetDaysInYear(int year, int era)
{
return _helper.GetDaysInYear(year, era);
}
public override int GetDayOfMonth(DateTime time)
{
return _helper.GetDayOfMonth(time);
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return _helper.GetDayOfWeek(time);
}
public override int GetDayOfYear(DateTime time)
{
return _helper.GetDayOfYear(time);
}
public override int GetMonthsInYear(int year, int era)
{
return _helper.GetMonthsInYear(year, era);
}
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return _helper.GetWeekOfYear(time, rule, firstDayOfWeek);
}
public override int GetEra(DateTime time)
{
return _helper.GetEra(time);
}
public override int GetMonth(DateTime time)
{
return _helper.GetMonth(time);
}
public override int GetYear(DateTime time)
{
return _helper.GetYear(time);
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
return _helper.IsLeapDay(year, month, day, era);
}
public override bool IsLeapYear(int year, int era)
{
return _helper.IsLeapYear(year, era);
}
public override int GetLeapMonth(int year, int era)
{
return _helper.GetLeapMonth(year, era);
}
public override bool IsLeapMonth(int year, int month, int era)
{
return _helper.IsLeapMonth(year, month, era);
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
return _helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era);
}
/// <summary>
/// For Japanese calendar, four digit year is not used. Few emperors will live for more than one hundred years.
/// Therefore, for any two digit number, we just return the original number.
/// </summary>
public override int ToFourDigitYear(int year)
{
if (year <= 0)
{
throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedPosNum);
}
if (year > _helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
year,
SR.Format(SR.ArgumentOutOfRange_Range, 1, _helper.MaxYear));
}
return year;
}
public override int[] Eras => _helper.Eras;
/// <summary>
/// Return the various era strings
/// Note: The arrays are backwards of the eras
/// </summary>
internal static string[] EraNames()
{
EraInfo[] eras = GetEraInfo();
string[] eraNames = new string[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
eraNames[i] = eras[eras.Length - i - 1].eraName!;
}
return eraNames;
}
internal static string[] AbbrevEraNames()
{
EraInfo[] eras = GetEraInfo();
string[] erasAbbrev = new string[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
erasAbbrev[i] = eras[eras.Length - i - 1].abbrevEraName!;
}
return erasAbbrev;
}
internal static string[] EnglishEraNames()
{
EraInfo[] eras = GetEraInfo();
string[] erasEnglish = new string[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
erasEnglish[i] = eras[eras.Length - i - 1].englishEraName!;
}
return erasEnglish;
}
private const int DefaultTwoDigitYearMax = 99;
internal override bool IsValidYear(int year, int era)
{
return _helper.IsValidYear(year, era);
}
public override int TwoDigitYearMax
{
get
{
if (_twoDigitYearMax == -1)
{
_twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DefaultTwoDigitYearMax);
}
return _twoDigitYearMax;
}
set
{
VerifyWritable();
if (value < 99 || value > _helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.ArgumentOutOfRange_Range, 99, _helper.MaxYear));
}
_twoDigitYearMax = value;
}
}
}
}
| |
#if UNITY_EDITOR || !UNITY_FLASH
/// <summary>
/// This class handles receiving data from the Game Analytics servers.
/// JSON data is sent using a MD5 hashed authorization header, containing the JSON data and private key. Data received must be in JSON format also.
/// </summary>
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System;
//using LitJson;
public class GA_Request
{
/// <summary>
/// Handlers for success and fail regarding requests sent to the GA server
/// </summary>
public delegate void SubmitSuccessHandler(RequestType requestType, Hashtable returnParam, SubmitErrorHandler errorEvent);
public delegate void SubmitErrorHandler(string message);
/// <summary>
/// Types of requests that can be made to the GA server
/// </summary>
public enum RequestType { GA_GetHeatmapGameInfo, GA_GetHeatmapData }
/// <summary>
/// All the different types of requests
/// </summary>
public Dictionary<RequestType, string> Requests = new Dictionary<RequestType, string>()
{
{ RequestType.GA_GetHeatmapGameInfo, "game" },
{ RequestType.GA_GetHeatmapData, "heatmap" }
};
#region private values
private string _baseURL = "http://data-api.gameanalytics.com";
#endregion
#region public methods
public WWW RequestGameInfo(SubmitSuccessHandler successEvent, SubmitErrorHandler errorEvent)
{
if (string.IsNullOrEmpty(GA.SettingsGA.GameKey))
{
GA.LogWarning("Game key not set - please setup your Game key in GA_Settings, under the Basic tab");
return null;
}
if (string.IsNullOrEmpty(GA.SettingsGA.ApiKey))
{
GA.LogWarning("API key not set - please setup your API key in GA_Settings, under the Advanced tab");
return null;
}
string game_key = GA.SettingsGA.GameKey;
string requestInfo = "game_key=" + game_key + "&keys=area%7Cevent_id%7Cbuild";
requestInfo = requestInfo.Replace(" ", "%20");
//Get the url with the request type
string url = GetURL(Requests[RequestType.GA_GetHeatmapGameInfo]);
url += "/?" + requestInfo;
WWW www = null;
#if UNITY_FLASH
//Set the authorization header to contain an MD5 hash of the JSON array string + the private key
Hashtable headers = new Hashtable();
headers.Add("Authorization", GA_Submit.CreateMD5Hash(requestInfo + GA.SettingsGA.ApiKey));
//Try to send the data
www = new WWW(url, new byte[] { 0 }, headers);
#else
//Set the authorization header to contain an MD5 hash of the JSON array string + the private key
#if UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0
Hashtable headers = new Hashtable();
#else
Dictionary<string, string> headers = new Dictionary<string, string>();
#endif
headers.Add("Authorization", GA_Submit.CreateMD5Hash(requestInfo + GA.SettingsGA.ApiKey));
//Try to send the data
www = new WWW(url, new byte[] { 0 }, headers);
#endif
GA.RunCoroutine(Request(www, RequestType.GA_GetHeatmapGameInfo, successEvent, errorEvent),()=>www.isDone);
return www;
}
public WWW RequestHeatmapData(List<string> events, string area, string build, SubmitSuccessHandler successEvent, SubmitErrorHandler errorEvent)
{
return RequestHeatmapData(events, area, build, null, null, successEvent, errorEvent);
}
public WWW RequestHeatmapData(List<string> events, string area, string build, DateTime? startDate, DateTime? endDate, SubmitSuccessHandler successEvent, SubmitErrorHandler errorEvent)
{
string game_key = GA.SettingsGA.GameKey;
string event_ids = "";
for (int i = 0; i < events.Count; i++)
{
if (i == events.Count - 1)
event_ids += events[i];
else
event_ids += events[i] + "|";
}
string requestInfo = "game_key=" + game_key + "&event_ids=" + event_ids + "&area=" + area;
if (!build.Equals(""))
requestInfo += "&build=" + build;
requestInfo = requestInfo.Replace(" ", "%20");
if (startDate.HasValue && endDate.HasValue)
{
DateTime startDT = new DateTime(startDate.Value.Year, startDate.Value.Month, startDate.Value.Day, 0, 0, 0);
DateTime endDT = new DateTime(endDate.Value.Year, endDate.Value.Month, endDate.Value.Day, 0, 0, 0);
requestInfo += "&start_ts=" + DateTimeToUnixTimestamp(startDT) + "&end_ts=" + DateTimeToUnixTimestamp(endDT);
}
//Get the url with the request type
string url = GetURL(Requests[RequestType.GA_GetHeatmapData]);
url += "/?" + requestInfo;
WWW www = null;
#if UNITY_FLASH
//Set the authorization header to contain an MD5 hash of the JSON array string + the private key
Hashtable headers = new Hashtable();
headers.Add("Authorization", GA_Submit.CreateMD5Hash(requestInfo + GA.SettingsGA.ApiKey));
//Try to send the data
www = new WWW(url, new byte[] { 0 }, headers);
#else
//Set the authorization header to contain an MD5 hash of the JSON array string + the private key
#if UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0
Hashtable headers = new Hashtable();
#else
Dictionary<string, string> headers = new Dictionary<string, string>();
#endif
headers.Add("Authorization", GA_Submit.CreateMD5Hash(requestInfo + GA.SettingsGA.ApiKey));
//Try to send the data
www = new WWW(url, new byte[] { 0 }, headers);
#endif
GA.RunCoroutine(Request(www, RequestType.GA_GetHeatmapData, successEvent, errorEvent),()=>www.isDone);
return www;
}
public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
return (dateTime - new DateTime(1970, 1, 1)).TotalSeconds;
}
#endregion
#region private methods
private IEnumerator Request(WWW www, RequestType requestType, SubmitSuccessHandler successEvent, SubmitErrorHandler errorEvent)
{
yield return www;
GA.Log("GameAnalytics: URL " + www.url);
try
{
if (!string.IsNullOrEmpty(www.error))
{
throw new Exception(www.error);
}
//Get the JSON object from the response
string text = www.text;
text = text.Replace("null","0");
Hashtable returnParam = (Hashtable)GA_MiniJSON.JsonDecode(text);
if (returnParam != null)
{
GA.Log("GameAnalytics: Result: " + text);
if (successEvent != null)
{
successEvent(requestType, returnParam, errorEvent);
}
}
else
{
throw new Exception(text);
}
}
catch (Exception e)
{
if (errorEvent != null)
{
errorEvent(e.Message);
}
}
}
/// <summary>
/// Gets the url on the GA server matching the specific service we are interested in
/// </summary>
/// <param name="category">
/// Determines the GA service/category <see cref="System.String"/>
/// </param>
/// <returns>
/// A string representing the url matching our service choice on the GA server <see cref="System.String"/>
/// </returns>
private string GetURL(string category)
{
return _baseURL + "/" + category;
}
#endregion
}
#endif
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Login Event
///<para>SObject Name: LoginEvent</para>
///<para>Custom Object: False</para>
///</summary>
public class SfLoginEvent : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "LoginEvent"; }
}
///<summary>
/// Login Event ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Event Identifier
/// <para>Name: EventIdentifier</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "eventIdentifier")]
[Updateable(false), Createable(false)]
public string EventIdentifier { get; set; }
///<summary>
/// User ID
/// <para>Name: UserId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "userId")]
[Updateable(false), Createable(false)]
public string UserId { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: User</para>
///</summary>
[JsonProperty(PropertyName = "user")]
[Updateable(false), Createable(false)]
public SfUser User { get; set; }
///<summary>
/// Username
/// <para>Name: Username</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "username")]
[Updateable(false), Createable(false)]
public string Username { get; set; }
///<summary>
/// Event Date
/// <para>Name: EventDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "eventDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? EventDate { get; set; }
///<summary>
/// Related Event Identifier
/// <para>Name: RelatedEventIdentifier</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relatedEventIdentifier")]
[Updateable(false), Createable(false)]
public string RelatedEventIdentifier { get; set; }
///<summary>
/// Transaction Security Policy ID
/// <para>Name: PolicyId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "policyId")]
[Updateable(false), Createable(false)]
public string PolicyId { get; set; }
///<summary>
/// ReferenceTo: TransactionSecurityPolicy
/// <para>RelationshipName: Policy</para>
///</summary>
[JsonProperty(PropertyName = "policy")]
[Updateable(false), Createable(false)]
public SfTransactionSecurityPolicy Policy { get; set; }
///<summary>
/// Policy Outcome
/// <para>Name: PolicyOutcome</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "policyOutcome")]
[Updateable(false), Createable(false)]
public string PolicyOutcome { get; set; }
///<summary>
/// Evaluation Time
/// <para>Name: EvaluationTime</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "evaluationTime")]
[Updateable(false), Createable(false)]
public double? EvaluationTime { get; set; }
///<summary>
/// Session Key
/// <para>Name: SessionKey</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "sessionKey")]
[Updateable(false), Createable(false)]
public string SessionKey { get; set; }
///<summary>
/// Login Key
/// <para>Name: LoginKey</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "loginKey")]
[Updateable(false), Createable(false)]
public string LoginKey { get; set; }
///<summary>
/// Session Level
/// <para>Name: SessionLevel</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "sessionLevel")]
[Updateable(false), Createable(false)]
public string SessionLevel { get; set; }
///<summary>
/// Source IP
/// <para>Name: SourceIp</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "sourceIp")]
[Updateable(false), Createable(false)]
public string SourceIp { get; set; }
///<summary>
/// Additional Information
/// <para>Name: AdditionalInfo</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "additionalInfo")]
[Updateable(false), Createable(false)]
public string AdditionalInfo { get; set; }
///<summary>
/// API Type
/// <para>Name: ApiType</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "apiType")]
[Updateable(false), Createable(false)]
public string ApiType { get; set; }
///<summary>
/// API Version
/// <para>Name: ApiVersion</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "apiVersion")]
[Updateable(false), Createable(false)]
public string ApiVersion { get; set; }
///<summary>
/// Application
/// <para>Name: Application</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "application")]
[Updateable(false), Createable(false)]
public string Application { get; set; }
///<summary>
/// Authentication Service ID
/// <para>Name: AuthServiceId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "authServiceId")]
[Updateable(false), Createable(false)]
public string AuthServiceId { get; set; }
///<summary>
/// Browser
/// <para>Name: Browser</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "browser")]
[Updateable(false), Createable(false)]
public string Browser { get; set; }
///<summary>
/// HTTP Method
/// <para>Name: HttpMethod</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "httpMethod")]
[Updateable(false), Createable(false)]
public string HttpMethod { get; set; }
///<summary>
/// Country Code
/// <para>Name: CountryIso</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "countryIso")]
[Updateable(false), Createable(false)]
public string CountryIso { get; set; }
///<summary>
/// Latitude
/// <para>Name: LoginLatitude</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "loginLatitude")]
[Updateable(false), Createable(false)]
public double? LoginLatitude { get; set; }
///<summary>
/// Longitude
/// <para>Name: LoginLongitude</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "loginLongitude")]
[Updateable(false), Createable(false)]
public double? LoginLongitude { get; set; }
///<summary>
/// Country
/// <para>Name: Country</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "country")]
[Updateable(false), Createable(false)]
public string Country { get; set; }
///<summary>
/// City
/// <para>Name: City</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "city")]
[Updateable(false), Createable(false)]
public string City { get; set; }
///<summary>
/// PostalCode
/// <para>Name: PostalCode</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "postalCode")]
[Updateable(false), Createable(false)]
public string PostalCode { get; set; }
///<summary>
/// Subdivision
/// <para>Name: Subdivision</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "subdivision")]
[Updateable(false), Createable(false)]
public string Subdivision { get; set; }
///<summary>
/// TLS Cipher Suite
/// <para>Name: CipherSuite</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "cipherSuite")]
[Updateable(false), Createable(false)]
public string CipherSuite { get; set; }
///<summary>
/// Client Version
/// <para>Name: ClientVersion</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "clientVersion")]
[Updateable(false), Createable(false)]
public string ClientVersion { get; set; }
///<summary>
/// Login Geo Data ID
/// <para>Name: LoginGeoId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "loginGeoId")]
[Updateable(false), Createable(false)]
public string LoginGeoId { get; set; }
///<summary>
/// Login History ID
/// <para>Name: LoginHistoryId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "loginHistoryId")]
[Updateable(false), Createable(false)]
public string LoginHistoryId { get; set; }
///<summary>
/// Login Type
/// <para>Name: LoginType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "loginType")]
[Updateable(false), Createable(false)]
public string LoginType { get; set; }
///<summary>
/// Login URL
/// <para>Name: LoginUrl</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "loginUrl")]
[Updateable(false), Createable(false)]
public string LoginUrl { get; set; }
///<summary>
/// Platform
/// <para>Name: Platform</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "platform")]
[Updateable(false), Createable(false)]
public string Platform { get; set; }
///<summary>
/// Status
/// <para>Name: Status</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "status")]
[Updateable(false), Createable(false)]
public string Status { get; set; }
///<summary>
/// TLS Protocol
/// <para>Name: TlsProtocol</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "tlsProtocol")]
[Updateable(false), Createable(false)]
public string TlsProtocol { get; set; }
///<summary>
/// User Type
/// <para>Name: UserType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "userType")]
[Updateable(false), Createable(false)]
public string UserType { get; set; }
}
}
| |
// <copyright file="EventFiringWebDriver.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Support.Events
{
/// <summary>
/// A wrapper around an arbitrary WebDriver instance which supports registering for
/// events, e.g. for logging purposes.
/// </summary>
public class EventFiringWebDriver : IWebDriver, IJavaScriptExecutor, ITakesScreenshot, IWrapsDriver
{
private IWebDriver driver;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringWebDriver"/> class.
/// </summary>
/// <param name="parentDriver">The driver to register events for.</param>
public EventFiringWebDriver(IWebDriver parentDriver)
{
this.driver = parentDriver;
}
/// <summary>
/// Fires before the driver begins navigation.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> Navigating;
/// <summary>
/// Fires after the driver completes navigation
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> Navigated;
/// <summary>
/// Fires before the driver begins navigation back one entry in the browser history list.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> NavigatingBack;
/// <summary>
/// Fires after the driver completes navigation back one entry in the browser history list.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> NavigatedBack;
/// <summary>
/// Fires before the driver begins navigation forward one entry in the browser history list.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> NavigatingForward;
/// <summary>
/// Fires after the driver completes navigation forward one entry in the browser history list.
/// </summary>
public event EventHandler<WebDriverNavigationEventArgs> NavigatedForward;
/// <summary>
/// Fires before the driver clicks on an element.
/// </summary>
public event EventHandler<WebElementEventArgs> ElementClicking;
/// <summary>
/// Fires after the driver has clicked on an element.
/// </summary>
public event EventHandler<WebElementEventArgs> ElementClicked;
/// <summary>
/// Fires before the driver changes the value of an element via Clear(), SendKeys() or Toggle().
/// </summary>
public event EventHandler<WebElementValueEventArgs> ElementValueChanging;
/// <summary>
/// Fires after the driver has changed the value of an element via Clear(), SendKeys() or Toggle().
/// </summary>
public event EventHandler<WebElementValueEventArgs> ElementValueChanged;
/// <summary>
/// Fires before the driver starts to find an element.
/// </summary>
public event EventHandler<FindElementEventArgs> FindingElement;
/// <summary>
/// Fires after the driver completes finding an element.
/// </summary>
public event EventHandler<FindElementEventArgs> FindElementCompleted;
/// <summary>
/// Fires before a script is executed.
/// </summary>
public event EventHandler<WebDriverScriptEventArgs> ScriptExecuting;
/// <summary>
/// Fires after a script is executed.
/// </summary>
public event EventHandler<WebDriverScriptEventArgs> ScriptExecuted;
/// <summary>
/// Fires when an exception is thrown.
/// </summary>
public event EventHandler<WebDriverExceptionEventArgs> ExceptionThrown;
/// <summary>
/// Gets the <see cref="IWebDriver"/> wrapped by this EventsFiringWebDriver instance.
/// </summary>
public IWebDriver WrappedDriver
{
get { return this.driver; }
}
/// <summary>
/// Gets or sets the URL the browser is currently displaying.
/// </summary>
/// <remarks>
/// Setting the <see cref="Url"/> property will load a new web page in the current browser window.
/// This is done using an HTTP GET operation, and the method will block until the
/// load is complete. This will follow redirects issued either by the server or
/// as a meta-redirect from within the returned HTML. Should a meta-redirect "rest"
/// for any duration of time, it is best to wait until this timeout is over, since
/// should the underlying page change while your test is executing the results of
/// future calls against this interface will be against the freshly loaded page.
/// </remarks>
/// <seealso cref="INavigation.GoToUrl(string)"/>
/// <seealso cref="INavigation.GoToUrl(System.Uri)"/>
public string Url
{
get
{
string url = string.Empty;
try
{
url = this.driver.Url;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return url;
}
set
{
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.driver, value);
this.OnNavigating(e);
this.driver.Url = value;
this.OnNavigated(e);
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
}
}
/// <summary>
/// Gets the title of the current browser window.
/// </summary>
public string Title
{
get
{
string title = string.Empty;
try
{
title = this.driver.Title;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return title;
}
}
/// <summary>
/// Gets the source of the page last loaded by the browser.
/// </summary>
/// <remarks>
/// If the page has been modified after loading (for example, by JavaScript)
/// there is no guarantee that the returned text is that of the modified page.
/// Please consult the documentation of the particular driver being used to
/// determine whether the returned text reflects the current state of the page
/// or the text last sent by the web server. The page source returned is a
/// representation of the underlying DOM: do not expect it to be formatted
/// or escaped in the same way as the response sent from the web server.
/// </remarks>
public string PageSource
{
get
{
string source = string.Empty;
try
{
source = this.driver.PageSource;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return source;
}
}
/// <summary>
/// Gets the current window handle, which is an opaque handle to this
/// window that uniquely identifies it within this driver instance.
/// </summary>
public string CurrentWindowHandle
{
get
{
string handle = string.Empty;
try
{
handle = this.driver.CurrentWindowHandle;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return handle;
}
}
/// <summary>
/// Gets the window handles of open browser windows.
/// </summary>
public ReadOnlyCollection<string> WindowHandles
{
get
{
ReadOnlyCollection<string> handles = null;
try
{
handles = this.driver.WindowHandles;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return handles;
}
}
/// <summary>
/// Close the current window, quitting the browser if it is the last window currently open.
/// </summary>
public void Close()
{
try
{
this.driver.Close();
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
}
/// <summary>
/// Quits this driver, closing every associated window.
/// </summary>
public void Quit()
{
try
{
this.driver.Quit();
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
}
/// <summary>
/// Instructs the driver to change its settings.
/// </summary>
/// <returns>An <see cref="IOptions"/> object allowing the user to change
/// the settings of the driver.</returns>
public IOptions Manage()
{
return new EventFiringOptions(this);
}
/// <summary>
/// Instructs the driver to navigate the browser to another location.
/// </summary>
/// <returns>An <see cref="INavigation"/> object allowing the user to access
/// the browser's history and to navigate to a given URL.</returns>
public INavigation Navigate()
{
return new EventFiringNavigation(this);
}
/// <summary>
/// Instructs the driver to send future commands to a different frame or window.
/// </summary>
/// <returns>An <see cref="ITargetLocator"/> object which can be used to select
/// a frame or window.</returns>
public ITargetLocator SwitchTo()
{
return new EventFiringTargetLocator(this);
}
/// <summary>
/// Find the first <see cref="IWebElement"/> using the given method.
/// </summary>
/// <param name="by">The locating mechanism to use.</param>
/// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns>
/// <exception cref="NoSuchElementException">If no element matches the criteria.</exception>
public IWebElement FindElement(By by)
{
IWebElement wrappedElement = null;
try
{
FindElementEventArgs e = new FindElementEventArgs(this.driver, by);
this.OnFindingElement(e);
IWebElement element = this.driver.FindElement(by);
this.OnFindElementCompleted(e);
wrappedElement = this.WrapElement(element);
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return wrappedElement;
}
/// <summary>
/// Find all <see cref="IWebElement">IWebElements</see> within the current context
/// using the given mechanism.
/// </summary>
/// <param name="by">The locating mechanism to use.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see>
/// matching the current criteria, or an empty list if nothing matches.</returns>
public ReadOnlyCollection<IWebElement> FindElements(By by)
{
List<IWebElement> wrappedElementList = new List<IWebElement>();
try
{
FindElementEventArgs e = new FindElementEventArgs(this.driver, by);
this.OnFindingElement(e);
ReadOnlyCollection<IWebElement> elements = this.driver.FindElements(by);
this.OnFindElementCompleted(e);
foreach (IWebElement element in elements)
{
IWebElement wrappedElement = this.WrapElement(element);
wrappedElementList.Add(wrappedElement);
}
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return wrappedElementList.AsReadOnly();
}
/// <summary>
/// Frees all managed and unmanaged resources used by this instance.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Executes JavaScript in the context of the currently selected frame or window.
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="args">The arguments to the script.</param>
/// <returns>The value returned by the script.</returns>
/// <remarks>
/// <para>
/// The <see cref="ExecuteScript"/>method executes JavaScript in the context of
/// the currently selected frame or window. This means that "document" will refer
/// to the current document. If the script has a return value, then the following
/// steps will be taken:
/// </para>
/// <para>
/// <list type="bullet">
/// <item><description>For an HTML element, this method returns a <see cref="IWebElement"/></description></item>
/// <item><description>For a number, a <see cref="long"/> is returned</description></item>
/// <item><description>For a boolean, a <see cref="bool"/> is returned</description></item>
/// <item><description>For all other cases a <see cref="string"/> is returned.</description></item>
/// <item><description>For an array,we check the first element, and attempt to return a
/// <see cref="List{T}"/> of that type, following the rules above. Nested lists are not
/// supported.</description></item>
/// <item><description>If the value is null or there is no return value,
/// <see langword="null"/> is returned.</description></item>
/// </list>
/// </para>
/// <para>
/// Arguments must be a number (which will be converted to a <see cref="long"/>),
/// a <see cref="bool"/>, a <see cref="string"/> or a <see cref="IWebElement"/>.
/// An exception will be thrown if the arguments do not meet these criteria.
/// The arguments will be made available to the JavaScript via the "arguments" magic
/// variable, as if the function were called via "Function.apply"
/// </para>
/// </remarks>
public object ExecuteScript(string script, params object[] args)
{
IJavaScriptExecutor javascriptDriver = this.driver as IJavaScriptExecutor;
if (javascriptDriver == null)
{
throw new NotSupportedException("Underlying driver instance does not support executing JavaScript");
}
object scriptResult = null;
try
{
object[] unwrappedArgs = UnwrapElementArguments(args);
WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.driver, script);
this.OnScriptExecuting(e);
scriptResult = javascriptDriver.ExecuteScript(script, unwrappedArgs);
this.OnScriptExecuted(e);
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return scriptResult;
}
/// <summary>
/// Executes JavaScript asynchronously in the context of the currently selected frame or window.
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="args">The arguments to the script.</param>
/// <returns>The value returned by the script.</returns>
public object ExecuteAsyncScript(string script, params object[] args)
{
object scriptResult = null;
IJavaScriptExecutor javascriptDriver = this.driver as IJavaScriptExecutor;
if (javascriptDriver == null)
{
throw new NotSupportedException("Underlying driver instance does not support executing JavaScript");
}
try
{
object[] unwrappedArgs = UnwrapElementArguments(args);
WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.driver, script);
this.OnScriptExecuting(e);
scriptResult = javascriptDriver.ExecuteAsyncScript(script, unwrappedArgs);
this.OnScriptExecuted(e);
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.driver, ex));
throw;
}
return scriptResult;
}
/// <summary>
/// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen.
/// </summary>
/// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
public Screenshot GetScreenshot()
{
ITakesScreenshot screenshotDriver = this.driver as ITakesScreenshot;
if (this.driver == null)
{
throw new NotSupportedException("Underlying driver instance does not support taking screenshots");
}
Screenshot screen = null;
screen = screenshotDriver.GetScreenshot();
return screen;
}
/// <summary>
/// Frees all managed and, optionally, unmanaged resources used by this instance.
/// </summary>
/// <param name="disposing"><see langword="true"/> to dispose of only managed resources;
/// <see langword="false"/> to dispose of managed and unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.driver.Dispose();
}
}
/// <summary>
/// Raises the <see cref="Navigating"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigating(WebDriverNavigationEventArgs e)
{
if (this.Navigating != null)
{
this.Navigating(this, e);
}
}
/// <summary>
/// Raises the <see cref="Navigated"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigated(WebDriverNavigationEventArgs e)
{
if (this.Navigated != null)
{
this.Navigated(this, e);
}
}
/// <summary>
/// Raises the <see cref="NavigatingBack"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigatingBack(WebDriverNavigationEventArgs e)
{
if (this.NavigatingBack != null)
{
this.NavigatingBack(this, e);
}
}
/// <summary>
/// Raises the <see cref="NavigatedBack"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigatedBack(WebDriverNavigationEventArgs e)
{
if (this.NavigatedBack != null)
{
this.NavigatedBack(this, e);
}
}
/// <summary>
/// Raises the <see cref="NavigatingForward"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigatingForward(WebDriverNavigationEventArgs e)
{
if (this.NavigatingForward != null)
{
this.NavigatingForward(this, e);
}
}
/// <summary>
/// Raises the <see cref="NavigatedForward"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverNavigationEventArgs"/> that contains the event data.</param>
protected virtual void OnNavigatedForward(WebDriverNavigationEventArgs e)
{
if (this.NavigatedForward != null)
{
this.NavigatedForward(this, e);
}
}
/// <summary>
/// Raises the <see cref="ElementClicking"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementEventArgs"/> that contains the event data.</param>
protected virtual void OnElementClicking(WebElementEventArgs e)
{
if (this.ElementClicking != null)
{
this.ElementClicking(this, e);
}
}
/// <summary>
/// Raises the <see cref="ElementClicked"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementEventArgs"/> that contains the event data.</param>
protected virtual void OnElementClicked(WebElementEventArgs e)
{
if (this.ElementClicked != null)
{
this.ElementClicked(this, e);
}
}
/// <summary>
/// Raises the <see cref="ElementValueChanging"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementEventArgs"/> that contains the event data.</param>
[Obsolete("Use the new overload that takes a WebElementValueEventArgs argument")]
protected virtual void OnElementValueChanging(WebElementEventArgs e)
{
this.OnElementValueChanging(new WebElementValueEventArgs(e.Driver, e.Element, null));
}
/// <summary>
/// Raises the <see cref="ElementValueChanging"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementValueEventArgs"/> that contains the event data.</param>
protected virtual void OnElementValueChanging(WebElementValueEventArgs e)
{
if (this.ElementValueChanging != null)
{
this.ElementValueChanging(this, e);
}
}
/// <summary>
/// Raises the <see cref="ElementValueChanged"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementEventArgs"/> that contains the event data.</param>
[Obsolete("Use the new overload that takes a WebElementValueEventArgs argument")]
protected virtual void OnElementValueChanged(WebElementEventArgs e)
{
this.OnElementValueChanged(e);
}
/// <summary>
/// Raises the <see cref="ElementValueChanged"/> event.
/// </summary>
/// <param name="e">A <see cref="WebElementValueEventArgs"/> that contains the event data.</param>
protected virtual void OnElementValueChanged(WebElementValueEventArgs e)
{
if (this.ElementValueChanged != null)
{
this.ElementValueChanged(this, e);
}
}
/// <summary>
/// Raises the <see cref="FindingElement"/> event.
/// </summary>
/// <param name="e">A <see cref="FindElementEventArgs"/> that contains the event data.</param>
protected virtual void OnFindingElement(FindElementEventArgs e)
{
if (this.FindingElement != null)
{
this.FindingElement(this, e);
}
}
/// <summary>
/// Raises the <see cref="FindElementCompleted"/> event.
/// </summary>
/// <param name="e">A <see cref="FindElementEventArgs"/> that contains the event data.</param>
protected virtual void OnFindElementCompleted(FindElementEventArgs e)
{
if (this.FindElementCompleted != null)
{
this.FindElementCompleted(this, e);
}
}
/// <summary>
/// Raises the <see cref="ScriptExecuting"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverScriptEventArgs"/> that contains the event data.</param>
protected virtual void OnScriptExecuting(WebDriverScriptEventArgs e)
{
if (this.ScriptExecuting != null)
{
this.ScriptExecuting(this, e);
}
}
/// <summary>
/// Raises the <see cref="ScriptExecuted"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverScriptEventArgs"/> that contains the event data.</param>
protected virtual void OnScriptExecuted(WebDriverScriptEventArgs e)
{
if (this.ScriptExecuted != null)
{
this.ScriptExecuted(this, e);
}
}
/// <summary>
/// Raises the <see cref="ExceptionThrown"/> event.
/// </summary>
/// <param name="e">A <see cref="WebDriverExceptionEventArgs"/> that contains the event data.</param>
protected virtual void OnException(WebDriverExceptionEventArgs e)
{
if (this.ExceptionThrown != null)
{
this.ExceptionThrown(this, e);
}
}
private static object[] UnwrapElementArguments(object[] args)
{
// Walk the args: the various drivers expect unwrapped versions of the elements
List<object> unwrappedArgs = new List<object>();
foreach (object arg in args)
{
EventFiringWebElement eventElementArg = arg as EventFiringWebElement;
if (eventElementArg != null)
{
unwrappedArgs.Add(eventElementArg.WrappedElement);
}
else
{
unwrappedArgs.Add(arg);
}
}
return unwrappedArgs.ToArray();
}
private IWebElement WrapElement(IWebElement underlyingElement)
{
IWebElement wrappedElement = new EventFiringWebElement(this, underlyingElement);
return wrappedElement;
}
/// <summary>
/// Provides a mechanism for Navigating with the driver.
/// </summary>
private class EventFiringNavigation : INavigation
{
private EventFiringWebDriver parentDriver;
private INavigation wrappedNavigation;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringNavigation"/> class
/// </summary>
/// <param name="driver">Driver in use</param>
public EventFiringNavigation(EventFiringWebDriver driver)
{
this.parentDriver = driver;
this.wrappedNavigation = this.parentDriver.WrappedDriver.Navigate();
}
/// <summary>
/// Move the browser back
/// </summary>
public void Back()
{
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver);
this.parentDriver.OnNavigatingBack(e);
this.wrappedNavigation.Back();
this.parentDriver.OnNavigatedBack(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Move the browser forward
/// </summary>
public void Forward()
{
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver);
this.parentDriver.OnNavigatingForward(e);
this.wrappedNavigation.Forward();
this.parentDriver.OnNavigatedForward(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Navigate to a url for your test
/// </summary>
/// <param name="url">String of where you want the browser to go to</param>
public void GoToUrl(string url)
{
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver, url);
this.parentDriver.OnNavigating(e);
this.wrappedNavigation.GoToUrl(url);
this.parentDriver.OnNavigated(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Navigate to a url for your test
/// </summary>
/// <param name="url">Uri object of where you want the browser to go to</param>
public void GoToUrl(Uri url)
{
if (url == null)
{
throw new ArgumentNullException("url", "url cannot be null");
}
try
{
WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver, url.ToString());
this.parentDriver.OnNavigating(e);
this.wrappedNavigation.GoToUrl(url);
this.parentDriver.OnNavigated(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Refresh the browser
/// </summary>
public void Refresh()
{
try
{
this.wrappedNavigation.Refresh();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
}
/// <summary>
/// Provides a mechanism for setting options needed for the driver during the test.
/// </summary>
private class EventFiringOptions : IOptions
{
private IOptions wrappedOptions;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringOptions"/> class
/// </summary>
/// <param name="driver">Instance of the driver currently in use</param>
public EventFiringOptions(EventFiringWebDriver driver)
{
this.wrappedOptions = driver.WrappedDriver.Manage();
}
/// <summary>
/// Gets an object allowing the user to manipulate cookies on the page.
/// </summary>
public ICookieJar Cookies
{
get { return this.wrappedOptions.Cookies; }
}
/// <summary>
/// Gets an object allowing the user to manipulate the currently-focused browser window.
/// </summary>
/// <remarks>"Currently-focused" is defined as the browser window having the window handle
/// returned when IWebDriver.CurrentWindowHandle is called.</remarks>
public IWindow Window
{
get { return this.wrappedOptions.Window; }
}
public ILogs Logs
{
get { return this.wrappedOptions.Logs; }
}
/// <summary>
/// Provides access to the timeouts defined for this driver.
/// </summary>
/// <returns>An object implementing the <see cref="ITimeouts"/> interface.</returns>
public ITimeouts Timeouts()
{
return new EventFiringTimeouts(this.wrappedOptions);
}
}
/// <summary>
/// Provides a mechanism for finding elements on the page with locators.
/// </summary>
private class EventFiringTargetLocator : ITargetLocator
{
private ITargetLocator wrappedLocator;
private EventFiringWebDriver parentDriver;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringTargetLocator"/> class
/// </summary>
/// <param name="driver">The driver that is currently in use</param>
public EventFiringTargetLocator(EventFiringWebDriver driver)
{
this.parentDriver = driver;
this.wrappedLocator = this.parentDriver.WrappedDriver.SwitchTo();
}
/// <summary>
/// Move to a different frame using its index
/// </summary>
/// <param name="frameIndex">The index of the </param>
/// <returns>A WebDriver instance that is currently in use</returns>
public IWebDriver Frame(int frameIndex)
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.Frame(frameIndex);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Move to different frame using its name
/// </summary>
/// <param name="frameName">name of the frame</param>
/// <returns>A WebDriver instance that is currently in use</returns>
public IWebDriver Frame(string frameName)
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.Frame(frameName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Move to a frame element.
/// </summary>
/// <param name="frameElement">a previously found FRAME or IFRAME element.</param>
/// <returns>A WebDriver instance that is currently in use.</returns>
public IWebDriver Frame(IWebElement frameElement)
{
IWebDriver driver = null;
try
{
IWrapsElement wrapper = frameElement as IWrapsElement;
driver = this.wrappedLocator.Frame(wrapper.WrappedElement);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Select the parent frame of the currently selected frame.
/// </summary>
/// <returns>An <see cref="IWebDriver"/> instance focused on the specified frame.</returns>
public IWebDriver ParentFrame()
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.ParentFrame();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Change to the Window by passing in the name
/// </summary>
/// <param name="windowName">name of the window that you wish to move to</param>
/// <returns>A WebDriver instance that is currently in use</returns>
public IWebDriver Window(string windowName)
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.Window(windowName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Change the active frame to the default
/// </summary>
/// <returns>Element of the default</returns>
public IWebDriver DefaultContent()
{
IWebDriver driver = null;
try
{
driver = this.wrappedLocator.DefaultContent();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return driver;
}
/// <summary>
/// Finds the active element on the page and returns it
/// </summary>
/// <returns>Element that is active</returns>
public IWebElement ActiveElement()
{
IWebElement element = null;
try
{
element = this.wrappedLocator.ActiveElement();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return element;
}
/// <summary>
/// Switches to the currently active modal dialog for this particular driver instance.
/// </summary>
/// <returns>A handle to the dialog.</returns>
public IAlert Alert()
{
IAlert alert = null;
try
{
alert = this.wrappedLocator.Alert();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return alert;
}
}
/// <summary>
/// Defines the interface through which the user can define timeouts.
/// </summary>
private class EventFiringTimeouts : ITimeouts
{
private ITimeouts wrappedTimeouts;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringTimeouts"/> class
/// </summary>
/// <param name="options">The <see cref="IOptions"/> object to wrap.</param>
public EventFiringTimeouts(IOptions options)
{
this.wrappedTimeouts = options.Timeouts();
}
/// <summary>
/// Gets or sets the implicit wait timeout, which is the amount of time the
/// driver should wait when searching for an element if it is not immediately
/// present.
/// </summary>
/// <remarks>
/// When searching for a single element, the driver should poll the page
/// until the element has been found, or this timeout expires before throwing
/// a <see cref="NoSuchElementException"/>. When searching for multiple elements,
/// the driver should poll the page until at least one element has been found
/// or this timeout has expired.
/// <para>
/// Increasing the implicit wait timeout should be used judiciously as it
/// will have an adverse effect on test run time, especially when used with
/// slower location strategies like XPath.
/// </para>
/// </remarks>
public TimeSpan ImplicitWait
{
get { return this.wrappedTimeouts.ImplicitWait; }
set { this.wrappedTimeouts.ImplicitWait = value; }
}
/// <summary>
/// Gets or sets the asynchronous script timeout, which is the amount
/// of time the driver should wait when executing JavaScript asynchronously.
/// This timeout only affects the <see cref="IJavaScriptExecutor.ExecuteAsyncScript(string, object[])"/>
/// method.
/// </summary>
public TimeSpan AsynchronousJavaScript
{
get { return this.wrappedTimeouts.AsynchronousJavaScript; }
set { this.wrappedTimeouts.AsynchronousJavaScript = value; }
}
/// <summary>
/// Gets or sets the page load timeout, which is the amount of time the driver
/// should wait for a page to load when setting the <see cref="IWebDriver.Url"/>
/// property.
/// </summary>
public TimeSpan PageLoad
{
get { return this.wrappedTimeouts.PageLoad; }
set { this.wrappedTimeouts.PageLoad = value; }
}
}
/// <summary>
/// EventFiringWebElement allows you to have access to specific items that are found on the page
/// </summary>
private class EventFiringWebElement : IWebElement, IWrapsElement
{
private IWebElement underlyingElement;
private EventFiringWebDriver parentDriver;
/// <summary>
/// Initializes a new instance of the <see cref="EventFiringWebElement"/> class.
/// </summary>
/// <param name="driver">The <see cref="EventFiringWebDriver"/> instance hosting this element.</param>
/// <param name="element">The <see cref="IWebElement"/> to wrap for event firing.</param>
public EventFiringWebElement(EventFiringWebDriver driver, IWebElement element)
{
this.underlyingElement = element;
this.parentDriver = driver;
}
/// <summary>
/// Gets the underlying wrapped <see cref="IWebElement"/>.
/// </summary>
public IWebElement WrappedElement
{
get { return this.underlyingElement; }
}
/// <summary>
/// Gets the DOM Tag of element
/// </summary>
public string TagName
{
get
{
string tagName = string.Empty;
try
{
tagName = this.underlyingElement.TagName;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return tagName;
}
}
/// <summary>
/// Gets the text from the element
/// </summary>
public string Text
{
get
{
string text = string.Empty;
try
{
text = this.underlyingElement.Text;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return text;
}
}
/// <summary>
/// Gets a value indicating whether an element is currently enabled
/// </summary>
public bool Enabled
{
get
{
bool enabled = false;
try
{
enabled = this.underlyingElement.Enabled;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return enabled;
}
}
/// <summary>
/// Gets a value indicating whether this element is selected or not. This operation only applies to input elements such as checkboxes, options in a select and radio buttons.
/// </summary>
public bool Selected
{
get
{
bool selected = false;
try
{
selected = this.underlyingElement.Selected;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return selected;
}
}
/// <summary>
/// Gets the Location of an element and returns a Point object
/// </summary>
public Point Location
{
get
{
Point location = default(Point);
try
{
location = this.underlyingElement.Location;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return location;
}
}
/// <summary>
/// Gets the <see cref="Size"/> of the element on the page
/// </summary>
public Size Size
{
get
{
Size size = default(Size);
try
{
size = this.underlyingElement.Size;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return size;
}
}
/// <summary>
/// Gets a value indicating whether the element is currently being displayed
/// </summary>
public bool Displayed
{
get
{
bool displayed = false;
try
{
displayed = this.underlyingElement.Displayed;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return displayed;
}
}
/// <summary>
/// Gets the underlying EventFiringWebDriver for this element.
/// </summary>
protected EventFiringWebDriver ParentDriver
{
get { return this.parentDriver; }
}
/// <summary>
/// Method to clear the text out of an Input element
/// </summary>
public void Clear()
{
try
{
WebElementValueEventArgs e = new WebElementValueEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement, null);
this.parentDriver.OnElementValueChanging(e);
this.underlyingElement.Clear();
this.parentDriver.OnElementValueChanged(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Method for sending native key strokes to the browser
/// </summary>
/// <param name="text">String containing what you would like to type onto the screen</param>
public void SendKeys(string text)
{
try
{
WebElementValueEventArgs e = new WebElementValueEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement, text);
this.parentDriver.OnElementValueChanging(e);
this.underlyingElement.SendKeys(text);
this.parentDriver.OnElementValueChanged(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// If this current element is a form, or an element within a form, then this will be submitted to the remote server.
/// If this causes the current page to change, then this method will block until the new page is loaded.
/// </summary>
public void Submit()
{
try
{
this.underlyingElement.Submit();
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// Click this element. If this causes a new page to load, this method will block until
/// the page has loaded. At this point, you should discard all references to this element
/// and any further operations performed on this element will have undefined behavior unless
/// you know that the element and the page will still be present. If this element is not
/// clickable, then this operation is a no-op since it's pretty common for someone to
/// accidentally miss the target when clicking in Real Life
/// </summary>
public void Click()
{
try
{
WebElementEventArgs e = new WebElementEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement);
this.parentDriver.OnElementClicking(e);
this.underlyingElement.Click();
this.parentDriver.OnElementClicked(e);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
}
/// <summary>
/// If this current element is a form, or an element within a form, then this will be submitted to the remote server. If this causes the current page to change, then this method will block until the new page is loaded.
/// </summary>
/// <param name="attributeName">Attribute you wish to get details of</param>
/// <returns>The attribute's current value or null if the value is not set.</returns>
public string GetAttribute(string attributeName)
{
string attribute = string.Empty;
try
{
attribute = this.underlyingElement.GetAttribute(attributeName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return attribute;
}
/// <summary>
/// Gets the value of a JavaScript property of this element.
/// </summary>
/// <param name="propertyName">The name JavaScript the JavaScript property to get the value of.</param>
/// <returns>The JavaScript property's current value. Returns a <see langword="null"/> if the
/// value is not set or the property does not exist.</returns>
public string GetProperty(string propertyName)
{
string elementProperty = string.Empty;
try
{
elementProperty = this.underlyingElement.GetProperty(propertyName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return elementProperty;
}
/// <summary>
/// Method to return the value of a CSS Property
/// </summary>
/// <param name="propertyName">CSS property key</param>
/// <returns>string value of the CSS property</returns>
public string GetCssValue(string propertyName)
{
string cssValue = string.Empty;
try
{
cssValue = this.underlyingElement.GetCssValue(propertyName);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return cssValue;
}
/// <summary>
/// Finds the first element in the page that matches the <see cref="By"/> object
/// </summary>
/// <param name="by">By mechanism to find the element</param>
/// <returns>IWebElement object so that you can interaction that object</returns>
public IWebElement FindElement(By by)
{
IWebElement wrappedElement = null;
try
{
FindElementEventArgs e = new FindElementEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement, by);
this.parentDriver.OnFindingElement(e);
IWebElement element = this.underlyingElement.FindElement(by);
this.parentDriver.OnFindElementCompleted(e);
wrappedElement = this.parentDriver.WrapElement(element);
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return wrappedElement;
}
/// <summary>
/// Finds the elements on the page by using the <see cref="By"/> object and returns a ReadOnlyCollection of the Elements on the page
/// </summary>
/// <param name="by">By mechanism to find the element</param>
/// <returns>ReadOnlyCollection of IWebElement</returns>
public ReadOnlyCollection<IWebElement> FindElements(By by)
{
List<IWebElement> wrappedElementList = new List<IWebElement>();
try
{
FindElementEventArgs e = new FindElementEventArgs(this.parentDriver.WrappedDriver, this.underlyingElement, by);
this.parentDriver.OnFindingElement(e);
ReadOnlyCollection<IWebElement> elements = this.underlyingElement.FindElements(by);
this.parentDriver.OnFindElementCompleted(e);
foreach (IWebElement element in elements)
{
IWebElement wrappedElement = this.parentDriver.WrapElement(element);
wrappedElementList.Add(wrappedElement);
}
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
return wrappedElementList.AsReadOnly();
}
}
}
}
| |
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 MVCTaxonomyPickerWeb
{
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 registered for this add-in</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 add-in event
/// </summary>
/// <param name="properties">Properties of an add-in 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 registered for this add-in</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 registered for this add-in</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 add-in. 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 add-in 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 add-in 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 add-in 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 add-in.
/// </summary>
/// <returns>True if this is a high trust add-in.</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 add-in 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
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Lucene.Net.Index;
using IndexReader = Lucene.Net.Index.IndexReader;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
namespace Lucene.Net.Search
{
/// <summary> A query that applies a filter to the results of another query.
///
/// <p/>Note: the bits are retrieved from the filter each time this
/// query is used in a search - use a CachingWrapperFilter to avoid
/// regenerating the bits every time.
///
/// <p/>Created: Apr 20, 2004 8:58:29 AM
///
/// </summary>
/// <since>1.4</since>
/// <seealso cref="CachingWrapperFilter"/>
//[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300
public class FilteredQuery:Query
{
//[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300
private class AnonymousClassWeight:Weight
{
public AnonymousClassWeight(Lucene.Net.Search.Weight weight, Lucene.Net.Search.Similarity similarity, FilteredQuery enclosingInstance)
{
InitBlock(weight, similarity, enclosingInstance);
}
private class AnonymousClassScorer:Scorer
{
private void InitBlock(Lucene.Net.Search.Scorer scorer, Lucene.Net.Search.DocIdSetIterator docIdSetIterator, AnonymousClassWeight enclosingInstance)
{
this.scorer = scorer;
this.docIdSetIterator = docIdSetIterator;
this.enclosingInstance = enclosingInstance;
}
private Lucene.Net.Search.Scorer scorer;
private Lucene.Net.Search.DocIdSetIterator docIdSetIterator;
private AnonymousClassWeight enclosingInstance;
public AnonymousClassWeight Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal AnonymousClassScorer(Lucene.Net.Search.Scorer scorer, Lucene.Net.Search.DocIdSetIterator docIdSetIterator, AnonymousClassWeight enclosingInstance, Lucene.Net.Search.Similarity Param1):base(Param1)
{
InitBlock(scorer, docIdSetIterator, enclosingInstance);
}
private int doc = - 1;
private int AdvanceToCommon(int scorerDoc, int disiDoc)
{
while (scorerDoc != disiDoc)
{
if (scorerDoc < disiDoc)
{
scorerDoc = scorer.Advance(disiDoc);
}
else
{
disiDoc = docIdSetIterator.Advance(scorerDoc);
}
}
return scorerDoc;
}
public override int NextDoc()
{
int scorerDoc, disiDoc;
return doc = (disiDoc = docIdSetIterator.NextDoc()) != NO_MORE_DOCS && (scorerDoc = scorer.NextDoc()) != NO_MORE_DOCS && AdvanceToCommon(scorerDoc, disiDoc) != NO_MORE_DOCS?scorer.DocID():NO_MORE_DOCS;
}
public override int DocID()
{
return doc;
}
public override int Advance(int target)
{
int disiDoc, scorerDoc;
return doc = (disiDoc = docIdSetIterator.Advance(target)) != NO_MORE_DOCS && (scorerDoc = scorer.Advance(disiDoc)) != NO_MORE_DOCS && AdvanceToCommon(scorerDoc, disiDoc) != NO_MORE_DOCS?scorer.DocID():NO_MORE_DOCS;
}
public override float Score()
{
return Enclosing_Instance.Enclosing_Instance.Boost * scorer.Score();
}
}
private void InitBlock(Lucene.Net.Search.Weight weight, Lucene.Net.Search.Similarity similarity, FilteredQuery enclosingInstance)
{
this.weight = weight;
this.similarity = similarity;
this.enclosingInstance = enclosingInstance;
}
private Lucene.Net.Search.Weight weight;
private Lucene.Net.Search.Similarity similarity;
private FilteredQuery enclosingInstance;
public FilteredQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private float value_Renamed;
// pass these methods through to enclosed query's weight
public override float Value
{
get { return value_Renamed; }
}
public override float GetSumOfSquaredWeights()
{
return weight.GetSumOfSquaredWeights()*Enclosing_Instance.Boost*Enclosing_Instance.Boost;
}
public override void Normalize(float v)
{
weight.Normalize(v);
value_Renamed = weight.Value * Enclosing_Instance.Boost;
}
public override Explanation Explain(IndexReader ir, int i)
{
Explanation inner = weight.Explain(ir, i);
if (Enclosing_Instance.Boost != 1)
{
Explanation preBoost = inner;
inner = new Explanation(inner.Value * Enclosing_Instance.Boost, "product of:");
inner.AddDetail(new Explanation(Enclosing_Instance.Boost, "boost"));
inner.AddDetail(preBoost);
}
Filter f = Enclosing_Instance.filter;
DocIdSet docIdSet = f.GetDocIdSet(ir);
DocIdSetIterator docIdSetIterator = docIdSet == null?DocIdSet.EMPTY_DOCIDSET.Iterator():docIdSet.Iterator();
if (docIdSetIterator == null)
{
docIdSetIterator = DocIdSet.EMPTY_DOCIDSET.Iterator();
}
if (docIdSetIterator.Advance(i) == i)
{
return inner;
}
else
{
Explanation result = new Explanation(0.0f, "failure to match filter: " + f.ToString());
result.AddDetail(inner);
return result;
}
}
// return this query
public override Query Query
{
get { return Enclosing_Instance; }
}
// return a filtering scorer
public override Scorer Scorer(IndexReader indexReader, bool scoreDocsInOrder, bool topScorer)
{
Scorer scorer = weight.Scorer(indexReader, true, false);
if (scorer == null)
{
return null;
}
DocIdSet docIdSet = Enclosing_Instance.filter.GetDocIdSet(indexReader);
if (docIdSet == null)
{
return null;
}
DocIdSetIterator docIdSetIterator = docIdSet.Iterator();
if (docIdSetIterator == null)
{
return null;
}
return new AnonymousClassScorer(scorer, docIdSetIterator, this, similarity);
}
}
internal Query query;
internal Filter filter;
/// <summary> Constructs a new query which applies a filter to the results of the original query.
/// Filter.getDocIdSet() will be called every time this query is used in a search.
/// </summary>
/// <param name="query"> Query to be filtered, cannot be <c>null</c>.
/// </param>
/// <param name="filter">Filter to apply to query results, cannot be <c>null</c>.
/// </param>
public FilteredQuery(Query query, Filter filter)
{
this.query = query;
this.filter = filter;
}
/// <summary> Returns a Weight that applies the filter to the enclosed query's Weight.
/// This is accomplished by overriding the Scorer returned by the Weight.
/// </summary>
public override Weight CreateWeight(Searcher searcher)
{
Weight weight = query.CreateWeight(searcher);
Similarity similarity = query.GetSimilarity(searcher);
return new AnonymousClassWeight(weight, similarity, this);
}
/// <summary>Rewrites the wrapped query. </summary>
public override Query Rewrite(IndexReader reader)
{
Query rewritten = query.Rewrite(reader);
if (rewritten != query)
{
FilteredQuery clone = (FilteredQuery) this.Clone();
clone.query = rewritten;
return clone;
}
else
{
return this;
}
}
public virtual Query Query
{
get { return query; }
}
public virtual Filter Filter
{
get { return filter; }
}
// inherit javadoc
public override void ExtractTerms(System.Collections.Generic.ISet<Term> terms)
{
Query.ExtractTerms(terms);
}
/// <summary>Prints a user-readable version of this query. </summary>
public override System.String ToString(System.String s)
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
buffer.Append("filtered(");
buffer.Append(query.ToString(s));
buffer.Append(")->");
buffer.Append(filter);
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
/// <summary>Returns true iff <c>o</c> is equal to this. </summary>
public override bool Equals(System.Object o)
{
if (o is FilteredQuery)
{
FilteredQuery fq = (FilteredQuery) o;
return (query.Equals(fq.query) && filter.Equals(fq.filter) && Boost == fq.Boost);
}
return false;
}
/// <summary>Returns a hash code value for this object. </summary>
public override int GetHashCode()
{
return query.GetHashCode() ^ filter.GetHashCode() + System.Convert.ToInt32(Boost);
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Internal.FileAppenders
{
using System;
using System.IO;
using System.Threading;
/// <summary>
/// Maintains a collection of file appenders usually associated with file targets.
/// </summary>
internal sealed class FileAppenderCache
{
private BaseFileAppender[] appenders;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
private string archiveFilePatternToWatch = null;
private readonly MultiFileWatcher externalFileArchivingWatcher = new MultiFileWatcher(NotifyFilters.FileName);
private bool logFileWasArchived = false;
#endif
/// <summary>
/// An "empty" instance of the <see cref="FileAppenderCache"/> class with zero size and empty list of appenders.
/// </summary>
public static readonly FileAppenderCache Empty = new FileAppenderCache();
/// <summary>
/// Initializes a new "empty" instance of the <see cref="FileAppenderCache"/> class with zero size and empty
/// list of appenders.
/// </summary>
private FileAppenderCache() : this(0, null, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="FileAppenderCache"/> class.
/// </summary>
/// <remarks>
/// The size of the list should be positive. No validations are performed during initialisation as it is an
/// intenal class.
/// </remarks>
/// <param name="size">Total number of appenders allowed in list.</param>
/// <param name="appenderFactory">Factory used to create each appender.</param>
/// <param name="createFileParams">Parameters used for creating a file.</param>
public FileAppenderCache(int size, IFileAppenderFactory appenderFactory, ICreateFileParameters createFileParams)
{
Size = size;
Factory = appenderFactory;
CreateFileParameters = createFileParams;
appenders = new BaseFileAppender[Size];
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
externalFileArchivingWatcher.OnChange += ExternalFileArchivingWatcher_OnChange;
#endif
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
private void ExternalFileArchivingWatcher_OnChange(object sender, FileSystemEventArgs e)
{
if ((e.ChangeType & WatcherChangeTypes.Created) == WatcherChangeTypes.Created)
logFileWasArchived = true;
}
/// <summary>
/// The archive file path pattern that is used to detect when archiving occurs.
/// </summary>
public string ArchiveFilePatternToWatch
{
get { return archiveFilePatternToWatch; }
set
{
if (archiveFilePatternToWatch != value)
{
archiveFilePatternToWatch = value;
logFileWasArchived = false;
externalFileArchivingWatcher.StopWatching();
}
}
}
/// <summary>
/// Invalidates appenders for all files that were archived.
/// </summary>
public void InvalidateAppendersForInvalidFiles()
{
if (logFileWasArchived)
{
CloseAppenders();
logFileWasArchived = false;
}
}
#endif
/// <summary>
/// Gets the parameters which will be used for creating a file.
/// </summary>
public ICreateFileParameters CreateFileParameters { get; private set; }
/// <summary>
/// Gets the file appender factory used by all the appenders in this list.
/// </summary>
public IFileAppenderFactory Factory { get; private set; }
/// <summary>
/// Gets the number of appenders which the list can hold.
/// </summary>
public int Size { get; private set; }
/// <summary>
/// It allocates the first slot in the list when the file name does not already in the list and clean up any
/// unused slots.
/// </summary>
/// <param name="fileName">File name associated with a single appender.</param>
/// <returns>The allocated appender.</returns>
/// <exception cref="NullReferenceException">
/// Thrown when <see cref="M:AllocateAppender"/> is called on an <c>Empty</c><see cref="FileAppenderCache"/> instance.
/// </exception>
public BaseFileAppender AllocateAppender(string fileName)
{
//
// BaseFileAppender.Write is the most expensive operation here
// so the in-memory data structure doesn't have to be
// very sophisticated. It's a table-based LRU, where we move
// the used element to become the first one.
// The number of items is usually very limited so the
// performance should be equivalent to the one of the hashtable.
//
BaseFileAppender appenderToWrite = null;
int freeSpot = appenders.Length - 1;
for (int i = 0; i < appenders.Length; ++i)
{
// Use empty slot in recent appender list, if there is one.
if (appenders[i] == null)
{
freeSpot = i;
break;
}
if (appenders[i].FileName == fileName)
{
// found it, move it to the first place on the list
// (MRU)
// file open has a chance of failure
// if it fails in the constructor, we won't modify any data structures
BaseFileAppender app = appenders[i];
for (int j = i; j > 0; --j)
{
appenders[j] = appenders[j - 1];
}
appenders[0] = app;
appenderToWrite = app;
break;
}
}
if (appenderToWrite == null)
{
BaseFileAppender newAppender = Factory.Open(fileName, CreateFileParameters);
if (appenders[freeSpot] != null)
{
CloseAppender(appenders[freeSpot]);
appenders[freeSpot] = null;
}
for (int j = freeSpot; j > 0; --j)
{
appenders[j] = appenders[j - 1];
}
appenders[0] = newAppender;
appenderToWrite = newAppender;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
if (!string.IsNullOrEmpty(archiveFilePatternToWatch))
{
string directoryPath = Path.GetDirectoryName(archiveFilePatternToWatch);
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
externalFileArchivingWatcher.Watch(archiveFilePatternToWatch);
}
#endif
}
return appenderToWrite;
}
/// <summary>
/// Close all the allocated appenders.
/// </summary>
public void CloseAppenders()
{
if (appenders != null)
{
for (int i = 0; i < appenders.Length; ++i)
{
if (appenders[i] == null)
{
break;
}
CloseAppender(appenders[i]);
appenders[i] = null;
}
}
}
/// <summary>
/// Close the allocated appenders initialised before the supplied time.
/// </summary>
/// <param name="expireTime">The time which prior the appenders considered expired</param>
public void CloseAppenders(DateTime expireTime)
{
for (int i = 0; i < this.appenders.Length; ++i)
{
if (this.appenders[i] == null)
{
break;
}
if (this.appenders[i].OpenTime < expireTime)
{
for (int j = i; j < this.appenders.Length; ++j)
{
if (this.appenders[j] == null)
{
break;
}
CloseAppender(this.appenders[j]);
this.appenders[j] = null;
}
break;
}
}
}
/// <summary>
/// Fluch all the allocated appenders.
/// </summary>
public void FlushAppenders()
{
foreach (BaseFileAppender appender in appenders)
{
if (appender == null)
{
break;
}
appender.Flush();
}
}
private BaseFileAppender GetAppender(string fileName)
{
foreach (BaseFileAppender appender in appenders)
{
if (appender == null)
break;
if (appender.FileName == fileName)
return appender;
}
return null;
}
public DateTime? GetFileCreationTimeUtc(string filePath, bool fallback)
{
var appender = GetAppender(filePath);
DateTime? result = null;
if (appender != null)
result = appender.GetFileCreationTimeUtc();
if (result == null && fallback)
{
var fileInfo = new FileInfo(filePath);
if (fileInfo.Exists)
{
return fileInfo.GetCreationTimeUtc();
}
}
return result;
}
public DateTime? GetFileLastWriteTimeUtc(string filePath, bool fallback)
{
var appender = GetAppender(filePath);
DateTime? result = null;
if (appender != null)
result = appender.GetFileLastWriteTimeUtc();
if (result == null && fallback)
{
var fileInfo = new FileInfo(filePath);
if (fileInfo.Exists)
{
return fileInfo.GetLastWriteTimeUtc();
}
}
return result;
}
public long? GetFileLength(string filePath, bool fallback)
{
var appender = GetAppender(filePath);
long? result = null;
if (appender != null)
result = appender.GetFileLength();
if (result == null && fallback)
{
var fileInfo = new FileInfo(filePath);
if (fileInfo.Exists)
{
return fileInfo.Length;
}
}
return result;
}
/// <summary>
/// Closes the specified appender and removes it from the list.
/// </summary>
/// <param name="filePath">File name of the appender to be closed.</param>
public void InvalidateAppender(string filePath)
{
for (int i = 0; i < appenders.Length; ++i)
{
if (appenders[i] == null)
{
break;
}
if (appenders[i].FileName == filePath)
{
CloseAppender(appenders[i]);
for (int j = i; j < appenders.Length - 1; ++j)
{
appenders[j] = appenders[j + 1];
}
appenders[appenders.Length - 1] = null;
break;
}
}
}
private void CloseAppender(BaseFileAppender appender)
{
appender.Close();
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
externalFileArchivingWatcher.StopWatching();
#endif
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using log4net;
using MindTouch.Collections;
using MindTouch.Tasking;
namespace MindTouch.Threading {
/// <summary>
/// ElasticThreadPool provides a thread pool that can have a variable number of threads going from a minimum number of reserved threads
/// to a maximum number of parallel threads.
/// </summary>
/// <remarks>
/// The threads are obtained from the DispatchThreadScheduler and shared across all other clients of the DispatchThreadScheduler.
/// Obtained threads are released automatically if the thread pool is idle for long enough. Reserved threads are never released.
/// </remarks>
public class ElasticThreadPool : IDispatchHost, IDispatchQueue, IDisposable {
//--- Constants ---
/// <summary>
/// Maximum number of threads that can be reserved by a single instance.
/// </summary>
public const int MAX_RESERVED_THREADS = 1000;
//--- Class Fields ---
private static int _instanceCounter;
private static readonly ILog _log = LogUtils.CreateLog();
//--- Fields ---
private readonly object _syncRoot = new object();
private readonly int _id = Interlocked.Increment(ref _instanceCounter);
private readonly IThreadsafeQueue<Action> _inbox = new LockFreeQueue<Action>();
private readonly IThreadsafeStack<KeyValuePair<DispatchThread, Result<DispatchWorkItem>>> _reservedThreads = new LockFreeStack<KeyValuePair<DispatchThread, Result<DispatchWorkItem>>>();
private readonly int _minReservedThreads;
private readonly int _maxParallelThreads;
private int _threadCount;
private int _threadVelocity;
private DispatchThread[] _activeThreads;
private bool _disposed;
//--- Constructors ---
/// <summary>
/// Creates a new ElasticThreadPool instance.
/// </summary>
/// <param name="minReservedThreads">Minium number of threads to reserve for the thread pool.</param>
/// <param name="maxParallelThreads">Maximum number of parallel threads used by the thread pool.</param>
/// <exception cref="InsufficientResourcesException">The ElasticThreadPool instance was unable to obtain the minimum reserved threads.</exception>
public ElasticThreadPool(int minReservedThreads, int maxParallelThreads) {
_minReservedThreads = Math.Max(0, Math.Min(minReservedThreads, MAX_RESERVED_THREADS));
_maxParallelThreads = Math.Max(Math.Max(1, minReservedThreads), Math.Min(maxParallelThreads, int.MaxValue));
// initialize reserved threads
_activeThreads = new DispatchThread[Math.Min(_maxParallelThreads, Math.Max(_minReservedThreads, Math.Min(16, _maxParallelThreads)))];
if(_minReservedThreads > 0) {
DispatchThreadScheduler.RequestThread(_minReservedThreads, AddThread);
}
DispatchThreadScheduler.RegisterHost(this);
_log.DebugFormat("Create @{0}", this);
}
//--- Properties ---
/// <summary>
/// Number of minimum reserved threads.
/// </summary>
public int MinReservedThreads { get { return _disposed ? 0 : _minReservedThreads; } }
/// <summary>
/// Number of maxium parallel threads.
/// </summary>
public int MaxParallelThreads { get { return _maxParallelThreads; } }
/// <summary>
/// Number of threads currently used.
/// </summary>
public int ThreadCount { get { return _threadCount; } }
/// <summary>
/// Number of items pending for execution.
/// </summary>
public int WorkItemCount {
get {
int result = _inbox.Count;
DispatchThread[] threads = _activeThreads;
foreach(DispatchThread thread in threads) {
if(thread != null) {
result += thread.PendingWorkItemCount;
}
}
return result;
}
}
//--- Methods ---
/// <summary>
/// Adds an item to the thread pool.
/// </summary>
/// <param name="callback">Item to add to the thread pool.</param>
public void QueueWorkItem(Action callback) {
if(!TryQueueWorkItem(callback)) {
throw new NotSupportedException("TryQueueWorkItem failed");
}
}
/// <summary>
/// Adds an item to the thread pool.
/// </summary>
/// <param name="callback">Item to add to the thread pool.</param>
/// <returns>Always returns true.</returns>
public bool TryQueueWorkItem(Action callback) {
if(_disposed) {
throw new ObjectDisposedException("ElasticThreadPool has already been disposed");
}
// check if we can enqueue work-item into current dispatch thread
if(DispatchThread.TryQueueWorkItem(this, callback)) {
return true;
}
// check if there are available threads to which the work-item can be given to
KeyValuePair<DispatchThread, Result<DispatchWorkItem>> entry;
if(_reservedThreads.TryPop(out entry)) {
lock(_syncRoot) {
RegisterThread("new item", entry.Key);
}
// found an available thread, let's resume it with the work-item
entry.Value.Return(new DispatchWorkItem(callback, this));
return true;
}
// no threads available, keep work-item for later
if(!_inbox.TryEnqueue(callback)) {
return false;
}
// check if we need to request a thread to kick things off
if(ThreadCount == 0) {
((IDispatchHost)this).IncreaseThreadCount("request first thread");
}
return true;
}
/// <summary>
/// Shutdown the ElasticThreadPool instance. This method blocks until all pending items have finished processing.
/// </summary>
public void Dispose() {
if(!_disposed) {
_disposed = true;
_log.DebugFormat("Dispose @{0}", this);
// TODO (steveb): make dispose more reliable
// 1) we can't wait indefinitively!
// 2) we should progressively sleep longer and longer to avoid unnecessary overhead
// 3) this pattern feels useful enough to be captured into a helper method
// wait until all threads have been decommissioned
while(ThreadCount > 0) {
Thread.Sleep(100);
}
// discard all reserved threads
KeyValuePair<DispatchThread, Result<DispatchWorkItem>> reserved;
while(_reservedThreads.TryPop(out reserved)) {
DispatchThreadScheduler.ReleaseThread(reserved.Key, reserved.Value);
}
DispatchThreadScheduler.UnregisterHost(this);
}
}
/// <summary>
/// Convert the dispatch queue into a string.
/// </summary>
/// <returns>String.</returns>
public override string ToString() {
return string.Format("ElasticThreadPool @{0} (current: {1}, reserve: {5}, velocity: {2}, min: {3}, max: {4}, items: {6})", _id, _threadCount, _threadVelocity, _minReservedThreads, _maxParallelThreads, _reservedThreads.Count, WorkItemCount);
}
private void AddThread(KeyValuePair<DispatchThread, Result<DispatchWorkItem>> keyvalue) {
DispatchThread thread = keyvalue.Key;
Result<DispatchWorkItem> result = keyvalue.Value;
if(_threadVelocity >= 0) {
lock(_syncRoot) {
_threadVelocity = 0;
// check if an item is available for dispatch
Action callback;
if(TryRequestItem(null, out callback)) {
RegisterThread("new thread", thread);
// dispatch work-item
result.Return(new DispatchWorkItem(callback, this));
return;
}
}
}
// we have no need for this thread
RemoveThread("insufficient work for new thread", thread, result);
}
private void RemoveThread(string reason, DispatchThread thread, Result<DispatchWorkItem> result) {
if(thread == null) {
throw new ArgumentNullException("thread");
}
if(result == null) {
throw new ArgumentNullException("result");
}
if(thread.PendingWorkItemCount != 0) {
throw new ArgumentException(string.Format("thread #{1} still has work-items in queue (items: {0})", thread.PendingWorkItemCount, thread.Id), "thread");
}
// remove thread from list of allocated threads
lock(_syncRoot) {
_threadVelocity = 0;
UnregisterThread(reason, thread);
}
// check if we can put thread into the reserved list
if(_reservedThreads.Count < MinReservedThreads) {
if(!_reservedThreads.TryPush(new KeyValuePair<DispatchThread, Result<DispatchWorkItem>>(thread, result))) {
throw new NotSupportedException("TryPush failed");
}
} else {
// return thread to resource manager
DispatchThreadScheduler.ReleaseThread(thread, result);
}
}
private bool TryRequestItem(DispatchThread thread, out Action callback) {
// check if we can find a work-item in the shared queue
if(_inbox.TryDequeue(out callback)) {
return true;
}
// try to steal a work-item from another thread; take a snapshot of all allocated threads (needed in case the array is copied for resizing)
DispatchThread[] threads = _activeThreads;
foreach(DispatchThread entry in threads) {
// check if we can steal a work-item from this thread
if((entry != null) && !ReferenceEquals(entry, thread) && entry.TryStealWorkItem(out callback)) {
return true;
}
}
// check again if we can find a work-item in the shared queue since trying to steal may have overlapped with the arrival of a new item
if(_inbox.TryDequeue(out callback)) {
return true;
}
return false;
}
private void RegisterThread(string reason, DispatchThread thread) {
++_threadCount;
thread.Host = this;
// find an empty slot in the array of all threads
int index;
for(index = 0; index < _activeThreads.Length; ++index) {
// check if we found an empty slot
if(_activeThreads[index] == null) {
// assign it to the found slot and stop iterating
_activeThreads[index] = thread;
break;
}
}
// check if we need to grow the array
if(index == _activeThreads.Length) {
// make room to add a new thread by doubling the array size and copying over the existing entries
DispatchThread[] newArray = new DispatchThread[2 * _activeThreads.Length];
Array.Copy(_activeThreads, newArray, _activeThreads.Length);
// assign new thread
newArray[index] = thread;
// update instance field
_activeThreads = newArray;
}
#if EXTRA_DEBUG
_log.DebugFormat("AddThread: {1} - {0}", this, reason);
#endif
}
private void UnregisterThread(string reason, DispatchThread thread) {
thread.Host = null;
// find thread and remove it
for(int i = 0; i < _activeThreads.Length; ++i) {
if(ReferenceEquals(_activeThreads[i], thread)) {
--_threadCount;
_activeThreads[i] = null;
#if EXTRA_DEBUG
_log.DebugFormat("RemoveThread: {1} - {0}", this, reason);
#endif
break;
}
}
}
//--- IDispatchHost Members ---
long IDispatchHost.PendingWorkItemCount { get { return WorkItemCount; } }
int IDispatchHost.MinThreadCount { get { return MinReservedThreads; } }
int IDispatchHost.MaxThreadCount { get { return _maxParallelThreads; } }
void IDispatchHost.RequestWorkItem(DispatchThread thread, Result<DispatchWorkItem> result) {
if(thread == null) {
throw new ArgumentNullException("thread");
}
if(thread.PendingWorkItemCount > 0) {
throw new ArgumentException(string.Format("thread #{1} still has work-items in queue (items: {0})", thread.PendingWorkItemCount, thread.Id), "thread");
}
if(!ReferenceEquals(thread.Host, this)) {
throw new InvalidOperationException(string.Format("thread is allocated to another queue: received {0}, expected: {1}", thread.Host, this));
}
if(result == null) {
throw new ArgumentNullException("result");
}
Action callback;
// check if we need to decommission threads without causing starvation
if(_threadVelocity < 0) {
RemoveThread("system saturation", thread, result);
return;
}
// check if we found a work-item
if(TryRequestItem(thread, out callback)) {
// dispatch work-item
result.Return(new DispatchWorkItem(callback, this));
} else {
// relinquich thread; it's not required anymore
RemoveThread("insufficient work", thread, result);
}
}
void IDispatchHost.IncreaseThreadCount(string reason) {
// check if thread pool is already awaiting another thread
if(_threadVelocity > 0) {
return;
}
lock(_syncRoot) {
_threadVelocity = 1;
// check if thread pool has enough threads
if(_threadCount >= _maxParallelThreads) {
_threadVelocity = 0;
return;
}
#if EXTRA_DEBUG
_log.DebugFormat("IncreaseThreadCount: {1} - {0}", this, reason);
#endif
}
// check if there are threads in the reserve
KeyValuePair<DispatchThread, Result<DispatchWorkItem>> reservedThread;
if(_reservedThreads.TryPop(out reservedThread)) {
AddThread(reservedThread);
} else {
DispatchThreadScheduler.RequestThread(0, AddThread);
}
}
void IDispatchHost.MaintainThreadCount(string reason) {
// check if thread pool is already trying to steady
if(_threadVelocity == 0) {
return;
}
lock(_syncRoot) {
_threadVelocity = 0;
#if EXTRA_DEBUG
_log.DebugFormat("MaintainThreadCount: {1} - {0}", this, reason);
#endif
}
}
void IDispatchHost.DecreaseThreadCount(string reason) {
// check if thread pool is already trying to discard thread
if(_threadVelocity < 0) {
return;
}
lock(_syncRoot) {
_threadVelocity = -1;
#if EXTRA_DEBUG
_log.DebugFormat("DecreaseThreadCount: {1} - {0}", this, reason);
#endif
}
}
}
}
| |
using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using Moscrif.IDE.Iface.Entities;
using System.Security.Cryptography;
using System.Reflection;
using Moscrif.IDE.Tool;
using System.IO;
using System.Timers;
using System.Threading;
using Moscrif.IDE.Option;
namespace Moscrif.IDE.Iface
{
public class LoggUser
{
public LoggUser() {
}
string redgisterUrl = MainClass.Settings.redgisterUrl ;
string pingUrl = MainClass.Settings.pingUrl ;
string loginUrl = MainClass.Settings.loginUrl ;
string SALT = Security.SALT;
public void Register(string email,string login,string password,LoginYesTaskHandler loggYesTask,LoginNoTaskHandler loggNoTask){
string URL = redgisterUrl;
SystemWebClient client = new SystemWebClient();
string data = String.Format("{0}\n{1}\n{2}",email,login,GetMd5Sum(password+SALT));
client.UploadStringCompleted+= delegate(object sender, UploadStringCompletedEventArgs e) {
if (e.Cancelled){
if(loggNoTask!= null) loggNoTask(null,"Register failed.");
return;
}
if (e.Error != null){
if(loggNoTask!= null) loggNoTask(null,"Register failed.");
return;
}
string result = e.Result;
string token = "";
string licence = "";
ParseResult(result, ref token,ref licence);
if(String.IsNullOrEmpty(token)){
if(loggNoTask!= null) loggNoTask(null,"Register failed.");
return;
}
Account ac = CreateAccount(token);
if( ac!= null ){
ac.Login = login ;
Licenses lsl = Licenses.LoadLicenses(licence);
if(lsl!= null && lsl.Items.Count>0){
ac.LicenseId = lsl.Items[0].Typ;
}else {
ac.LicenseId = "-100";
}
if(loggYesTask!= null) loggYesTask(null,ac);
} else {
if(loggNoTask!= null) loggNoTask(null,"Register failed.");
return;
}
/*Account ac = CreateAccount(result);
if(ac!= null ){
ac.Login = login;
if(loggYesTask!= null) loggYesTask(null,ac);
} else {
if(loggNoTask!= null) loggNoTask(null,"Login failed.");
return;
}*/
};
client.UploadStringAsync(new Uri(URL),data);
}
public bool Ping(string token){
string URL =pingUrl;
string result;
SystemWebClient client = new SystemWebClient();
if( !string.IsNullOrEmpty(token))
URL = String.Format(URL+"?t={0}",token);
else {
return false;
}
try{
result = client.DownloadString(new Uri(URL));
if(!string.IsNullOrEmpty(result)){
Licenses lc = Licenses.LoadLicenses(result);
//MainClass.User.Licenses = lc;
if(lc!= null && lc.Items.Count>0){
MainClass.User.LicenseId = lc.Items[0].Typ;
}
}
}catch(Exception ex){
string statusDesc = "";
GetStatusCode(client,out statusDesc);
Console.WriteLine(ex.Message);
Logger.Error(ex.Message);
return false;
}
return true;
}
private static int GetStatusCode(SystemWebClient client, out string statusDescription)
{
FieldInfo responseField = client.GetType().GetField("m_WebRequest", BindingFlags.Instance | BindingFlags.NonPublic);
if (responseField != null)
{
HttpWebResponse response = responseField.GetValue(client) as HttpWebResponse;
if (response != null)
{
statusDescription = response.StatusDescription;
return (int)response.StatusCode;
}
}
statusDescription = null;
return 0;
}
public void CheckLogin(string name, string password,LoginYesTaskHandler loggYesTask,LoginNoTaskHandler loggNoTask){
string URL = loginUrl;
SystemWebClient client = new SystemWebClient();
string data = String.Format("{0}\n{1}",name,GetMd5Sum(password+SALT)); //\n{2}\n{3}",name,GetMd5Sum(password+SALT),Environment.MachineName,Environment.UserName);
try{
string result = client.UploadString(new Uri(URL),data);
string token = "";
string licence = "";
ParseResult(result, ref token,ref licence);
if(String.IsNullOrEmpty(token)){
if(loggNoTask!= null) loggNoTask(null,"Wrong username or password.");
return;
}
Account ac = CreateAccount(token);
if( ac!= null ){
ac.Login = name ;
Licenses lsl = Licenses.LoadLicenses(licence);
//ac.Licenses = lsl;
if(lsl!= null && lsl.Items.Count>0){
ac.LicenseId = lsl.Items[0].Typ;
} else {
ac.LicenseId = "-100";
}
if(loggYesTask!= null) loggYesTask(null,ac);
} else {
if(loggNoTask!= null) loggNoTask(null,"Wrong username or password.");
return;
}
} catch (Exception ex){
Logger.Error(ex.Message);
//if(loggNoTask!= null) loggNoTask(null,"Wrong username or password.");
if(loggNoTask!= null) loggNoTask(null,ex.Message);
return;
}
}
private void ParseResult (string input, ref string token, ref string licence){
int indx = input.IndexOf("<token>");
int indxLast = input.LastIndexOf("</token>");
//Console.WriteLine(result);
if((indx>-1)&&(indxLast>-1)){
//result = result.Substring(
Regex regx = new Regex("<token>.*?</token>");
MatchCollection mc = regx.Matches(input);
if(mc.Count>0){
token = mc[0].Value;
token= token.Replace("<token>",string.Empty);
token= token.Replace("</token>",string.Empty);
}
licence = regx.Replace(input,String.Empty);
}
}
/*
public void CheckLoginII(string name, string password,LoginYesTaskHandler loggYesTask,LoginNoTaskHandler loggNoTask){
string URL = loginUrl;
SystemWebClient client = new SystemWebClient();
string data = String.Format("{0}\n{1}\n{2}\n{3}",name,GetMd5Sum(password+SALT),Environment.MachineName,Environment.UserName);
client.UploadStringCompleted+= delegate(object sender, UploadStringCompletedEventArgs e) {
if (e.Cancelled){
if(loggNoTask!= null) loggNoTask(null,"Wrong username or password.");
return;
}
if (e.Error != null){
if(loggNoTask!= null) loggNoTask(null,"Wrong username or password.");
return;
}
string result = e.Result;
Account ac = CreateAccount(result);
if( ac!= null ){
ac.Login = name ;
if(loggYesTask!= null) loggYesTask(null,ac);
} else {
if(loggNoTask!= null) loggNoTask(null,"Wrong username or password.");
return;
}
};
client.UploadStringAsync(new Uri(URL),data);
}
*/
private Account CreateAccount(string response){
if(!String.IsNullOrEmpty(response)){
//Console.WriteLine(response);
/*License lcs = License.LoadLicense(response);
Account a = new Account();
a.Token = lcs.Token;
return a;*/
string[] responses = response.Replace('\r', '\0').Split('\n');
Account a = new Account();
a.Token = responses[0];
return a;
} else return null;
}
public string GetMd5Sum(string str) {
byte[] input = ASCIIEncoding.ASCII.GetBytes(str);
byte[] output = MD5.Create().ComputeHash(input);
StringBuilder sb = new StringBuilder();
for(int i=0;i<output.Length;i++) {
sb.Append(output[i].ToString("X2"));
}
return sb.ToString();
}
public delegate void LoginYesTaskHandler(object sender, Account account);
public delegate void LoginNoTaskHandler(object sender, string message);
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace CodeCracker.CSharp.Usage
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ReadonlyFieldAnalyzer : DiagnosticAnalyzer
{
internal const string Title = "Make field readonly";
internal const string Message = "Make '{0}' readonly";
internal const string Category = SupportedCategories.Usage;
const string Description = "A field that is only assigned on the constructor can be made readonly.";
internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticId.ReadonlyField.ToDiagnosticId(),
Title,
Message,
Category,
DiagnosticSeverity.Info,
isEnabledByDefault: true,
description: Description,
helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.ReadonlyField));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context) => context.RegisterCompilationStartAction(AnalyzeCompilation);
private static void AnalyzeCompilation(CompilationStartAnalysisContext compilationStartAnalysisContext)
{
var compilation = compilationStartAnalysisContext.Compilation;
compilationStartAnalysisContext.RegisterSyntaxTreeAction(context => AnalyzeTree(context, compilation));
}
private struct MethodKindComparer : IComparer<MethodKind>
{
public int Compare(MethodKind x, MethodKind y) =>
x - y == 0
? 0
: (x == MethodKind.Constructor
? 1
: (y == MethodKind.Constructor
? -1
: x - y));
}
private static readonly MethodKindComparer methodKindComparer = new MethodKindComparer();
private static void AnalyzeTree(SyntaxTreeAnalysisContext context, Compilation compilation)
{
if (context.IsGenerated()) return;
if (!compilation.SyntaxTrees.Contains(context.Tree)) return;
var semanticModel = compilation.GetSemanticModel(context.Tree);
SyntaxNode root;
if (!context.Tree.TryGetRoot(out root)) return;
var types = GetTypesInRoot(root);
foreach (var type in types)
{
var fieldDeclarations = type.ChildNodes().OfType<FieldDeclarationSyntax>();
var variablesToMakeReadonly = GetCandidateVariables(semanticModel, fieldDeclarations);
var typeSymbol = semanticModel.GetDeclaredSymbol(type);
if (typeSymbol == null) continue;
var methods = typeSymbol.GetAllMethodsIncludingFromInnerTypes();
methods = methods.OrderByDescending(m => m.MethodKind, methodKindComparer).ToList();
foreach (var method in methods)
{
foreach (var syntaxReference in method.DeclaringSyntaxReferences)
{
var syntaxRefSemanticModel = syntaxReference.SyntaxTree.Equals(context.Tree)
? semanticModel
: compilation.GetSemanticModel(syntaxReference.SyntaxTree);
var descendants = syntaxReference.GetSyntax().DescendantNodes().ToList();
var argsWithRefOrOut = descendants.OfType<ArgumentSyntax>().Where(a => a.RefOrOutKeyword != null);
foreach (var argWithRefOrOut in argsWithRefOrOut)
{
var fieldSymbol = syntaxRefSemanticModel.GetSymbolInfo(argWithRefOrOut.Expression).Symbol as IFieldSymbol;
if (fieldSymbol == null) continue;
variablesToMakeReadonly.Remove(fieldSymbol);
}
var assignments = descendants.OfKind(SyntaxKind.SimpleAssignmentExpression,
SyntaxKind.AddAssignmentExpression, SyntaxKind.AndAssignmentExpression, SyntaxKind.DivideAssignmentExpression,
SyntaxKind.ExclusiveOrAssignmentExpression, SyntaxKind.LeftShiftAssignmentExpression, SyntaxKind.ModuloAssignmentExpression,
SyntaxKind.MultiplyAssignmentExpression, SyntaxKind.OrAssignmentExpression, SyntaxKind.RightShiftAssignmentExpression,
SyntaxKind.SubtractAssignmentExpression);
foreach (AssignmentExpressionSyntax assignment in assignments)
{
var fieldSymbol = syntaxRefSemanticModel.GetSymbolInfo(assignment.Left).Symbol as IFieldSymbol;
VerifyVariable(variablesToMakeReadonly, method, syntaxRefSemanticModel, assignment, fieldSymbol);
}
var postFixUnaries = descendants.OfKind(SyntaxKind.PostIncrementExpression, SyntaxKind.PostDecrementExpression);
foreach (PostfixUnaryExpressionSyntax postFixUnary in postFixUnaries)
{
var fieldSymbol = syntaxRefSemanticModel.GetSymbolInfo(postFixUnary.Operand).Symbol as IFieldSymbol;
VerifyVariable(variablesToMakeReadonly, method, syntaxRefSemanticModel, postFixUnary, fieldSymbol);
}
var preFixUnaries = descendants.OfKind(SyntaxKind.PreDecrementExpression, SyntaxKind.PreIncrementExpression);
foreach (PrefixUnaryExpressionSyntax preFixUnary in preFixUnaries)
{
var fieldSymbol = syntaxRefSemanticModel.GetSymbolInfo(preFixUnary.Operand).Symbol as IFieldSymbol;
VerifyVariable(variablesToMakeReadonly, method, syntaxRefSemanticModel, preFixUnary, fieldSymbol);
}
}
}
foreach (var readonlyVariable in variablesToMakeReadonly.Values)
{
var props = new Dictionary<string, string> { { "identifier", readonlyVariable.Identifier.Text } }.ToImmutableDictionary();
var diagnostic = Diagnostic.Create(Rule, readonlyVariable.GetLocation(), props, readonlyVariable.Identifier.Text);
context.ReportDiagnostic(diagnostic);
}
}
}
private static void VerifyVariable(Dictionary<IFieldSymbol, VariableDeclaratorSyntax> variablesToMakeReadonly, IMethodSymbol method,
SemanticModel syntaxRefSemanticModel, SyntaxNode node, IFieldSymbol fieldSymbol)
{
if (fieldSymbol == null) return;
if (!CanBeMadeReadonly(fieldSymbol)) return;
if (!HasAssignmentInLambda(node)
&& ((method.MethodKind == MethodKind.StaticConstructor && fieldSymbol.IsStatic)
|| (method.MethodKind == MethodKind.Constructor && !fieldSymbol.IsStatic)))
AddVariableThatWasSkippedBeforeBecauseItLackedAInitializer(variablesToMakeReadonly, fieldSymbol, node, syntaxRefSemanticModel);
else
RemoveVariableThatHasAssignment(variablesToMakeReadonly, fieldSymbol);
}
private static bool HasAssignmentInLambda(SyntaxNode assignment)
{
var parent = assignment.Parent;
while (parent != null)
{
if (parent is AnonymousFunctionExpressionSyntax)
return true;
parent = parent.Parent;
}
return false;
}
private static void AddVariableThatWasSkippedBeforeBecauseItLackedAInitializer(Dictionary<IFieldSymbol, VariableDeclaratorSyntax> variablesToMakeReadonly, IFieldSymbol fieldSymbol, SyntaxNode assignment, SemanticModel semanticModel)
{
if (!fieldSymbol.IsReadOnly && !variablesToMakeReadonly.Keys.Contains(fieldSymbol) && !IsComplexValueType(fieldSymbol.Type))
{
var containingType = assignment.FirstAncestorOfKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration);
if (containingType == null) return;
var containingTypeSymbol = semanticModel.GetDeclaredSymbol(containingType) as INamedTypeSymbol;
if (containingTypeSymbol == null) return;
if (!fieldSymbol.ContainingType.Equals(containingTypeSymbol)) return;
foreach (var variable in fieldSymbol.DeclaringSyntaxReferences)
variablesToMakeReadonly.Add(fieldSymbol, (VariableDeclaratorSyntax)variable.GetSyntax());
}
}
private static void RemoveVariableThatHasAssignment(Dictionary<IFieldSymbol, VariableDeclaratorSyntax> variablesToMakeReadonly, IFieldSymbol fieldSymbol)
{
if (variablesToMakeReadonly.Keys.Contains(fieldSymbol))
variablesToMakeReadonly.Remove(fieldSymbol);
}
private static Dictionary<IFieldSymbol, VariableDeclaratorSyntax> GetCandidateVariables(SemanticModel semanticModel, IEnumerable<FieldDeclarationSyntax> fieldDeclarations)
{
var variablesToMakeReadonly = new Dictionary<IFieldSymbol, VariableDeclaratorSyntax>();
foreach (var fieldDeclaration in fieldDeclarations)
variablesToMakeReadonly.AddRange(GetCandidateVariables(semanticModel, fieldDeclaration));
return variablesToMakeReadonly;
}
private static Dictionary<IFieldSymbol, VariableDeclaratorSyntax> GetCandidateVariables(SemanticModel semanticModel, FieldDeclarationSyntax fieldDeclaration)
{
var variablesToMakeReadonly = new Dictionary<IFieldSymbol, VariableDeclaratorSyntax>();
if (fieldDeclaration == null ||
IsComplexValueType(semanticModel, fieldDeclaration) ||
!CanBeMadeReadonly(fieldDeclaration))
{
return variablesToMakeReadonly;
}
foreach (var variable in fieldDeclaration.Declaration.Variables)
{
if (variable.Initializer == null) continue;
var variableSymbol = semanticModel.GetDeclaredSymbol(variable);
if (variableSymbol == null) continue;
variablesToMakeReadonly.Add((IFieldSymbol)variableSymbol, variable);
}
return variablesToMakeReadonly;
}
private static bool CanBeMadeReadonly(FieldDeclarationSyntax fieldDeclaration)
{
return !fieldDeclaration.Modifiers.Any()
|| !fieldDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.PublicKeyword)
|| m.IsKind(SyntaxKind.ProtectedKeyword)
|| m.IsKind(SyntaxKind.InternalKeyword)
|| m.IsKind(SyntaxKind.ReadOnlyKeyword)
|| m.IsKind(SyntaxKind.ConstKeyword));
}
private static bool IsComplexValueType(SemanticModel semanticModel, FieldDeclarationSyntax fieldDeclaration)
{
var fieldTypeName = fieldDeclaration.Declaration.Type;
var fieldType = semanticModel.GetTypeInfo(fieldTypeName).ConvertedType;
return IsComplexValueType(fieldType);
}
private static bool IsComplexValueType(ITypeSymbol fieldType) => fieldType.IsValueType && !(fieldType.TypeKind == TypeKind.Enum || fieldType.IsPrimitive());
private static bool CanBeMadeReadonly(IFieldSymbol fieldSymbol)
{
return (fieldSymbol.DeclaredAccessibility == Accessibility.NotApplicable
|| fieldSymbol.DeclaredAccessibility == Accessibility.Private)
&& !fieldSymbol.IsReadOnly
&& !fieldSymbol.IsConst;
}
private static List<TypeDeclarationSyntax> GetTypesInRoot(SyntaxNode root)
{
var types = new List<TypeDeclarationSyntax>();
if (root.IsKind(SyntaxKind.ClassDeclaration) || root.IsKind(SyntaxKind.StructDeclaration))
types.Add((TypeDeclarationSyntax)root);
else
types.AddRange(root.DescendantTypes());
return types;
}
}
}
| |
// Copyright (c) 2013-2015 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
// Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using SharpNav.Geometry;
namespace SharpNav
{
/// <summary>
/// Flags that can be applied to a region.
/// </summary>
[Flags]
public enum RegionFlags
{
/// <summary>
/// The border flag
/// </summary>
Border = 0x20000000,
/// <summary>
/// The vertex border flag
/// </summary>
VertexBorder = 0x40000000,
/// <summary>
/// The area border flag
/// </summary>
AreaBorder = unchecked((int)0x80000000)
}
/// <summary>
/// A <see cref="RegionId"/> is an identifier with flags marking borders.
/// </summary>
[Serializable]
public struct RegionId : IEquatable<RegionId>, IEquatable<int>
{
/// <summary>
/// A null region is one with an ID of 0.
/// </summary>
public static readonly RegionId Null = new RegionId(0, 0);
/// <summary>
/// A bitmask
/// </summary>
public const int MaskId = 0x1fffffff;
/// <summary>
/// The internal storage of a <see cref="RegionId"/>. The <see cref="RegionFlags"/> portion are the most
/// significant bits, the integer identifier are the least significant bits, marked by <see cref="MaskId"/>.
/// </summary>
private int bits;
/// <summary>
/// Initializes a new instance of the <see cref="RegionId"/> struct without any flags.
/// </summary>
/// <param name="id">The identifier.</param>
public RegionId(int id)
: this(id, 0)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RegionId"/> struct.
/// </summary>
/// <param name="id"></param>
/// <param name="flags"></param>
public RegionId(int id, RegionFlags flags)
{
int masked = id & MaskId;
if (masked != id)
throw new ArgumentOutOfRangeException("id", "The provided id is outside of the valid range. The 3 most significant bits must be 0. Maybe you wanted RegionId.FromRawBits()?");
if ((RegionFlags)((int)flags & ~MaskId) != flags)
throw new ArgumentException("flags", "The provide region flags are invalid.");
bits = masked | (int)flags;
}
/// <summary>
/// Gets the ID of the region without any flags.
/// </summary>
public int Id
{
get
{
return bits & MaskId;
}
}
/// <summary>
/// Gets the flags set for this region.
/// </summary>
public RegionFlags Flags
{
get
{
return (RegionFlags)(bits & ~MaskId);
}
}
/// <summary>
/// Gets a value indicating whether the region is the null region (ID == 0).
/// </summary>
public bool IsNull
{
get
{
return (bits & MaskId) == 0;
}
}
/// <summary>
/// Creates a new <see cref="RegionId"/> from a value that contains both the region ID and the flags.
/// </summary>
/// <param name="bits">The int containing <see cref="RegionId"/> data.</param>
/// <returns>A new instance of the <see cref="RegionId"/> struct with the specified data.</returns>
public static RegionId FromRawBits(int bits)
{
RegionId id;
id.bits = bits;
return id;
}
/// <summary>
/// Creates a new <see cref="RegionId"/> with extra flags.
/// </summary>
/// <param name="region">The region to add flags to.</param>
/// <param name="flags">The flags to add.</param>
/// <returns>A new instance of the <see cref="RegionId"/> struct with extra flags.</returns>
public static RegionId WithFlags(RegionId region, RegionFlags flags)
{
if ((RegionFlags)((int)flags & ~MaskId) != flags)
throw new ArgumentException("flags", "The provide region flags are invalid.");
RegionFlags newFlags = region.Flags | flags;
return RegionId.FromRawBits((region.bits & MaskId) | (int)newFlags);
}
/// <summary>
/// Creates a new instance of the <see cref="RegionId"/> class without any flags set.
/// </summary>
/// <param name="region">The region to use.</param>
/// <returns>A new instance of the <see cref="RegionId"/> struct without any flags set.</returns>
public static RegionId WithoutFlags(RegionId region)
{
return new RegionId(region.Id);
}
/// <summary>
/// Creates a new instance of the <see cref="RegionId"/> class without certain flags set.
/// </summary>
/// <param name="region">The region to use.</param>
/// <param name="flags">The flags to unset.</param>
/// <returns>A new instnace of the <see cref="RegionId"/> struct without certain flags set.</returns>
public static RegionId WithoutFlags(RegionId region, RegionFlags flags)
{
if ((RegionFlags)((int)flags & ~MaskId) != flags)
throw new ArgumentException("flags", "The provide region flags are invalid.");
RegionFlags newFlags = region.Flags & ~flags;
return RegionId.FromRawBits((region.bits & MaskId) | (int)newFlags);
}
/// <summary>
/// Checks if a region has certain flags.
/// </summary>
/// <param name="region">The region to check.</param>
/// <param name="flags">The flags to check.</param>
/// <returns>A value indicating whether the region has all of the specified flags.</returns>
public static bool HasFlags(RegionId region, RegionFlags flags)
{
return (region.Flags & flags) != 0;
}
/// <summary>
/// Compares an instance of <see cref="RegionId"/> with an integer for equality.
/// </summary>
/// <remarks>
/// This checks for both the ID and flags set on the region. If you want to only compare the IDs, use the
/// following code:
/// <code>
/// RegionId left = ...;
/// int right = ...;
/// if (left.Id == right)
/// {
/// // ...
/// }
/// </code>
/// </remarks>
/// <param name="left">An instance of <see cref="RegionId"/>.</param>
/// <param name="right">An integer.</param>
/// <returns>A value indicating whether the two values are equal.</returns>
public static bool operator ==(RegionId left, int right)
{
return left.Equals(right);
}
/// <summary>
/// Compares an instance of <see cref="RegionId"/> with an integer for inequality.
/// </summary>
/// <remarks>
/// This checks for both the ID and flags set on the region. If you want to only compare the IDs, use the
/// following code:
/// <code>
/// RegionId left = ...;
/// int right = ...;
/// if (left.Id != right)
/// {
/// // ...
/// }
/// </code>
/// </remarks>
/// <param name="left">An instance of <see cref="RegionId"/>.</param>
/// <param name="right">An integer.</param>
/// <returns>A value indicating whether the two values are unequal.</returns>
public static bool operator !=(RegionId left, int right)
{
return !(left == right);
}
/// <summary>
/// Compares two instances of <see cref="RegionId"/> for equality.
/// </summary>
/// <remarks>
/// This checks for both the ID and flags set on the regions. If you want to only compare the IDs, use the
/// following code:
/// <code>
/// RegionId left = ...;
/// RegionId right = ...;
/// if (left.Id == right.Id)
/// {
/// // ...
/// }
/// </code>
/// </remarks>
/// <param name="left">An instance of <see cref="RegionId"/>.</param>
/// <param name="right">Another instance of <see cref="RegionId"/>.</param>
/// <returns>A value indicating whether the two instances are equal.</returns>
public static bool operator ==(RegionId left, RegionId right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two instances of <see cref="RegionId"/> for inequality.
/// </summary>
/// <remarks>
/// This checks for both the ID and flags set on the regions. If you want to only compare the IDs, use the
/// following code:
/// <code>
/// RegionId left = ...;
/// RegionId right = ...;
/// if (left.Id != right.Id)
/// {
/// // ...
/// }
/// </code>
/// </remarks>
/// <param name="left">An instance of <see cref="RegionId"/>.</param>
/// <param name="right">Another instance of <see cref="RegionId"/>.</param>
/// <returns>A value indicating whether the two instances are unequal.</returns>
public static bool operator !=(RegionId left, RegionId right)
{
return !(left == right);
}
/// <summary>
/// Converts an instance of <see cref="RegionId"/> to an integer containing both the ID and the flags.
/// </summary>
/// <param name="id">An instance of <see cref="RegionId"/>.</param>
/// <returns>An integer.</returns>
public static explicit operator int(RegionId id)
{
return id.bits;
}
/// <summary>
/// Compares this instance with another instance of <see cref="RegionId"/> for equality, including flags.
/// </summary>
/// <param name="other">An instance of <see cref="RegionId"/>.</param>
/// <returns>A value indicating whether the two instances are equal.</returns>
public bool Equals(RegionId other)
{
bool thisNull = this.IsNull;
bool otherNull = other.IsNull;
if (thisNull && otherNull)
return true;
else if (thisNull ^ otherNull)
return false;
else
return this.bits == other.bits;
}
/// <summary>
/// Compares this instance with another an intenger for equality, including flags.
/// </summary>
/// <param name="other">An integer.</param>
/// <returns>A value indicating whether the two instances are equal.</returns>
public bool Equals(int other)
{
RegionId otherId;
otherId.bits = other;
return this.Equals(otherId);
}
/// <summary>
/// Compares this instance with an object for equality.
/// </summary>
/// <param name="obj">An object</param>
/// <returns>A value indicating whether the two instances are equal.</returns>
public override bool Equals(object obj)
{
var regObj = obj as RegionId?;
var intObj = obj as int?;
if (regObj.HasValue)
return this.Equals(regObj.Value);
else if (intObj.HasValue)
return this.Equals(intObj.Value);
else
return false;
}
/// <summary>
/// Gets a unique hash code for this instance.
/// </summary>
/// <returns>A hash code.</returns>
public override int GetHashCode()
{
if (IsNull)
return 0;
return bits.GetHashCode();
}
/// <summary>
/// Gets a human-readable version of this instance.
/// </summary>
/// <returns>A string representing this instance.</returns>
public override string ToString()
{
return "{ Id: " + Id + ", Flags: " + Flags + "}";
}
}
/// <summary>
/// A Region contains a group of adjacent spans.
/// </summary>
public class Region
{
private int spanCount;
private RegionId id;
private Area areaType;
private bool remap;
private bool visited;
private List<RegionId> connections;
private List<RegionId> floors;
/// <summary>
/// Initializes a new instance of the <see cref="Region" /> class.
/// </summary>
/// <param name="idNum">The id</param>
public Region(int idNum)
{
spanCount = 0;
id = new RegionId(idNum);
areaType = 0;
remap = false;
visited = false;
connections = new List<RegionId>();
floors = new List<RegionId>();
}
/// <summary>
/// Gets or sets the number of spans
/// </summary>
public int SpanCount
{
get
{
return spanCount;
}
set
{
this.spanCount = value;
}
}
/// <summary>
/// Gets or sets the region id
/// </summary>
public RegionId Id
{
get
{
return id;
}
set
{
this.id = value;
}
}
/// <summary>
/// Gets or sets the AreaType of this region
/// </summary>
public Area AreaType
{
get
{
return areaType;
}
set
{
this.areaType = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this region has been remapped or not
/// </summary>
public bool Remap
{
get
{
return remap;
}
set
{
this.remap = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this region has been visited or not
/// </summary>
public bool Visited
{
get
{
return visited;
}
set
{
this.visited = value;
}
}
/// <summary>
/// Gets the list of floor regions
/// </summary>
public List<RegionId> FloorRegions
{
get
{
return floors;
}
}
/// <summary>
/// Gets the list of connected regions
/// </summary>
public List<RegionId> Connections
{
get
{
return connections;
}
}
/// <summary>
/// Gets a value indicating whether the region is a border region.
/// </summary>
public bool IsBorder
{
get
{
return RegionId.HasFlags(id, RegionFlags.Border);
}
}
/// <summary>
/// Gets a value indicating whether the region is either a border region or the null region.
/// </summary>
public bool IsBorderOrNull
{
get
{
return id.IsNull || IsBorder;
}
}
/// <summary>
/// Remove adjacent connections if there is a duplicate
/// </summary>
public void RemoveAdjacentNeighbors()
{
if (connections.Count <= 1)
return;
// Remove adjacent duplicates.
for (int i = 0; i < connections.Count; i++)
{
//get the next i
int ni = (i + 1) % connections.Count;
//remove duplicate if found
if (connections[i] == connections[ni])
{
connections.RemoveAt(i);
i--;
}
}
}
/// <summary>
/// Replace all connection and floor values
/// </summary>
/// <param name="oldId">The value you want to replace</param>
/// <param name="newId">The new value that will be used</param>
public void ReplaceNeighbor(RegionId oldId, RegionId newId)
{
//replace the connections
bool neiChanged = false;
for (int i = 0; i < connections.Count; ++i)
{
if (connections[i] == oldId)
{
connections[i] = newId;
neiChanged = true;
}
}
//replace the floors
for (int i = 0; i < floors.Count; ++i)
{
if (floors[i] == oldId)
floors[i] = newId;
}
//make sure to remove adjacent neighbors
if (neiChanged)
RemoveAdjacentNeighbors();
}
/// <summary>
/// Determine whether this region can merge with another region.
/// </summary>
/// <param name="otherRegion">The other region to merge with</param>
/// <returns>True if the two regions can be merged, false if otherwise</returns>
public bool CanMergeWith(Region otherRegion)
{
//make sure areas are the same
if (areaType != otherRegion.areaType)
return false;
//count the number of connections to the other region
int n = 0;
for (int i = 0; i < connections.Count; i++)
{
if (connections[i] == otherRegion.id)
n++;
}
//make sure there's only one connection
if (n > 1)
return false;
//make sure floors are separate
if (floors.Contains(otherRegion.id))
return false;
return true;
}
/// <summary>
/// Only add a floor if it hasn't been added already
/// </summary>
/// <param name="n">The value of the floor</param>
public void AddUniqueFloorRegion(RegionId n)
{
if (!floors.Contains(n))
floors.Add(n);
}
/// <summary>
/// Merge two regions into one. Needs good testing
/// </summary>
/// <param name="otherRegion">The region to merge with</param>
/// <returns>True if merged successfully, false if otherwise</returns>
public bool MergeWithRegion(Region otherRegion)
{
RegionId thisId = id;
RegionId otherId = otherRegion.id;
// Duplicate current neighborhood.
List<RegionId> thisConnected = new List<RegionId>();
for (int i = 0; i < connections.Count; ++i)
thisConnected.Add(connections[i]);
List<RegionId> otherConnected = otherRegion.connections;
// Find insertion point on this region
int insertInThis = -1;
for (int i = 0; i < thisConnected.Count; ++i)
{
if (thisConnected[i] == otherId)
{
insertInThis = i;
break;
}
}
if (insertInThis == -1)
return false;
// Find insertion point on the other region
int insertInOther = -1;
for (int i = 0; i < otherConnected.Count; ++i)
{
if (otherConnected[i] == thisId)
{
insertInOther = i;
break;
}
}
if (insertInOther == -1)
return false;
// Merge neighbors.
connections = new List<RegionId>();
for (int i = 0, ni = thisConnected.Count; i < ni - 1; ++i)
connections.Add(thisConnected[(insertInThis + 1 + i) % ni]);
for (int i = 0, ni = otherConnected.Count; i < ni - 1; ++i)
connections.Add(otherConnected[(insertInOther + 1 + i) % ni]);
RemoveAdjacentNeighbors();
for (int j = 0; j < otherRegion.floors.Count; ++j)
AddUniqueFloorRegion(otherRegion.floors[j]);
spanCount += otherRegion.spanCount;
otherRegion.spanCount = 0;
otherRegion.connections.Clear();
return true;
}
/// <summary>
/// Test if region is connected to a border
/// </summary>
/// <returns>True if connected, false if not</returns>
public bool IsConnectedToBorder()
{
// Region is connected to border if
// one of the neighbors is null id.
for (int i = 0; i < connections.Count; ++i)
{
if (connections[i] == 0)
return true;
}
return false;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
namespace Lucene.Net.Search
{
/// <summary>Subclass of FilteredTermEnum for enumerating all terms that are similiar
/// to the specified filter term.
///
/// <p/>Term enumerations are always ordered by Term.compareTo(). Each term in
/// the enumeration is greater than all that precede it.
/// </summary>
public sealed class FuzzyTermEnum:FilteredTermEnum
{
/* This should be somewhere around the average long word.
* If it is longer, we waste time and space. If it is shorter, we waste a
* little bit of time growing the array as we encounter longer words.
*/
private const int TYPICAL_LONGEST_WORD_IN_INDEX = 19;
/* Allows us save time required to create a new array
* everytime similarity is called.
*/
private int[][] d;
private float similarity;
private bool endEnum = false;
private Term searchTerm = null;
private System.String field;
private System.String text;
private System.String prefix;
private float minimumSimilarity;
private float scale_factor;
private int[] maxDistances = new int[TYPICAL_LONGEST_WORD_IN_INDEX];
/// <summary> Creates a FuzzyTermEnum with an empty prefix and a minSimilarity of 0.5f.
/// <p/>
/// After calling the constructor the enumeration is already pointing to the first
/// valid term if such a term exists.
///
/// </summary>
/// <param name="reader">
/// </param>
/// <param name="term">
/// </param>
/// <throws> IOException </throws>
/// <seealso cref="FuzzyTermEnum(IndexReader, Term, float, int)">
/// </seealso>
public FuzzyTermEnum(IndexReader reader, Term term):this(reader, term, FuzzyQuery.defaultMinSimilarity, FuzzyQuery.defaultPrefixLength)
{
}
/// <summary> Creates a FuzzyTermEnum with an empty prefix.
/// <p/>
/// After calling the constructor the enumeration is already pointing to the first
/// valid term if such a term exists.
///
/// </summary>
/// <param name="reader">
/// </param>
/// <param name="term">
/// </param>
/// <param name="minSimilarity">
/// </param>
/// <throws> IOException </throws>
/// <seealso cref="FuzzyTermEnum(IndexReader, Term, float, int)">
/// </seealso>
public FuzzyTermEnum(IndexReader reader, Term term, float minSimilarity):this(reader, term, minSimilarity, FuzzyQuery.defaultPrefixLength)
{
}
/// <summary> Constructor for enumeration of all terms from specified <code>reader</code> which share a prefix of
/// length <code>prefixLength</code> with <code>term</code> and which have a fuzzy similarity >
/// <code>minSimilarity</code>.
/// <p/>
/// After calling the constructor the enumeration is already pointing to the first
/// valid term if such a term exists.
///
/// </summary>
/// <param name="reader">Delivers terms.
/// </param>
/// <param name="term">Pattern term.
/// </param>
/// <param name="minSimilarity">Minimum required similarity for terms from the reader. Default value is 0.5f.
/// </param>
/// <param name="prefixLength">Length of required common prefix. Default value is 0.
/// </param>
/// <throws> IOException </throws>
public FuzzyTermEnum(IndexReader reader, Term term, float minSimilarity, int prefixLength):base()
{
if (minSimilarity >= 1.0f)
throw new System.ArgumentException("minimumSimilarity cannot be greater than or equal to 1");
else if (minSimilarity < 0.0f)
throw new System.ArgumentException("minimumSimilarity cannot be less than 0");
if (prefixLength < 0)
throw new System.ArgumentException("prefixLength cannot be less than 0");
this.minimumSimilarity = minSimilarity;
this.scale_factor = 1.0f / (1.0f - minimumSimilarity);
this.searchTerm = term;
this.field = searchTerm.Field();
//The prefix could be longer than the word.
//It's kind of silly though. It means we must match the entire word.
int fullSearchTermLength = searchTerm.Text().Length;
int realPrefixLength = prefixLength > fullSearchTermLength?fullSearchTermLength:prefixLength;
this.text = searchTerm.Text().Substring(realPrefixLength);
this.prefix = searchTerm.Text().Substring(0, (realPrefixLength) - (0));
InitializeMaxDistances();
this.d = InitDistanceArray();
SetEnum(reader.Terms(new Term(searchTerm.Field(), prefix)));
}
/// <summary> The termCompare method in FuzzyTermEnum uses Levenshtein distance to
/// calculate the distance between the given term and the comparing term.
/// </summary>
public /*protected internal*/ override bool TermCompare(Term term)
{
if ((System.Object) field == (System.Object) term.Field() && term.Text().StartsWith(prefix))
{
System.String target = term.Text().Substring(prefix.Length);
this.similarity = Similarity(target);
return (similarity > minimumSimilarity);
}
endEnum = true;
return false;
}
public override float Difference()
{
return (float) ((similarity - minimumSimilarity) * scale_factor);
}
public override bool EndEnum()
{
return endEnum;
}
/// <summary>***************************
/// Compute Levenshtein distance
/// ****************************
/// </summary>
/// <summary> Finds and returns the smallest of three integers </summary>
private static int Min(int a, int b, int c)
{
int t = (a < b)?a:b;
return (t < c)?t:c;
}
private int[][] InitDistanceArray()
{
int[][] tmpArray = new int[this.text.Length + 1][];
for (int i = 0; i < this.text.Length + 1; i++)
{
tmpArray[i] = new int[TYPICAL_LONGEST_WORD_IN_INDEX];
}
return tmpArray;
}
/// <summary> <p/>Similarity returns a number that is 1.0f or less (including negative numbers)
/// based on how similar the Term is compared to a target term. It returns
/// exactly 0.0f when
/// <pre>
/// editDistance < maximumEditDistance</pre>
/// Otherwise it returns:
/// <pre>
/// 1 - (editDistance / length)</pre>
/// where length is the length of the shortest term (text or target) including a
/// prefix that are identical and editDistance is the Levenshtein distance for
/// the two words.<p/>
///
/// <p/>Embedded within this algorithm is a fail-fast Levenshtein distance
/// algorithm. The fail-fast algorithm differs from the standard Levenshtein
/// distance algorithm in that it is aborted if it is discovered that the
/// mimimum distance between the words is greater than some threshold.
///
/// <p/>To calculate the maximum distance threshold we use the following formula:
/// <pre>
/// (1 - minimumSimilarity) * length</pre>
/// where length is the shortest term including any prefix that is not part of the
/// similarity comparision. This formula was derived by solving for what maximum value
/// of distance returns false for the following statements:
/// <pre>
/// similarity = 1 - ((float)distance / (float) (prefixLength + Math.min(textlen, targetlen)));
/// return (similarity > minimumSimilarity);</pre>
/// where distance is the Levenshtein distance for the two words.
/// <p/>
/// <p/>Levenshtein distance (also known as edit distance) is a measure of similiarity
/// between two strings where the distance is measured as the number of character
/// deletions, insertions or substitutions required to transform one string to
/// the other string.
/// </summary>
/// <param name="target">the target word or phrase
/// </param>
/// <returns> the similarity, 0.0 or less indicates that it matches less than the required
/// threshold and 1.0 indicates that the text and target are identical
/// </returns>
private float Similarity(System.String target)
{
int m = target.Length;
int n = text.Length;
if (n == 0)
{
//we don't have anything to compare. That means if we just add
//the letters for m we get the new word
return prefix.Length == 0 ? 0.0f : 1.0f - ((float)m / prefix.Length);
}
if (m == 0)
{
return prefix.Length == 0 ? 0.0f : 1.0f - ((float)n / prefix.Length);
}
int maxDistance = GetMaxDistance(m);
if (maxDistance < System.Math.Abs(m - n))
{
//just adding the characters of m to n or vice-versa results in
//too many edits
//for example "pre" length is 3 and "prefixes" length is 8. We can see that
//given this optimal circumstance, the edit distance cannot be less than 5.
//which is 8-3 or more precisesly Math.abs(3-8).
//if our maximum edit distance is 4, then we can discard this word
//without looking at it.
return 0.0f;
}
//let's make sure we have enough room in our array to do the distance calculations.
if (d[0].Length <= m)
{
GrowDistanceArray(m);
}
// init matrix d
for (int i = 0; i <= n; i++)
d[i][0] = i;
for (int j = 0; j <= m; j++)
d[0][j] = j;
// start computing edit distance
for (int i = 1; i <= n; i++)
{
int bestPossibleEditDistance = m;
char s_i = text[i - 1];
for (int j = 1; j <= m; j++)
{
if (s_i != target[j - 1])
{
d[i][j] = Min(d[i - 1][j], d[i][j - 1], d[i - 1][j - 1]) + 1;
}
else
{
d[i][j] = Min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1]);
}
bestPossibleEditDistance = System.Math.Min(bestPossibleEditDistance, d[i][j]);
}
//After calculating row i, the best possible edit distance
//can be found by found by finding the smallest value in a given column.
//If the bestPossibleEditDistance is greater than the max distance, abort.
if (i > maxDistance && bestPossibleEditDistance > maxDistance)
{
//equal is okay, but not greater
//the closest the target can be to the text is just too far away.
//this target is leaving the party early.
return 0.0f;
}
}
// this will return less than 0.0 when the edit distance is
// greater than the number of characters in the shorter word.
// but this was the formula that was previously used in FuzzyTermEnum,
// so it has not been changed (even though minimumSimilarity must be
// greater than 0.0)
return 1.0f - ((float)d[n][m] / (float)(prefix.Length + System.Math.Min(n, m)));
}
/// <summary> Grow the second dimension of the array, so that we can calculate the
/// Levenshtein difference.
/// </summary>
private void GrowDistanceArray(int m)
{
for (int i = 0; i < d.Length; i++)
{
d[i] = new int[m + 1];
}
}
/// <summary> The max Distance is the maximum Levenshtein distance for the text
/// compared to some other value that results in score that is
/// better than the minimum similarity.
/// </summary>
/// <param name="m">the length of the "other value"
/// </param>
/// <returns> the maximum levenshtein distance that we care about
/// </returns>
private int GetMaxDistance(int m)
{
return (m < maxDistances.Length)?maxDistances[m]:CalculateMaxDistance(m);
}
private void InitializeMaxDistances()
{
for (int i = 0; i < maxDistances.Length; i++)
{
maxDistances[i] = CalculateMaxDistance(i);
}
}
private int CalculateMaxDistance(int m)
{
return (int) ((1 - minimumSimilarity) * (System.Math.Min(text.Length, m) + prefix.Length));
}
public override void Close()
{
base.Close(); //call super.close() and let the garbage collector do its work.
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmExport
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmExport() : base()
{
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_Click;
}
}
}
public System.Windows.Forms.Label lblHeading;
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.ProgressBar prgUpdate;
private System.Windows.Forms.Button withEventsField_Command3;
public System.Windows.Forms.Button Command3 {
get { return withEventsField_Command3; }
set {
if (withEventsField_Command3 != null) {
withEventsField_Command3.Click -= Command3_Click;
}
withEventsField_Command3 = value;
if (withEventsField_Command3 != null) {
withEventsField_Command3.Click += Command3_Click;
}
}
}
public System.Windows.Forms.TextBox txtFile;
public System.Windows.Forms.OpenFileDialog cmdDlgOpen;
public Microsoft.VisualBasic.PowerPacks.LineShape Line1;
public System.Windows.Forms.Label Label2;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmExport));
this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this.Line1 = new Microsoft.VisualBasic.PowerPacks.LineShape();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdClose = new System.Windows.Forms.Button();
this.lblHeading = new System.Windows.Forms.Label();
this.prgUpdate = new System.Windows.Forms.ProgressBar();
this.Command3 = new System.Windows.Forms.Button();
this.txtFile = new System.Windows.Forms.TextBox();
this.cmdDlgOpen = new System.Windows.Forms.OpenFileDialog();
this.Label2 = new System.Windows.Forms.Label();
this.picButtons.SuspendLayout();
this.SuspendLayout();
//
//ShapeContainer1
//
this.ShapeContainer1.Location = new System.Drawing.Point(0, 0);
this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0);
this.ShapeContainer1.Name = "ShapeContainer1";
this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] { this.Line1 });
this.ShapeContainer1.Size = new System.Drawing.Size(512, 114);
this.ShapeContainer1.TabIndex = 5;
this.ShapeContainer1.TabStop = false;
//
//Line1
//
this.Line1.BorderColor = System.Drawing.SystemColors.WindowText;
this.Line1.BorderWidth = 2;
this.Line1.Name = "Line1";
this.Line1.X1 = 4;
this.Line1.X2 = 504;
this.Line1.Y1 = 44;
this.Line1.Y2 = 44;
//
//picButtons
//
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Controls.Add(this.cmdClose);
this.picButtons.Controls.Add(this.lblHeading);
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.Name = "picButtons";
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Size = new System.Drawing.Size(512, 38);
this.picButtons.TabIndex = 4;
//
//cmdClose
//
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Location = new System.Drawing.Point(432, 2);
this.cmdClose.Name = "cmdClose";
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.TabIndex = 5;
this.cmdClose.TabStop = false;
this.cmdClose.Text = "E&xit";
this.cmdClose.UseVisualStyleBackColor = false;
//
//lblHeading
//
this.lblHeading.BackColor = System.Drawing.Color.Transparent;
this.lblHeading.Cursor = System.Windows.Forms.Cursors.Default;
this.lblHeading.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblHeading.ForeColor = System.Drawing.Color.White;
this.lblHeading.Location = new System.Drawing.Point(12, 8);
this.lblHeading.Name = "lblHeading";
this.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblHeading.Size = new System.Drawing.Size(407, 21);
this.lblHeading.TabIndex = 6;
this.lblHeading.Text = "HandHeld StockTake: (Item Barcode, Item Quantity)";
//
//prgUpdate
//
this.prgUpdate.Location = new System.Drawing.Point(84, 72);
this.prgUpdate.Maximum = 1;
this.prgUpdate.Name = "prgUpdate";
this.prgUpdate.Size = new System.Drawing.Size(373, 33);
this.prgUpdate.TabIndex = 3;
//
//Command3
//
this.Command3.BackColor = System.Drawing.SystemColors.Control;
this.Command3.Cursor = System.Windows.Forms.Cursors.Default;
this.Command3.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.Command3.ForeColor = System.Drawing.SystemColors.ControlText;
this.Command3.Location = new System.Drawing.Point(472, 52);
this.Command3.Name = "Command3";
this.Command3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Command3.Size = new System.Drawing.Size(35, 15);
this.Command3.TabIndex = 2;
this.Command3.Text = "...";
this.Command3.UseVisualStyleBackColor = false;
//
//txtFile
//
this.txtFile.AcceptsReturn = true;
this.txtFile.BackColor = System.Drawing.SystemColors.Window;
this.txtFile.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtFile.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtFile.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtFile.Location = new System.Drawing.Point(84, 48);
this.txtFile.MaxLength = 0;
this.txtFile.Name = "txtFile";
this.txtFile.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtFile.Size = new System.Drawing.Size(371, 17);
this.txtFile.TabIndex = 0;
//
//Label2
//
this.Label2.BackColor = System.Drawing.SystemColors.Control;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.Label2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label2.Location = new System.Drawing.Point(8, 50);
this.Label2.Name = "Label2";
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.Size = new System.Drawing.Size(65, 15);
this.Label2.TabIndex = 1;
this.Label2.Text = "File path";
//
//frmExport
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(512, 114);
this.Controls.Add(this.picButtons);
this.Controls.Add(this.prgUpdate);
this.Controls.Add(this.Command3);
this.Controls.Add(this.txtFile);
this.Controls.Add(this.Label2);
this.Controls.Add(this.ShapeContainer1);
this.Cursor = System.Windows.Forms.Cursors.Default;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon");
this.Location = new System.Drawing.Point(3, 22);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmExport";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Import";
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;
using OneApi.Retrievers;
using OneApi.Listeners;
using OneApi.Config;
using OneApi.Model;
using RestSharp;
using OneApi.Exceptions;
namespace OneApi.Client.Impl
{
public class SMSMessagingClientImpl : OneAPIBaseClientImpl, SMSMessagingClient
{
private const string SMS_MESSAGING_OUTBOUND_URL_BASE = "/smsmessaging/outbound";
private const string SMS_MESSAGING_INBOUND_URL_BASE = "/smsmessaging/inbound";
private DeliveryReportRetriever deliveryReportRetriever = null;
private InboundMessageRetriever inboundMessageRetriever = null;
private volatile IList<DeliveryReportListener> deliveryReportPullListenerList = null;
private volatile IList<InboundMessageListener> inboundMessagePullListenerList = null;
private volatile IList<DeliveryStatusNotificationsListener> deliveryStatusNotificationPushListenerList = null;
private volatile IList<InboundMessageNotificationsListener> inboundMessagePushListenerList = null;
private PushServerSimulator dlrStatusPushServerSimulator;
private PushServerSimulator inboundMessagesPushServerSimulator;
//*************************SMSMessagingClientImpl Initialization******************************************************************************************************************************************************
public SMSMessagingClientImpl(Configuration configuration)
: base(configuration)
{
}
//*************************SMSMessagingClientImpl public******************************************************************************************************************************************************
/// <summary>
/// Send an SMS over OneAPI to one or more mobile terminals using the customized 'SMS' object </summary>
/// <param name="sms"> (mandatory) object containing data needed to be filled in order to send the SMS </param>
/// <returns> SendMessageResult </returns>
public SendMessageResult SendSMS(SMSRequest smsRequest)
{
StringBuilder urlBuilder = new StringBuilder(SMS_MESSAGING_OUTBOUND_URL_BASE).Append("/");
urlBuilder.Append(HttpUtility.UrlEncode(smsRequest.SenderAddress));
urlBuilder.Append("/requests");
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.POST, null, smsRequest);
requestData.ContentType = RequestData.JSON_CONTENT_TYPE;
return ExecuteMethod<SendMessageResult>(requestData);
}
/// <summary>
/// Send an SMS asynchronously over OneAPI to one or more mobile terminals using the customized 'SMS' object </summary>
/// <param name="sms"> (mandatory) object containing data needed to be filled in order to send the SMS </param>
/// <param name="callback"> (mandatory) method to call after receiving sent SMS response </param>
public void SendSMSAsync(SMSRequest smsRequest, System.Action<SendMessageResult, RequestException> callback)
{
StringBuilder urlBuilder = new StringBuilder(SMS_MESSAGING_OUTBOUND_URL_BASE).Append("/");
urlBuilder.Append(HttpUtility.UrlEncode(smsRequest.SenderAddress));
urlBuilder.Append("/requests");
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.POST, null, smsRequest);
requestData.ContentType = RequestData.JSON_CONTENT_TYPE;
ExecuteMethodAsync<SendMessageResult>(requestData, callback);
}
/// <summary>
/// Query the delivery status over OneAPI for an SMS sent to one or more mobile terminals </summary>
/// <param name="senderAddress"> (mandatory) is the address from which SMS messages are being sent. Do not URL encode this value prior to passing to this function </param>
/// <param name="requestId"> (mandatory) contains the requestId returned from a previous call to the sendSMS function </param>
/// <returns> DeliveryInfoList </returns>
public DeliveryInfoList QueryDeliveryStatus(string senderAddress, string requestId)
{
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_OUTBOUND_URL_BASE)).Append("/");
urlBuilder.Append(HttpUtility.UrlEncode(senderAddress));
urlBuilder.Append("/requests/");
urlBuilder.Append(HttpUtility.UrlEncode(requestId));
urlBuilder.Append("/deliveryInfos");
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.GET, "deliveryInfoList");
return ExecuteMethod<DeliveryInfoList>(requestData);
}
/// <summary>
/// Query the delivery status asynchronously over OneAPI for an SMS sent to one or more mobile terminals </summary>
/// <param name="senderAddress"> (mandatory) is the address from which SMS messages are being sent. Do not URL encode this value prior to passing to this function </param>
/// <param name="requestId"> (mandatory) contains the requestId returned from a previous call to the sendSMS function </param>
/// <param name="callback"> (mandatory) method to call after receiving delivery status </param>
public void QueryDeliveryStatusAsync(string senderAddress, string requestId, Action<DeliveryInfoList, RequestException> callback)
{
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_OUTBOUND_URL_BASE)).Append("/");
urlBuilder.Append(HttpUtility.UrlEncode(senderAddress));
urlBuilder.Append("/requests/");
urlBuilder.Append(HttpUtility.UrlEncode(requestId));
urlBuilder.Append("/deliveryInfos");
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.GET, "deliveryInfoList");
ExecuteMethodAsync<DeliveryInfoList>(requestData, callback);
}
/// <summary>
/// Convert JSON to Delivery Info Notification </summary>
/// <returns> DeliveryInfoNotification </returns>
public DeliveryInfoNotification ConvertJsonToDeliveryInfoNotification(string json)
{
return ConvertJsonToObject<DeliveryInfoNotification>(json, "deliveryInfoNotification");
}
/// <summary>
/// Start subscribing to delivery status notifications over OneAPI for all your sent SMS </summary>
/// <param name="subscribeToDeliveryNotificationsRequest"> (mandatory) contains delivery notifications subscription data </param>
/// <returns> string - Subscription Id </returns>
public string SubscribeToDeliveryStatusNotifications(SubscribeToDeliveryNotificationsRequest subscribeToDeliveryNotificationsRequest)
{
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_OUTBOUND_URL_BASE)).Append("/");
if (null != subscribeToDeliveryNotificationsRequest.SenderAddress)
{
urlBuilder.Append(HttpUtility.UrlEncode(subscribeToDeliveryNotificationsRequest.SenderAddress)).Append("/");
}
urlBuilder.Append("subscriptions");
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.POST, "deliveryReceiptSubscription", subscribeToDeliveryNotificationsRequest);
DeliveryReceiptSubscription reliveryReceiptSubscription = ExecuteMethod<DeliveryReceiptSubscription>(requestData);
return GetIdFromResourceUrl(reliveryReceiptSubscription.ResourceURL);
}
/// <summary>
/// Get delivery notifications subscriptions by sender address </summary>
/// <param name="senderAddress"> </param>
/// <returns> DeliveryReportSubscription[] </returns>
public DeliveryReportSubscription[] GetDeliveryNotificationsSubscriptionsBySender(string senderAddress)
{
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_OUTBOUND_URL_BASE)).Append("/");
urlBuilder.Append(HttpUtility.UrlEncode(senderAddress));
urlBuilder.Append("/subscriptions");
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.GET, "deliveryReceiptSubscriptions");
return ExecuteMethod<DeliveryReportSubscription[]>(requestData);
}
/// <summary>
/// Get delivery notifications subscriptions by subscription id </summary>
/// <param name="subscriptionId"> </param>
/// <returns> DeliveryReportSubscription </returns>
public DeliveryReportSubscription GetDeliveryNotificationsSubscriptionById(string subscriptionId)
{
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_OUTBOUND_URL_BASE)).Append("/subscriptions/");
urlBuilder.Append(HttpUtility.UrlEncode(subscriptionId));
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.GET, "deliveryReceiptSubscription");
return ExecuteMethod<DeliveryReportSubscription>(requestData);
}
/// <summary>
/// Get delivery notifications subscriptions by for the current user </summary>
/// <returns> DeliveryReportSubscription[] </returns>
public DeliveryReportSubscription[] GetDeliveryNotificationsSubscriptions()
{
RequestData requestData = new RequestData(SMS_MESSAGING_OUTBOUND_URL_BASE + "/subscriptions", Method.GET, "deliveryReceiptSubscriptions");
return ExecuteMethod<DeliveryReportSubscription[]>(requestData);
}
/// <summary>
/// Stop subscribing to delivery status notifications over OneAPI for all your sent SMS </summary>
/// <param name="subscriptionId"> (mandatory) contains the subscriptionId of a previously created SMS delivery receipt subscription </param>
public void RemoveDeliveryNotificationsSubscription(string subscriptionId)
{
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_OUTBOUND_URL_BASE)).Append("/subscriptions/");
urlBuilder.Append(HttpUtility.UrlEncode(subscriptionId));
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.DELETE);
ExecuteMethod(requestData);
}
/// <summary>
/// Get SMS messages sent to your Web application over OneAPI using default 'maxBatchSize' = 100 </summary>
/// <returns> InboundSMSMessageList </returns>
public InboundSMSMessageList GetInboundMessages()
{
return this.GetInboundMessages(100);
}
/// <summary>
/// Get SMS messages sent to your Web application over OneAPI </summary>
/// <param name="maxBatchSize"> (optional) is the maximum number of messages to get in this request </param>
/// <returns> InboundSMSMessageList </returns>
public InboundSMSMessageList GetInboundMessages(int maxBatchSize)
{
//Registration ID is obsolete so any string can be put: e.g. INBOUND
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_INBOUND_URL_BASE)).Append("/registrations/INBOUND/messages");
urlBuilder.Append("?maxBatchSize=");
urlBuilder.Append(HttpUtility.UrlEncode(Convert.ToString(maxBatchSize)));
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.GET, "inboundSMSMessageList");
return ExecuteMethod<InboundSMSMessageList>(requestData);
}
/// <summary>
/// Get asynchronously SMS messages sent to your Web application over OneAPI </summary>
/// <param name="callback"> (mandatory) method to call after receiving inbound messages </param>
public void GetInboundMessagesAsync(Action<InboundSMSMessageList, RequestException> callback)
{
this.GetInboundMessagesAsync(100, callback);
}
/// <summary>
/// Get asynchronously SMS messages sent to your Web application over OneAPI </summary>
/// <param name="maxBatchSize"> (optional) is the maximum number of messages to get in this request </param>
/// <param name="callback"> (mandatory) method to call after receiving inbound messages </param>
public void GetInboundMessagesAsync(int maxBatchSize, Action<InboundSMSMessageList, RequestException> callback)
{
//Registration ID is obsolete so any string can be put: e.g. INBOUND
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_INBOUND_URL_BASE)).Append("/registrations/INBOUND/messages");
urlBuilder.Append("?maxBatchSize=");
urlBuilder.Append(HttpUtility.UrlEncode(Convert.ToString(maxBatchSize)));
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.GET, "inboundSMSMessageList");
ExecuteMethodAsync<InboundSMSMessageList>(requestData, callback);
}
/// <summary>
/// Convert JSON to Inbound SMS Message Notification </summary>
/// <returns> InboundSMSMessageList </returns>
public InboundSMSMessageList ConvertJsonToInboundSMSMessageNotification(string json)
{
return ConvertJsonToObject<InboundSMSMessageList>(json);
}
/// <summary>
/// Start subscribing to notifications of SMS messages sent to your application over OneAPI </summary>
/// <param name="subscribeToInboundMessagesRequest"> (mandatory) contains inbound messages subscription data </param>
/// <returns>string - Subscription Id </returns>
public string SubscribeToInboundMessagesNotifications(SubscribeToInboundMessagesRequest subscribeToInboundMessagesRequest)
{
RequestData requestData = new RequestData(SMS_MESSAGING_INBOUND_URL_BASE + "/subscriptions", Method.POST, "resourceReference", subscribeToInboundMessagesRequest);
ResourceReference resourceReference = ExecuteMethod<ResourceReference>(requestData);
return GetIdFromResourceUrl(resourceReference.ResourceURL);
}
/// <summary>
/// Get inbound messages notifications subscriptions for the current user </summary>
/// <returns> MoSubscription[] </returns>
public MoSubscription[] GetInboundMessagesNotificationsSubscriptions(int page, int pageSize)
{
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_INBOUND_URL_BASE)).Append("/subscriptions");
urlBuilder.Append("?page=");
urlBuilder.Append(HttpUtility.UrlEncode(Convert.ToString(page)));
urlBuilder.Append("&pageSize=");
urlBuilder.Append(HttpUtility.UrlEncode(Convert.ToString(pageSize)));
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.GET, "subscriptions");
return ExecuteMethod<MoSubscription[]>(requestData);
}
/// <summary>
/// Get inbound messages notifications subscriptions for the current user </summary>
/// <returns> MoSubscription[] </returns>
public MoSubscription[] GetInboundMessagesNotificationsSubscriptions()
{
return GetInboundMessagesNotificationsSubscriptions(1, 10);
}
/// <summary>
/// Stop subscribing to message receipt notifications for all your received SMS over OneAPI </summary>
/// <param name="subscriptionId"> (mandatory) contains the subscriptionId of a previously created SMS message receipt subscription </param>
public void RemoveInboundMessagesNotificationsSubscription(string subscriptionId)
{
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_INBOUND_URL_BASE)).Append("/subscriptions/");
urlBuilder.Append(HttpUtility.UrlEncode(subscriptionId));
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.DELETE);
ExecuteMethod(requestData);
}
/// <summary>
/// Get delivery reports
/// </summary>
public DeliveryReportList GetDeliveryReports()
{
return GetDeliveryReports(0);
}
/// <summary>
/// Get delivery reports asynchronously</summary>
/// <param name="callback"> (mandatory) method to call after receiving delivery reports </param>
public void GetDeliveryReportsAsync(Action<DeliveryReportList, RequestException> callback)
{
this.GetDeliveryReportsAsync(0, callback);
}
/// <summary>
/// Get delivery reports </summary>
/// <param name="limit"> </param>
/// <returns> DeliveryReportList </returns>
public DeliveryReportList GetDeliveryReports(int limit)
{
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_OUTBOUND_URL_BASE)).Append("/requests/deliveryReports");
urlBuilder.Append("?limit=");
urlBuilder.Append(HttpUtility.UrlEncode(Convert.ToString(limit)));
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.GET);
return ExecuteMethod<DeliveryReportList>(requestData);
}
/// <summary>
/// Get delivery reports asynchronously</summary>
/// <param name="limit"> </param>
/// <param name="callback"> (mandatory) method to call after receiving delivery reports </param>
public void GetDeliveryReportsAsync(int limit, Action<DeliveryReportList, RequestException> callback)
{
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_OUTBOUND_URL_BASE)).Append("/requests/deliveryReports");
urlBuilder.Append("?limit=");
urlBuilder.Append(HttpUtility.UrlEncode(Convert.ToString(limit)));
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.GET);
ExecuteMethodAsync<DeliveryReportList>(requestData, callback);
}
/// <summary>
/// Get delivery reports by Request Id </summary>
/// <param name="requestId"> </param>
/// <returns> DeliveryReportList </returns>
public DeliveryReportList GetDeliveryReportsByRequestId(string requestId)
{
return GetDeliveryReportsByRequestId(requestId, 0);
}
/// <summary>
/// Get delivery reports asynchronously by Request Id </summary>
/// <param name="requestId"> </param>
/// <param name="callback"> (mandatory) method to call after receiving delivery reports </param>
public void GetDeliveryReportsByRequestIdAsync(string requestId, Action<DeliveryReportList, RequestException> callback)
{
GetDeliveryReportsByRequestIdAsync(requestId, 0, callback);
}
/// <summary>
/// Get delivery reports by Request Id </summary>
/// <param name="requestId"> </param>
/// <param name="limit"> </param>
/// <returns> DeliveryReportList </returns>
public DeliveryReportList GetDeliveryReportsByRequestId(string requestId, int limit)
{
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_OUTBOUND_URL_BASE)).Append("/requests/");
urlBuilder.Append(HttpUtility.UrlEncode(requestId));
urlBuilder.Append("/deliveryReports");
urlBuilder.Append("?limit=");
urlBuilder.Append(HttpUtility.UrlEncode(Convert.ToString(limit)));
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.GET);
return ExecuteMethod<DeliveryReportList>(requestData);
}
/// <summary>
/// Get delivery reports asynchronously by Request Id </summary>
/// <param name="requestId"> </param>
/// <param name="limit"> </param>
/// <param name="callback"> (mandatory) method to call after receiving delivery reports </param>
public void GetDeliveryReportsByRequestIdAsync(string requestId, int limit, Action<DeliveryReportList, RequestException> callback)
{
StringBuilder urlBuilder = (new StringBuilder(SMS_MESSAGING_OUTBOUND_URL_BASE)).Append("/requests/");
urlBuilder.Append(HttpUtility.UrlEncode(requestId));
urlBuilder.Append("/deliveryReports");
urlBuilder.Append("?limit=");
urlBuilder.Append(HttpUtility.UrlEncode(Convert.ToString(limit)));
RequestData requestData = new RequestData(urlBuilder.ToString(), Method.GET);
ExecuteMethodAsync<DeliveryReportList>(requestData, callback);
}
/// <summary>
/// Add OneAPI PULL 'Delivery Reports' listener </summary>
/// <param name="listener"> - (new DeliveryReportListener) </param>
public void AddPullDeliveryReportListener(DeliveryReportListener listener)
{
if (listener == null)
{
return;
}
if (deliveryReportPullListenerList == null)
{
deliveryReportPullListenerList = new List<DeliveryReportListener>();
}
this.deliveryReportPullListenerList.Add(listener);
this.StartDeliveryReportRetriever();
}
/// <summary>
/// Add OneAPI PULL 'INBOUND Messages' listener
/// Messages are pulled automatically depending on the 'inboundMessagesRetrievingInterval' client configuration parameter </summary>
/// <param name="listener"> - (new InboundMessageListener) </param>
public void AddPullInboundMessageListener(InboundMessageListener listener)
{
if (listener == null)
{
return;
}
if (inboundMessagePullListenerList == null)
{
inboundMessagePullListenerList = new List<InboundMessageListener>();
}
this.inboundMessagePullListenerList.Add(listener);
this.StartInboundMessageRetriever();
}
/// <summary>
/// Returns INBOUND Message PULL Listeners list
/// </summary>
public IList<InboundMessageListener> InboundMessagePullListeners
{
get
{
return inboundMessagePullListenerList;
}
}
/// <summary>
/// Returns Delivery Reports PULL Listeners list
/// </summary>
public IList<DeliveryReportListener> DeliveryReportPullListeners
{
get
{
return deliveryReportPullListenerList;
}
}
/// <summary>
/// Remove PULL Delivery Reports listeners and stop retriever
/// </summary>
public void RemovePullDeliveryReportListeners()
{
StopDeliveryReportRetriever();
deliveryReportPullListenerList = null;
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("PULL Delivery Report Listeners are successfully released.");
}
}
/// <summary>
/// Remove PULL INBOUND Messages listeners and stop retriever
/// </summary>
public void RemovePullInboundMessageListeners()
{
StopInboundMessageRetriever();
inboundMessagePullListenerList = null;
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("PULL Inbound Message Listeners are successfully released.");
}
}
/// <summary>
/// Add OneAPI PUSH 'Delivery Status' Notifications listener and start push server simulator </summary>
/// <param name="listener"> - (new DeliveryStatusNotificationListener) </param>
public void AddPushDeliveryStatusNotificationsListener(DeliveryStatusNotificationsListener listener)
{
if (listener == null)
{
return;
}
if (deliveryStatusNotificationPushListenerList == null)
{
deliveryStatusNotificationPushListenerList = new List<DeliveryStatusNotificationsListener>();
}
deliveryStatusNotificationPushListenerList.Add(listener);
StartDlrStatusPushServerSimulator();
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("Listener is successfully added, push server is started and is waiting for Delivery Status Notifications");
}
}
/// <summary>
/// Add OneAPI PUSH 'INBOUND Messages' Notifications listener and start push server simulator
/// <param name="listener"> - (new InboundMessageNotificationsListener) </param>
public void AddPushInboundMessageNotificationsListener(InboundMessageNotificationsListener listener)
{
if (listener == null)
{
return;
}
if (inboundMessagePushListenerList == null)
{
inboundMessagePushListenerList = new List<InboundMessageNotificationsListener>();
}
inboundMessagePushListenerList.Add(listener);
StartInboundMessagesPushServerSimulator();
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("Listener is successfully added, push server is started and is waiting for Inbound Messages Notifications");
}
}
/// <summary>
/// Returns Delivery Status Notifications PUSH Listeners list
/// </summary>
public IList<DeliveryStatusNotificationsListener> DeliveryStatusPushNotificationsListeners
{
get
{
return deliveryStatusNotificationPushListenerList;
}
}
/// <summary>
/// Returns INBOUND Message Notifications PUSH Listeners list
/// </summary>
public IList<InboundMessageNotificationsListener> InboundMessagePushNotificationsListeners
{
get
{
return inboundMessagePushListenerList;
}
}
/// <summary>
/// Remove PUSH Delivery Reports Notifications listeners and stop server
/// </summary>
public void RemovePushDeliveryStatusNotificationsListeners()
{
StopDlrStatusPushServerSimulator();
deliveryStatusNotificationPushListenerList = null;
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("Delivery Status Notification Listeners are successfully removed.");
}
}
/// <summary>
/// Remove PUSH INBOUND Messages Notifications listeners and stop server
/// </summary>
public void RemovePushInboundMessageNotificationsListeners()
{
StopInboundMessagesPushServerSimulator();
inboundMessagePushListenerList = null;
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("Inbound Message Listeners are successfully removed.");
}
}
//*************************SMSMessagingClientImpl private******************************************************************************************************************************************************
/// <summary>
/// START DLR Retriever
/// </summary>
private void StartDeliveryReportRetriever()
{
if (this.deliveryReportRetriever != null)
{
return;
}
this.deliveryReportRetriever = new DeliveryReportRetriever();
int intervalMs = Configuration.DlrRetrievingInterval;
this.deliveryReportRetriever.Start(intervalMs, this);
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("Delivery Report Retriever is successfully started.");
}
}
/// <summary>
/// STOP DLR Retriever
/// </summary>
private void StopDeliveryReportRetriever()
{
if (deliveryReportRetriever == null)
{
return;
}
deliveryReportRetriever.Stop();
deliveryReportRetriever = null;
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("Delivery Report Retriever is successfully stopped.");
}
}
/// <summary>
/// START INBOUND Message Retriever
/// </summary>
private void StartInboundMessageRetriever()
{
if (this.inboundMessageRetriever != null)
{
return;
}
this.inboundMessageRetriever = new InboundMessageRetriever();
int intervalMs = Configuration.InboundMessagesRetrievingInterval;
this.inboundMessageRetriever.Start(intervalMs, this);
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("Inbound Messages Retriever is successfully started.");
}
}
/// <summary>
/// STOP INBOUND Message Retriever
/// </summary>
private void StopInboundMessageRetriever()
{
if (inboundMessageRetriever == null)
{
return;
}
inboundMessageRetriever.Stop();
inboundMessageRetriever = null;
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("Inbound Messages Retriever is successfully stopped.");
}
}
private void StartDlrStatusPushServerSimulator()
{
if (dlrStatusPushServerSimulator == null)
{
dlrStatusPushServerSimulator = new PushServerSimulator(this);
}
dlrStatusPushServerSimulator.Start(Configuration.DlrStatusPushServerPort);
}
private void StopDlrStatusPushServerSimulator()
{
if (dlrStatusPushServerSimulator != null)
{
dlrStatusPushServerSimulator.Stop();
}
}
private void StartInboundMessagesPushServerSimulator()
{
if (inboundMessagesPushServerSimulator == null)
{
inboundMessagesPushServerSimulator = new PushServerSimulator(this);
}
inboundMessagesPushServerSimulator.Start(Configuration.InboundMessagesPushServerSimulatorPort);
}
private void StopInboundMessagesPushServerSimulator()
{
if (inboundMessagesPushServerSimulator != null)
{
inboundMessagesPushServerSimulator.Stop();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using Baseline.Dates;
using Marten.Events.Daemon.HighWater;
using Marten.Events.Daemon.Progress;
using Marten.Events.Daemon.Resiliency;
using Marten.Events.Projections;
using Marten.Exceptions;
using Marten.Services;
using Microsoft.Extensions.Logging;
#nullable enable
namespace Marten.Events.Daemon
{
/// <summary>
/// The main class for running asynchronous projections
/// </summary>
internal class ProjectionDaemon: IProjectionDaemon
{
private readonly Dictionary<string, ShardAgent> _agents = new();
private CancellationTokenSource _cancellation;
private readonly HighWaterAgent _highWater;
private readonly ILogger _logger;
private readonly DocumentStore _store;
private INodeCoordinator? _coordinator;
public ProjectionDaemon(DocumentStore store, IHighWaterDetector detector, ILogger logger)
{
_cancellation = new CancellationTokenSource();
_store = store;
_logger = logger;
Tracker = new ShardStateTracker(logger);
_highWater = new HighWaterAgent(detector, Tracker, logger, store.Options.Projections, _cancellation.Token);
Settings = store.Options.Projections;
}
public ProjectionDaemon(DocumentStore store, ILogger logger) : this(store, new HighWaterDetector(new AutoOpenSingleQueryRunner(store.Tenancy.Default), store.Events), logger)
{
}
public Task UseCoordinator(INodeCoordinator coordinator)
{
_coordinator = coordinator;
return _coordinator.Start(this, _cancellation.Token);
}
public DaemonSettings Settings { get; }
public ShardStateTracker Tracker { get; }
public bool IsRunning => _highWater.IsRunning;
public async Task StartDaemon()
{
await _store.Tenancy.Default.EnsureStorageExistsAsync(typeof(IEvent)).ConfigureAwait(false);
await _highWater.Start().ConfigureAwait(false);
}
public async Task WaitForNonStaleData(TimeSpan timeout)
{
var stopWatch = Stopwatch.StartNew();
var statistics = await _store.Advanced.FetchEventStoreStatistics().ConfigureAwait(false);
while (stopWatch.Elapsed < timeout)
{
if(CurrentShards().All(x => x.Position >= statistics.EventSequenceNumber))
{
return;
}
await Task.Delay(100.Milliseconds()).ConfigureAwait(false);
}
var message = $"The active projection shards did not reach sequence {statistics.EventSequenceNumber} in time";
throw new TimeoutException(message);
}
public async Task StartAllShards()
{
if (!_highWater.IsRunning)
{
await StartDaemon().ConfigureAwait(false);
}
var shards = _store.Options.Projections.AllShards();
foreach (var shard in shards) await StartShard(shard, CancellationToken.None).ConfigureAwait(false);
}
public async Task StartShard(string shardName, CancellationToken token)
{
if (!_highWater.IsRunning)
{
await StartDaemon().ConfigureAwait(false);
}
// Latch it so it doesn't double start
if (_agents.ContainsKey(shardName)) return;
if (_store.Options.Projections.TryFindAsyncShard(shardName, out var shard)) await StartShard(shard, token).ConfigureAwait(false);
}
public async Task StartShard(AsyncProjectionShard shard, CancellationToken cancellationToken)
{
if (!_highWater.IsRunning)
{
await StartDaemon().ConfigureAwait(false);
}
// Don't duplicate the shard
if (_agents.ContainsKey(shard.Name.Identity)) return;
var parameters = new ActionParameters(async () =>
{
try
{
var agent = new ShardAgent(_store, shard, _logger, cancellationToken);
var position = await agent.Start(this).ConfigureAwait(false);
Tracker.Publish(new ShardState(shard.Name, position) {Action = ShardAction.Started});
_agents[shard.Name.Identity] = agent;
}
catch (Exception e)
{
throw new ShardStartException(shard.Name, e);
}
}, cancellationToken);
parameters.LogAction = (logger, ex) =>
{
logger.LogError(ex, "Error when trying to start projection shard '{ShardName}'", shard.Name.Identity);
};
await TryAction(parameters).ConfigureAwait(false);
}
public async Task StopShard(string shardName, Exception? ex = null)
{
if (_agents.TryGetValue(shardName, out var agent))
{
if (agent.IsStopping()) return;
var parameters = new ActionParameters(agent, async () =>
{
try
{
await agent.Stop(ex).ConfigureAwait(false);
_agents.Remove(shardName);
}
catch (Exception e)
{
throw new ShardStopException(agent.ShardName, e);
}
}, _cancellation.Token)
{
LogAction = (logger, exception) =>
{
logger.LogError(exception, "Error when trying to stop projection shard '{ShardName}'",
shardName);
}
};
await TryAction(parameters).ConfigureAwait(false);
}
}
private bool _isStopping = false;
public async Task StopAll()
{
// This avoids issues around whether it was signaled here
// first or through the coordinator first
if (_isStopping) return;
_isStopping = true;
if (_coordinator != null)
{
await _coordinator.Stop().ConfigureAwait(false);
}
_cancellation.Cancel();
await _highWater.Stop().ConfigureAwait(false);
foreach (var agent in _agents.Values)
{
try
{
if (agent.IsStopping()) continue;
await agent.Stop().ConfigureAwait(false);
}
catch (Exception e)
{
_logger.LogError(e, "Error trying to stop shard '{ShardName}'", agent.ShardName.Identity);
}
}
_agents.Clear();
// Need to restart this so that the daemon could
// be restarted later
_cancellation = new CancellationTokenSource();
}
public void Dispose()
{
_coordinator?.Dispose();
Tracker?.As<IDisposable>().Dispose();
_cancellation?.Dispose();
_highWater?.Dispose();
}
public Task RebuildProjection<TView>(CancellationToken token)
{
return RebuildProjection(typeof(TView).Name, token);
}
public Task RebuildProjection(string projectionName, CancellationToken token)
{
if (!_store.Options.Projections.TryFindProjection(projectionName, out var projection))
throw new ArgumentOutOfRangeException(nameof(projectionName),
$"No registered projection matches the name '{projectionName}'. Available names are {_store.Options.Projections.AllProjectionNames().Join(", ")}");
return RebuildProjection(projection, token);
}
public ShardAgent[] CurrentShards()
{
return _agents.Values.ToArray();
}
private async Task RebuildProjection(ProjectionSource source, CancellationToken token)
{
_logger.LogInformation("Starting to rebuild Projection {ProjectionName}", source.ProjectionName);
var running = _agents.Values.Where(x => x.ShardName.ProjectionName == source.ProjectionName).ToArray();
foreach (var agent in running)
{
await agent.Stop().ConfigureAwait(false);
_agents.Remove(agent.ShardName.Identity);
}
if (token.IsCancellationRequested) return;
if (Tracker.HighWaterMark == 0) await _highWater.CheckNow().ConfigureAwait(false);
if (token.IsCancellationRequested) return;
var shards = source.AsyncProjectionShards(_store);
// Teardown the current state
var session = _store.LightweightSession();
await using (session.ConfigureAwait(false))
{
source.Options.Teardown(session);
foreach (var shard in shards)
session.QueueOperation(new DeleteProjectionProgress(_store.Events, shard.Name.Identity));
await session.SaveChangesAsync(token).ConfigureAwait(false);
}
if (token.IsCancellationRequested) return;
#if NET6_0_OR_GREATER
// Is the shard count the optimal DoP here?
await Parallel.ForEachAsync(shards, new ParallelOptions { CancellationToken = token, MaxDegreeOfParallelism = shards.Count },
async (shard, cancellationToken) =>
{
await StartShard(shard, cancellationToken).ConfigureAwait(false);
await Tracker.WaitForShardState(shard.Name, Tracker.HighWaterMark, 5.Minutes()).ConfigureAwait(false);
}).ConfigureAwait(false);
#else
var waiters = shards.Select(async x =>
{
await StartShard(x, token).ConfigureAwait(false);
await Tracker.WaitForShardState(x.Name, Tracker.HighWaterMark, 5.Minutes()).ConfigureAwait(false);
}).ToArray();
await waitForAllShardsToComplete(token, waiters).ConfigureAwait(false);
#endif
foreach (var shard in shards) await StopShard(shard.Name.Identity).ConfigureAwait(false);
}
private static async Task waitForAllShardsToComplete(CancellationToken token, Task[] waiters)
{
var completion = Task.WhenAll(waiters);
var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
using (token.Register(state =>
{
((TaskCompletionSource<object>)state!).TrySetResult(null!);
},
tcs))
{
var resultTask = await Task.WhenAny(completion, tcs.Task).ConfigureAwait(false);
if (resultTask == tcs.Task)
{
// Operation cancelled
throw new OperationCanceledException(token);
}
}
}
internal async Task TryAction(ActionParameters parameters)
{
if (parameters.Delay != default) await Task.Delay(parameters.Delay, parameters.Cancellation).ConfigureAwait(false);
if (parameters.Cancellation.IsCancellationRequested) return;
try
{
await parameters.Action().ConfigureAwait(false);
}
catch (Exception ex)
{
// Get out of here and do nothing if this is just a result of a Task being
// cancelled
if (ex is TaskCanceledException)
{
// Unless this is a parent action of a group action that failed and bailed out w/ a
// TaskCanceledException that is
if (parameters.Group?.Exception is ApplyEventException apply && parameters.GroupActionMode == GroupActionMode.Parent)
{
ex = apply;
}
else
{
return;
}
}
// IF you're using a group, you're using the group's cancellation, and it's going to be
// cancelled already
if (parameters.Group == null && parameters.Cancellation.IsCancellationRequested) return;
parameters.Group?.Abort(ex);
parameters.LogAction(_logger, ex);
var continuation = Settings.DetermineContinuation(ex, parameters.Attempts);
switch (continuation)
{
case RetryLater r:
parameters.IncrementAttempts(r.Delay);
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Retrying in {Milliseconds}", r.Delay.TotalMilliseconds);
}
await TryAction(parameters).ConfigureAwait(false);
break;
case Resiliency.StopShard:
if (parameters.Shard != null) await StopShard(parameters.Shard.ShardName.Identity, ex).ConfigureAwait(false);
break;
case StopAllShards:
#if NET6_0_OR_GREATER
await Parallel.ForEachAsync(_agents.Keys.ToArray(), _cancellation.Token,
async (name, _) => await StopShard(name, ex).ConfigureAwait(false)
).ConfigureAwait(false);
#else
var tasks = _agents.Keys.ToArray().Select(name =>
{
return Task.Run(async () =>
{
await StopShard(name, ex).ConfigureAwait(false);
}, _cancellation.Token);
});
await Task.WhenAll(tasks).ConfigureAwait(false);
#endif
Tracker.Publish(
new ShardState(ShardName.All, Tracker.HighWaterMark)
{
Action = ShardAction.Stopped, Exception = ex
});
break;
case PauseShard pause:
if (parameters.Shard != null) await parameters.Shard.Pause(pause.Delay).ConfigureAwait(false);
break;
case PauseAllShards pauseAll:
#if NET6_0_OR_GREATER
await Parallel.ForEachAsync(_agents.Values.ToArray(), _cancellation.Token,
async (agent, _) => await agent.Pause(pauseAll.Delay).ConfigureAwait(false))
.ConfigureAwait(false);
#else
var tasks2 = _agents.Values.ToArray().Select(agent =>
{
return Task.Run(async () =>
{
await agent.Pause(pauseAll.Delay).ConfigureAwait(false);
}, _cancellation.Token);
});
await Task.WhenAll(tasks2).ConfigureAwait(false);
#endif
break;
case SkipEvent skip:
if (parameters.GroupActionMode == GroupActionMode.Child)
{
// Don't do anything, this has to be retried from the parent
// task
return;
}
await parameters.ApplySkipAsync(skip).ConfigureAwait(false);
_logger.LogInformation("Skipping event #{Sequence} ({EventType}) in shard '{ShardName}'",
skip.Event.Sequence, skip.Event.EventType.GetFullName(), parameters.Shard.Name);
await WriteSkippedEvent(skip.Event, parameters.Shard.Name, (ex as ApplyEventException)!).ConfigureAwait(false);
await TryAction(parameters).ConfigureAwait(false);
break;
case DoNothing:
// Don't do anything.
break;
}
}
}
internal async Task WriteSkippedEvent(IEvent @event, ShardName shardName, ApplyEventException exception)
{
try
{
var deadLetterEvent = new DeadLetterEvent(@event, shardName, exception);
var session = _store.LightweightSession();
await using (session.ConfigureAwait(false))
{
session.Store(deadLetterEvent);
await session.SaveChangesAsync().ConfigureAwait(false);
}
}
catch (Exception e)
{
_logger.LogError(e, "Failed to write dead letter event {Event} to shard {ShardName}", @event,
shardName);
}
}
public AgentStatus StatusFor(string shardName)
{
return _agents.TryGetValue(shardName, out var agent)
? agent.Status
: AgentStatus.Stopped;
}
public Task WaitForShardToStop(string shardName, TimeSpan? timeout = null)
{
if (StatusFor(shardName) == AgentStatus.Stopped) return Task.CompletedTask;
bool IsStopped(ShardState s)
{
return s.ShardName.EqualsIgnoreCase(shardName) && s.Action == ShardAction.Stopped;
}
return Tracker.WaitForShardCondition(IsStopped, $"{shardName} is Stopped", timeout);
}
}
}
| |
using System;
using Microsoft.Xna.Framework.Input;
namespace DuckGame
{
// Token: 0x0200049A RID: 1178
public class Mouse : InputDevice
{
// Token: 0x060020D2 RID: 8402 RVA: 0x00139D20 File Offset: 0x00137F20
public override void Update()
{
Mouse._mouseStatePrev = Mouse._mouseState;
Mouse._mouseState = Mouse.GetState();
Vec3 mousePos = new Vec3((float)Mouse._mouseState.X, (float)Mouse._mouseState.Y, 0f);
Mouse._mouseScreenPos = new Vec2(mousePos.x / (float)Graphics.width * Layer.HUD.camera.width, mousePos.y / (float)Graphics.height * Layer.HUD.camera.height);
Mouse._mouseScreenPos.x = (float)((int)Mouse._mouseScreenPos.x);
Mouse._mouseScreenPos.y = (float)((int)Mouse._mouseScreenPos.y);
Mouse._mousePos = new Vec2((float)Mouse._mouseState.X, (float)Mouse._mouseState.Y);
}
// Token: 0x17000601 RID: 1537
// (get) Token: 0x060020D3 RID: 8403 RVA: 0x00139DF8 File Offset: 0x00137FF8
public static InputState left
{
get
{
if (Mouse._mouseState.LeftButton == ButtonState.Pressed && Mouse._mouseStatePrev.LeftButton == ButtonState.Released)
{
return InputState.Pressed;
}
if (Mouse._mouseState.LeftButton == ButtonState.Pressed && Mouse._mouseStatePrev.LeftButton == ButtonState.Pressed)
{
return InputState.Down;
}
if (Mouse._mouseState.LeftButton == ButtonState.Released && Mouse._mouseStatePrev.LeftButton == ButtonState.Pressed)
{
return InputState.Released;
}
return InputState.None;
}
}
// Token: 0x17000602 RID: 1538
// (get) Token: 0x060020D4 RID: 8404 RVA: 0x00139E58 File Offset: 0x00138058
public static InputState middle
{
get
{
if (Mouse._mouseState.MiddleButton == ButtonState.Pressed && Mouse._mouseStatePrev.MiddleButton == ButtonState.Released)
{
return InputState.Pressed;
}
if (Mouse._mouseState.MiddleButton == ButtonState.Pressed && Mouse._mouseStatePrev.MiddleButton == ButtonState.Pressed)
{
return InputState.Down;
}
if (Mouse._mouseState.MiddleButton == ButtonState.Released && Mouse._mouseStatePrev.MiddleButton == ButtonState.Pressed)
{
return InputState.Released;
}
return InputState.None;
}
}
// Token: 0x17000603 RID: 1539
// (get) Token: 0x060020D5 RID: 8405 RVA: 0x00139EB8 File Offset: 0x001380B8
public static InputState right
{
get
{
if (Mouse._mouseState.RightButton == ButtonState.Pressed && Mouse._mouseStatePrev.RightButton == ButtonState.Released)
{
return InputState.Pressed;
}
if (Mouse._mouseState.RightButton == ButtonState.Pressed && Mouse._mouseStatePrev.RightButton == ButtonState.Pressed)
{
return InputState.Down;
}
if (Mouse._mouseState.RightButton == ButtonState.Released && Mouse._mouseStatePrev.RightButton == ButtonState.Pressed)
{
return InputState.Released;
}
return InputState.None;
}
}
// Token: 0x17000604 RID: 1540
// (get) Token: 0x060020D6 RID: 8406 RVA: 0x000033E5 File Offset: 0x000015E5
public static bool available
{
get
{
return true;
}
}
// Token: 0x17000605 RID: 1541
// (get) Token: 0x060020D7 RID: 8407 RVA: 0x00016E52 File Offset: 0x00015052
public static float scroll
{
get
{
return (float)(Mouse._mouseStatePrev.ScrollWheelValue - Mouse._mouseState.ScrollWheelValue);
}
}
// Token: 0x17000606 RID: 1542
// (get) Token: 0x060020D8 RID: 8408 RVA: 0x00016E6A File Offset: 0x0001506A
public static float x
{
get
{
return Mouse._mouseScreenPos.x;
}
}
// Token: 0x17000607 RID: 1543
// (get) Token: 0x060020D9 RID: 8409 RVA: 0x00016E76 File Offset: 0x00015076
public static float y
{
get
{
return Mouse._mouseScreenPos.y;
}
}
// Token: 0x17000608 RID: 1544
// (get) Token: 0x060020DA RID: 8410 RVA: 0x00016E82 File Offset: 0x00015082
public static float xScreen
{
get
{
return Mouse.positionScreen.x;
}
}
// Token: 0x17000609 RID: 1545
// (get) Token: 0x060020DB RID: 8411 RVA: 0x00016E8E File Offset: 0x0001508E
public static float yScreen
{
get
{
return Mouse.positionScreen.y;
}
}
// Token: 0x1700060A RID: 1546
// (get) Token: 0x060020DC RID: 8412 RVA: 0x00016E9A File Offset: 0x0001509A
public static float xConsole
{
get
{
return Mouse.positionConsole.x;
}
}
// Token: 0x1700060B RID: 1547
// (get) Token: 0x060020DD RID: 8413 RVA: 0x00016EA6 File Offset: 0x000150A6
public static float yConsole
{
get
{
return Mouse.positionConsole.y;
}
}
// Token: 0x1700060C RID: 1548
// (get) Token: 0x060020DE RID: 8414 RVA: 0x00016EB2 File Offset: 0x000150B2
public static Vec2 position
{
get
{
return new Vec2(Mouse.x, Mouse.y);
}
}
// Token: 0x1700060D RID: 1549
// (get) Token: 0x060020DF RID: 8415 RVA: 0x00016EC3 File Offset: 0x000150C3
public static Vec2 mousePos
{
get
{
return Mouse._mousePos;
}
}
// Token: 0x1700060E RID: 1550
// (get) Token: 0x060020E0 RID: 8416 RVA: 0x00016ECA File Offset: 0x000150CA
public static Vec2 positionScreen
{
get
{
return Level.current.camera.transformScreenVector(Mouse._mousePos);
}
}
// Token: 0x1700060F RID: 1551
// (get) Token: 0x060020E1 RID: 8417 RVA: 0x00016EE0 File Offset: 0x000150E0
public static Vec2 positionConsole
{
get
{
return Layer.Console.camera.transformScreenVector(Mouse._mousePos);
}
}
// Token: 0x060020E2 RID: 8418 RVA: 0x0000AE1C File Offset: 0x0000901C
public Mouse() : base(0)
{
}
// Token: 0x04001F71 RID: 8049
private static Vec2 _mousePos;
// Token: 0x04001F72 RID: 8050
private static Vec2 _mouseScreenPos;
// Token: 0x04001F73 RID: 8051
private static MouseState _mouseState;
// Token: 0x04001F74 RID: 8052
private static MouseState _mouseStatePrev;
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 11/17/2008 8:35:34 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using DotSpatial.Data;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// LabelLayer
/// </summary>
public class LabelLayer : Layer, ILabelLayer
{
#region Events
/// <summary>
/// Occurs after the selection has been cleared
/// </summary>
public event EventHandler<FeatureChangeArgs> SelectionCleared;
/// <summary>
/// Occurs after the selection is updated by the addition of new members
/// </summary>
public event EventHandler<FeatureChangeEnvelopeArgs> SelectionExtended;
#endregion
#region Private Variables
private IFeatureLayer _featureLayer;
[Serialize("Symbology")]
private ILabelScheme _symbology;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of LabelLayer
/// </summary>
public LabelLayer()
{
Configure();
}
/// <summary>
/// Creates a new layer that uses the attributes from the given featureSet
/// </summary>
/// <param name="inFeatureSet"></param>
public LabelLayer(IFeatureSet inFeatureSet)
{
FeatureSet = inFeatureSet;
Configure();
}
/// <summary>
/// Creates a new label layer based on the features in the
/// </summary>
/// <param name="inFeatureLayer"></param>
public LabelLayer(IFeatureLayer inFeatureLayer)
{
FeatureSet = inFeatureLayer.DataSet;
_featureLayer = inFeatureLayer;
Configure();
}
private void Configure()
{
if (FeatureSet != null) MyExtent = FeatureSet.Extent.Copy();
_symbology = new LabelScheme();
}
#endregion
#region Methods
/// <summary>
/// Clears the current selection, reverting the geometries back to their
/// normal colors.
/// </summary>
public void ClearSelection()
{
}
/// <summary>
/// This builds the _drawnStates based on the current label scheme.
/// </summary>
public virtual void CreateLabels()
{
if (FeatureSet != null)
{
if (FeatureSet.IndexMode)
{
CreateIndexedLabels();
return;
}
}
DrawnStates = new Dictionary<IFeature, LabelDrawState>();
if (FeatureSet == null) return;
//DataTable dt = _featureSet.DataTable; // if working correctly, this should auto-populate
if (Symbology == null) return;
foreach (ILabelCategory category in Symbology.Categories)
{
List<IFeature> features;
if (!string.IsNullOrWhiteSpace(category.FilterExpression))
features = FeatureSet.SelectByAttribute(category.FilterExpression);
else
features = FeatureSet.Features.ToList();
foreach (IFeature feature in features)
{
if (DrawnStates.ContainsKey(feature))
DrawnStates[feature] = new LabelDrawState(category);
else
DrawnStates.Add(feature, new LabelDrawState(category));
}
}
}
/// <summary>
/// Highlights the values from a specified region. This will not unselect any members,
/// so if you want to select a new region instead of an old one, first use ClearSelection.
/// This is the default selection that only tests the anchor point, not the entire label.
/// </summary>
/// <param name="region">An Envelope showing a 3D selection box for intersection testing.</param>
/// <returns>True if any members were added to the current selection.</returns>
public bool Select(Extent region)
{
List<IFeature> features = FeatureSet.Select(region);
if (features.Count == 0) return false;
foreach (IFeature feature in features)
{
DrawnStates[feature].Selected = true;
}
return true;
}
/// <summary>
/// This builds the _drawnStates based on the current label scheme.
/// </summary>
protected void CreateIndexedLabels()
{
if (FeatureSet == null) return;
FastDrawnStates = new FastLabelDrawnState[FeatureSet.ShapeIndices.Count];
//DataTable dt = _featureSet.DataTable; // if working correctly, this should auto-populate
if (Symbology == null) return;
foreach (ILabelCategory category in Symbology.Categories)
{
if (category.FilterExpression != null)
{
List<int> features = FeatureSet.SelectIndexByAttribute(category.FilterExpression);
foreach (int feature in features)
{
FastDrawnStates[feature] = new FastLabelDrawnState(category);
}
}
else
{
for (int i = 0; i < FastDrawnStates.Length; i++)
{
FastDrawnStates[i] = new FastLabelDrawnState(category);
}
}
}
}
/// <summary>
/// Removes the features in the given region
/// </summary>
/// <param name="region">the geographic region to remove the feature from the selection on this layer</param>
/// <returns>Boolean true if any features were removed from the selection.</returns>
public bool UnSelect(Extent region)
{
List<IFeature> features = FeatureSet.Select(region);
if (features.Count == 0) return false;
foreach (IFeature feature in features)
{
DrawnStates[feature].Selected = false;
}
return true;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the dictionary that quickly identifies the category for
/// each label.
/// </summary>
[ShallowCopy]
public Dictionary<IFeature, LabelDrawState> DrawnStates { get; set; }
/// <summary>
/// Gets or sets the indexed collection of drawn states
/// </summary>
public FastLabelDrawnState[] FastDrawnStates { get; set; }
/// <summary>
/// Gets or sets the featureSet that defines the text for the labels on this layer.
/// </summary>
[ShallowCopy]
public IFeatureSet FeatureSet { get; set; }
/// <summary>
/// Gets or sets an optional layer to link this layer to. If this is specified, then drawing will
/// be associated with this layer. This also updates the FeatureSet property.
/// </summary>
[ShallowCopy]
public IFeatureLayer FeatureLayer
{
get { return _featureLayer; }
set
{
_featureLayer = value;
FeatureSet = _featureLayer.DataSet;
}
}
/// <summary>
/// Gets or sets the labeling scheme as a collection of categories.
/// </summary>
public ILabelScheme Symbology
{
get { return _symbology; }
set
{
_symbology = value;
CreateLabels(); // update the drawn state with the new categories
}
}
/// <summary>
/// Gets or sets the selection symbolizer from the first TextSymbol group.
/// </summary>
[ShallowCopy]
public ILabelSymbolizer SelectionSymbolizer
{
get
{
if (_symbology == null) return null;
if (_symbology.Categories == null) return null;
if (_symbology.Categories.Count == 0) return null;
return _symbology.Categories[0].SelectionSymbolizer;
}
set
{
if (_symbology == null) _symbology = new LabelScheme();
if (_symbology.Categories == null) _symbology.Categories = new BaseList<ILabelCategory>();
if (_symbology.Categories.Count == 0) _symbology.Categories.Add(new LabelCategory());
_symbology.Categories[0].SelectionSymbolizer = value;
}
}
/// <summary>
/// Gets or sets the regular symbolizer from the first TextSymbol group.
/// </summary>
[ShallowCopy]
public ILabelSymbolizer Symbolizer
{
get
{
if (_symbology == null) return null;
if (_symbology.Categories == null) return null;
if (_symbology.Categories.Count == 0) return null;
return _symbology.Categories[0].Symbolizer;
}
set
{
if (_symbology == null) _symbology = new LabelScheme();
if (_symbology.Categories == null) _symbology.Categories = new BaseList<ILabelCategory>();
if (_symbology.Categories.Count == 0) _symbology.Categories.Add(new LabelCategory());
_symbology.Categories[0].Symbolizer = value;
}
}
#endregion
#region Protected Methods
/// <summary>
/// Fires the selection cleared event
/// </summary>
protected virtual void OnSelectionCleared(FeatureChangeArgs args)
{
if (SelectionCleared != null) SelectionCleared(this, args);
}
/// <summary>
/// Fires the selection extended event
/// </summary>
/// <param name="args"></param>
protected virtual void OnSelectionExtended(FeatureChangeEnvelopeArgs args)
{
if (SelectionExtended != null) SelectionExtended(this, args);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using Xunit;
namespace Ignitor
{
public class RenderBatchReaderTest
{
static readonly object NullStringMarker = new object();
// All of these tests are copies from the RenderBatchWriterTest but converted to be round-trippable tests.
[Fact]
public void CanRoundTripEmptyRenderBatch()
{
// Arrange/Act
var bytes = RoundTripSerialize(new RenderBatch());
// Assert
AssertBinaryContents(bytes, /* startIndex */ 0,
0, // Length of UpdatedComponents
0, // Length of ReferenceFrames
0, // Length of DisposedComponentIds
0, // Length of DisposedEventHandlerIds
0, // Index of UpdatedComponents
4, // Index of ReferenceFrames
8, // Index of DisposedComponentIds
12, // Index of DisposedEventHandlerIds
16 // Index of Strings
);
Assert.Equal(36, bytes.Length); // No other data
}
[Fact]
public void CanRoundTripUpdatedComponentsWithEmptyEdits()
{
// Arrange/Act
var bytes = RoundTripSerialize(new RenderBatch(
new ArrayRange<RenderTreeDiff>(new[]
{
new RenderTreeDiff(123, default),
new RenderTreeDiff(int.MaxValue, default),
}, 2),
default,
default,
default));
// Assert
AssertBinaryContents(bytes, /* startIndex */ 0,
// UpdatedComponents[0]
123, // ComponentId
0, // Edits length
// UpdatedComponents[1]
int.MaxValue, // ComponentId
0, // Edits length
2, // Length of UpdatedComponents
0, // Index of UpdatedComponents[0]
8, // Index of UpdatedComponents[1]
0, // Length of ReferenceFrames
0, // Length of DisposedComponentIds
0, // Length of DisposedEventHandlerIds
16, // Index of UpdatedComponents
28, // Index of ReferenceFrames
32, // Index of DisposedComponentIds
36, // Index of DisposedEventHandlerIds
40 // Index of strings
);
Assert.Equal(60, bytes.Length); // No other data
}
[Fact]
public void CanRoundTripEdits()
{
// Arrange/Act
var edits = new[]
{
default, // Skipped (because offset=1 below)
RenderTreeEdit.PrependFrame(456, 789),
RenderTreeEdit.RemoveFrame(101),
RenderTreeEdit.SetAttribute(102, 103),
RenderTreeEdit.RemoveAttribute(104, "Some removed attribute"),
RenderTreeEdit.UpdateText(105, 106),
RenderTreeEdit.StepIn(107),
RenderTreeEdit.StepOut(),
RenderTreeEdit.UpdateMarkup(108, 109),
RenderTreeEdit.RemoveAttribute(110, "Some removed attribute"), // To test deduplication
};
var editsBuilder = new ArrayBuilder<RenderTreeEdit>();
editsBuilder.Append(edits, 0, edits.Length);
var editsSegment = editsBuilder.ToSegment(1, edits.Length); // Skip first to show offset is respected
var bytes = RoundTripSerialize(new RenderBatch(
new ArrayRange<RenderTreeDiff>(new[]
{
new RenderTreeDiff(123, editsSegment)
}, 1),
default,
default,
default));
// Assert
var diffsStartIndex = ReadInt(bytes, bytes.Length - 20);
AssertBinaryContents(bytes, diffsStartIndex,
1, // Number of diffs
0); // Index of diffs[0]
AssertBinaryContents(bytes, 0,
123, // Component ID for diff 0
9, // diff[0].Edits.Count
RenderTreeEditType.PrependFrame, 456, 789, NullStringMarker,
RenderTreeEditType.RemoveFrame, 101, 0, NullStringMarker,
RenderTreeEditType.SetAttribute, 102, 103, NullStringMarker,
RenderTreeEditType.RemoveAttribute, 104, 0, "Some removed attribute",
RenderTreeEditType.UpdateText, 105, 106, NullStringMarker,
RenderTreeEditType.StepIn, 107, 0, NullStringMarker,
RenderTreeEditType.StepOut, 0, 0, NullStringMarker,
RenderTreeEditType.UpdateMarkup, 108, 109, NullStringMarker,
RenderTreeEditType.RemoveAttribute, 110, 0, "Some removed attribute"
);
// We can deduplicate attribute names
Assert.Equal(new[] { "Some removed attribute" }, ReadStringTable(bytes));
}
[Fact]
public void CanRoundTripReferenceFrames()
{
// Arrange/Act
var bytes = RoundTripSerialize(new RenderBatch(
default,
new ArrayRange<RenderTreeFrame>(new[] {
RenderTreeFrame.Attribute(123, "Attribute with string value", "String value"),
RenderTreeFrame.Attribute(124, "Attribute with nonstring value", 1),
RenderTreeFrame.Attribute(125, "Attribute with delegate value", new Action(() => { }))
.WithAttributeEventHandlerId((ulong)uint.MaxValue + 1),
RenderTreeFrame.ChildComponent(126, typeof(object))
.WithComponentSubtreeLength(5678)
.WithComponent(new ComponentState(2000)),
RenderTreeFrame.ComponentReferenceCapture(127, value => { }, 1001),
RenderTreeFrame.Element(128, "Some element")
.WithElementSubtreeLength(1234),
RenderTreeFrame.ElementReferenceCapture(129, value => { })
.WithElementReferenceCaptureId("my unique ID"),
RenderTreeFrame.Region(130)
.WithRegionSubtreeLength(1234),
RenderTreeFrame.Text(131, "Some text"),
RenderTreeFrame.Markup(132, "Some markup"),
RenderTreeFrame.Text(133, "\n\t "),
// Testing deduplication
RenderTreeFrame.Attribute(134, "Attribute with string value", "String value"),
RenderTreeFrame.Element(135, "Some element") // Will be deduplicated
.WithElementSubtreeLength(999),
RenderTreeFrame.Text(136, "Some text"), // Will not be deduplicated
RenderTreeFrame.Markup(137, "Some markup"), // Will not be deduplicated
RenderTreeFrame.Text(138, "\n\t "), // Will be deduplicated
}, 16),
default,
default));
// Assert
var referenceFramesStartIndex = ReadInt(bytes, bytes.Length - 16);
AssertBinaryContents(bytes, referenceFramesStartIndex,
16, // Number of frames
RenderTreeFrameType.Attribute, "Attribute with string value", "String value", 0, 0,
RenderTreeFrameType.Attribute, "Attribute with nonstring value", NullStringMarker, 0, 0,
RenderTreeFrameType.Attribute, "Attribute with delegate value", NullStringMarker, (ulong)uint.MaxValue + 1,
RenderTreeFrameType.Component, 5678, 2000, 0, 0,
RenderTreeFrameType.ComponentReferenceCapture, 0, 0, 0, 0,
RenderTreeFrameType.Element, 1234, "Some element", 0, 0,
RenderTreeFrameType.ElementReferenceCapture, "my unique ID", 0, 0, 0,
RenderTreeFrameType.Region, 1234, 0, 0, 0,
RenderTreeFrameType.Text, "Some text", 0, 0, 0,
RenderTreeFrameType.Markup, "Some markup", 0, 0, 0,
RenderTreeFrameType.Text, "\n\t ", 0, 0, 0,
RenderTreeFrameType.Attribute, "Attribute with string value", "String value", 0, 0,
RenderTreeFrameType.Element, 999, "Some element", 0, 0,
RenderTreeFrameType.Text, "Some text", 0, 0, 0,
RenderTreeFrameType.Markup, "Some markup", 0, 0, 0,
RenderTreeFrameType.Text, "\n\t ", 0, 0, 0
);
Assert.Equal(new[]
{
"Attribute with string value",
"String value",
"Attribute with nonstring value",
"Attribute with delegate value",
"Some element",
"my unique ID",
"Some text",
"Some markup",
"\n\t ",
"String value",
"Some text",
"Some markup",
}, ReadStringTable(bytes));
}
private Span<byte> RoundTripSerialize(RenderBatch renderBatch)
{
var bytes = Serialize(renderBatch);
var roundTrippedRenderBatch = RenderBatchReader.Read(bytes);
var roundTrippedBytes = Serialize(roundTrippedRenderBatch);
return roundTrippedBytes;
Span<byte> Serialize(RenderBatch batch)
{
using (var ms = new MemoryStream())
using (var writer = new RenderBatchWriter(ms, leaveOpen: false))
{
writer.Write(batch);
return new Span<byte>(ms.ToArray(), 0, (int)ms.Length);
}
}
}
static string[] ReadStringTable(Span<byte> data)
{
var bytes = data.ToArray();
// The string table position is given by the final int, and continues
// until we get to the final set of top-level indices
var stringTableStartPosition = ReadInt(bytes, bytes.Length - 4);
var stringTableEndPositionExcl = bytes.Length - 20;
var result = new List<string>();
for (var entryPosition = stringTableStartPosition;
entryPosition < stringTableEndPositionExcl;
entryPosition += 4)
{
// The string table entries are all length-prefixed UTF8 blobs
var tableEntryPos = ReadInt(bytes, entryPosition);
var length = (int)ReadUnsignedLEB128(bytes, tableEntryPos, out var numLEB128Bytes);
var value = Encoding.UTF8.GetString(bytes, tableEntryPos + numLEB128Bytes, length);
result.Add(value);
}
return result.ToArray();
}
static void AssertBinaryContents(Span<byte> data, int startIndex, params object[] entries)
{
var bytes = data.ToArray();
var stringTableEntries = ReadStringTable(data);
using (var ms = new MemoryStream(bytes))
using (var reader = new BinaryReader(ms))
{
ms.Seek(startIndex, SeekOrigin.Begin);
foreach (var expectedEntryIterationVar in entries)
{
// Assume enums are represented as ints
var expectedEntry = expectedEntryIterationVar.GetType().IsEnum
? Convert.ToInt32(expectedEntryIterationVar, CultureInfo.InvariantCulture)
: expectedEntryIterationVar;
if (expectedEntry is int expectedInt)
{
Assert.Equal(expectedInt, reader.ReadInt32());
}
else if (expectedEntry is ulong expectedUlong)
{
Assert.Equal(expectedUlong, reader.ReadUInt64());
}
else if (expectedEntry is string || expectedEntry == NullStringMarker)
{
// For strings, we have to look up the value in the table of strings
// that appears at the end of the serialized data
var indexIntoStringTable = reader.ReadInt32();
var expectedString = expectedEntry as string;
if (expectedString == null)
{
Assert.Equal(-1, indexIntoStringTable);
}
else
{
Assert.Equal(expectedString, stringTableEntries[indexIntoStringTable]);
}
}
else
{
throw new InvalidOperationException($"Unsupported type: {expectedEntry.GetType().FullName}");
}
}
}
}
static int ReadInt(Span<byte> bytes, int startOffset)
=> BinaryPrimitives.ReadInt32LittleEndian(bytes.Slice(startOffset, 4));
public static uint ReadUnsignedLEB128(byte[] bytes, int startOffset, out int numBytesRead)
{
var result = (uint)0;
var shift = 0;
var currentByte = (byte)128;
numBytesRead = 0;
for (var count = 0; count < 4 && currentByte >= 128; count++)
{
currentByte = bytes[startOffset + count];
result += (uint)(currentByte & 0x7f) << shift;
shift += 7;
numBytesRead++;
}
return result;
}
}
}
| |
// This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using System.Collections;
using System;
using System.Linq;
using MoonSharp.Interpreter;
using MoonSharp.VsCodeDebugger;
namespace Fungus
{
/// <summary>
/// Wrapper for a MoonSharp Lua Script instance.
/// A debug server is started automatically when running in the Unity Editor. Use VS Code to debug Lua scripts.
/// </summary>
public class LuaEnvironment : MonoBehaviour
{
[Tooltip("Start a Lua debug server on scene start.")]
[SerializeField] protected bool startDebugServer = true;
[Tooltip("Port to use for the Lua debug server.")]
[SerializeField] protected int debugServerPort = 41912;
/// <summary>
/// The MoonSharp interpreter instance.
/// </summary>
protected Script interpreter;
/// <summary>
/// Flag used to avoid startup dependency issues.
/// </summary>
protected bool initialised = false;
protected virtual void Start()
{
InitEnvironment();
}
/// <summary>
/// Detach the MoonSharp script from the debugger.
/// </summary>
protected virtual void OnDestroy()
{
if (DebugServer != null)
{
DebugServer.Detach(interpreter);
}
}
/// <summary>
/// Register all Lua files in the project so they can be accessed at runtime.
/// </summary>
protected virtual void InitLuaScriptFiles()
{
object[] result = Resources.LoadAll("Lua", typeof(TextAsset));
interpreter.Options.ScriptLoader = new LuaScriptLoader(result.OfType<TextAsset>());
}
/// <summary>
/// A Unity coroutine method which updates a Lua coroutine each frame.
/// <param name="closure">A MoonSharp closure object representing a function.</param>
/// <param name="onComplete">A delegate method that is called when the coroutine completes. Includes return parameter.</param>
/// </summary>
protected virtual IEnumerator RunLuaCoroutine(Closure closure, Action<DynValue> onComplete = null)
{
DynValue co = interpreter.CreateCoroutine(closure);
DynValue returnValue = null;
while (co.Coroutine.State != CoroutineState.Dead)
{
try
{
returnValue = co.Coroutine.Resume();
}
catch (InterpreterException ex)
{
LogException(ex.DecoratedMessage, GetSourceCode());
}
yield return null;
}
if (onComplete != null)
{
onComplete(returnValue);
}
}
protected virtual string GetSourceCode()
{
// Get most recently executed source code
string sourceCode = "";
if (interpreter.SourceCodeCount > 0)
{
MoonSharp.Interpreter.Debugging.SourceCode sc = interpreter.GetSourceCode(interpreter.SourceCodeCount - 1);
if (sc != null)
{
sourceCode = sc.Code;
}
}
return sourceCode;
}
/// <summary>
/// Starts a standard Unity coroutine.
/// The coroutine is managed by the LuaEnvironment monobehavior, so you can call StopAllCoroutines to
/// stop all active coroutines later.
/// </summary>
protected virtual IEnumerator RunUnityCoroutineImpl(IEnumerator coroutine)
{
if (coroutine == null)
{
UnityEngine.Debug.LogWarning("Coroutine must not be null");
yield break;
}
yield return StartCoroutine(coroutine);
}
/// <summary>
/// Writes a MoonSharp exception to the debug log in a helpful format.
/// </summary>
/// <param name="decoratedMessage">Decorated message from a MoonSharp exception</param>
/// <param name="debugInfo">Debug info, usually the Lua script that was running.</param>
protected static void LogException(string decoratedMessage, string debugInfo)
{
string output = decoratedMessage + "\n";
char[] separators = { '\r', '\n' };
string[] lines = debugInfo.Split(separators, StringSplitOptions.None);
// Show line numbers for script listing
int count = 1;
foreach (string line in lines)
{
output += count.ToString() + ": " + line + "\n";
count++;
}
UnityEngine.Debug.LogError(output);
}
#region Public members
/// <summary>
/// Instance of VS Code debug server when debugging option is enabled.
/// </summary>
public static MoonSharpVsCodeDebugServer DebugServer { get; private set; }
/// <summary>
/// Returns the first Lua Environment found in the scene, or creates one if none exists.
/// This is a slow operation, call it once at startup and cache the returned value.
/// </summary>
public static LuaEnvironment GetLua()
{
var luaEnv = GameObject.FindObjectOfType<LuaEnvironment>();
if (luaEnv == null)
{
GameObject prefab = Resources.Load<GameObject>("Prefabs/LuaEnvironment");
if (prefab != null)
{
GameObject go = Instantiate(prefab) as GameObject;
go.name = "LuaEnvironment";
luaEnv = go.GetComponent<LuaEnvironment>();
}
}
return luaEnv;
}
/// <summary>
/// Register a type given it's assembly qualified name.
/// </summary>
public static void RegisterType(string typeName, bool extensionType = false)
{
System.Type t = null;
try
{
t = System.Type.GetType(typeName);
}
catch
{}
if (t == null)
{
UnityEngine.Debug.LogWarning("Type not found: " + typeName);
return;
}
// Registering System.Object breaks MoonSharp's automated conversion of Lists and Dictionaries to Lua tables.
if (t == typeof(System.Object))
{
return;
}
if (!UserData.IsTypeRegistered(t))
{
try
{
if (extensionType)
{
UserData.RegisterExtensionType(t);
}
else
{
UserData.RegisterType(t);
}
}
catch (ArgumentException ex)
{
UnityEngine.Debug.LogWarning(ex.Message);
}
}
}
/// <summary>
/// Start a Unity coroutine from a Lua call.
/// </summary>
public virtual Task RunUnityCoroutine(IEnumerator coroutine)
{
if (coroutine == null)
{
return null;
}
// We use the Task class so we can poll the coroutine to check if it has finished.
// Standard Unity coroutines don't support this check.
return new Task(RunUnityCoroutineImpl(coroutine));
}
/// <summary>
/// Initialise the Lua interpreter so we can start running Lua code.
/// </summary>
public virtual void InitEnvironment()
{
if (initialised)
{
return;
}
Script.DefaultOptions.DebugPrint = (s) => { UnityEngine.Debug.Log(s); };
// In some use cases (e.g. downloadable Lua files) some Lua modules can pose a potential security risk.
// You can restrict which core lua modules are available here if needed. See the MoonSharp documentation for details.
interpreter = new Script(CoreModules.Preset_Complete);
// Load all Lua scripts in the project
InitLuaScriptFiles();
// Initialize any attached initializer components (e.g. LuaUtils)
LuaEnvironmentInitializer[] initializers = GetComponents<LuaEnvironmentInitializer>();
foreach (LuaEnvironmentInitializer initializer in initializers)
{
initializer.Initialize();
}
//
// Change this to #if UNITY_STANDALONE if you want to debug a standalone build.
//
#if UNITY_EDITOR
if (startDebugServer &&
DebugServer == null)
{
// Create the debugger server
DebugServer = new MoonSharpVsCodeDebugServer(debugServerPort);
// Start the debugger server
DebugServer.Start();
// Attach the MoonSharp script to the debugger
DebugServer.AttachToScript(interpreter, gameObject.name);
}
#endif
initialised = true;
}
/// <summary>
/// The MoonSharp interpreter instance used to run Lua code.
/// </summary>
public virtual Script Interpreter { get { return interpreter; } }
/// <summary>
/// Loads and compiles a string containing Lua script, returning a closure (Lua function) which can be executed later.
/// <param name="luaString">The Lua code to be run.</param>
/// <param name="friendlyName">A descriptive name to be used in error reports.</param>
/// </summary>
public virtual Closure LoadLuaFunction(string luaString, string friendlyName)
{
InitEnvironment();
string processedString;
var initializer = GetComponent<LuaEnvironmentInitializer>();
if (initializer != null)
{
processedString = initializer.PreprocessScript(luaString);
}
else
{
processedString = luaString;
}
// Load the Lua script
DynValue res = null;
try
{
res = interpreter.LoadString(processedString, null, friendlyName);
}
catch (InterpreterException ex)
{
LogException(ex.DecoratedMessage, luaString);
}
if (res == null ||
res.Type != DataType.Function)
{
UnityEngine.Debug.LogError("Failed to create Lua function from Lua string");
return null;
}
return res.Function;
}
/// <summary>
/// Load and run a previously compiled Lua script. May be run as a coroutine.
/// <param name="fn">A previously compiled Lua function.</param>
/// <param name="runAsCoroutine">Run the Lua code as a coroutine to support asynchronous operations.</param>
/// <param name="onComplete">Method to callback when the Lua code finishes exection. Supports return parameters.</param>
/// </summary>
public virtual void RunLuaFunction(Closure fn, bool runAsCoroutine, Action<DynValue> onComplete = null)
{
if (fn == null)
{
if (onComplete != null)
{
onComplete(null);
}
return;
}
// Execute the Lua script
if (runAsCoroutine)
{
StartCoroutine(RunLuaCoroutine(fn, onComplete));
}
else
{
DynValue returnValue = null;
try
{
returnValue = fn.Call();
}
catch (InterpreterException ex)
{
LogException(ex.DecoratedMessage, GetSourceCode());
}
if (onComplete != null)
{
onComplete(returnValue);
}
}
}
/// <summary>
/// Load and run a string containing Lua script. May be run as a coroutine.
/// <param name="luaString">The Lua code to be run.</param>
/// <param name="friendlyName">A descriptive name to be used in error reports.</param>
/// <param name="runAsCoroutine">Run the Lua code as a coroutine to support asynchronous operations.</param>
/// <param name="onComplete">Method to callback when the Lua code finishes exection. Supports return parameters.</param>
/// </summary>
public virtual void DoLuaString(string luaString, string friendlyName, bool runAsCoroutine, Action<DynValue> onComplete = null)
{
Closure fn = LoadLuaFunction(luaString, friendlyName);
RunLuaFunction(fn, runAsCoroutine, onComplete);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Collections.Generic
{
// Implements a variable-size List that uses an array of objects to store the
// elements. A List has a capacity, which is the allocated length
// of the internal array. As elements are added to a List, the capacity
// of the List is automatically increased as required by reallocating the
// internal array.
//
[DebuggerTypeProxy(typeof(ICollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class List<T> : IList<T>, IList, IReadOnlyList<T>
{
private const int DefaultCapacity = 4;
private T[] _items; // Do not rename (binary serialization)
private int _size; // Do not rename (binary serialization)
private int _version; // Do not rename (binary serialization)
private static readonly T[] s_emptyArray = new T[0];
// Constructs a List. The list is initially empty and has a capacity
// of zero. Upon adding the first element to the list the capacity is
// increased to DefaultCapacity, and then increased in multiples of two
// as required.
public List()
{
_items = s_emptyArray;
}
// Constructs a List with a given initial capacity. The list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required.
//
public List(int capacity)
{
if (capacity < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (capacity == 0)
_items = s_emptyArray;
else
_items = new T[capacity];
}
// Constructs a List, copying the contents of the given collection. The
// size and capacity of the new list will both be equal to the size of the
// given collection.
//
public List(IEnumerable<T> collection)
{
if (collection == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
if (collection is ICollection<T> c)
{
int count = c.Count;
if (count == 0)
{
_items = s_emptyArray;
}
else
{
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
else
{
_size = 0;
_items = s_emptyArray;
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Add(en.Current);
}
}
}
}
// Gets and sets the capacity of this list. The capacity is the size of
// the internal array used to hold items. When set, the internal
// array of the list is reallocated to the given capacity.
//
public int Capacity
{
get
{
return _items.Length;
}
set
{
if (value < _size)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
}
if (value != _items.Length)
{
if (value > 0)
{
T[] newItems = new T[value];
if (_size > 0)
{
Array.Copy(_items, 0, newItems, 0, _size);
}
_items = newItems;
}
else
{
_items = s_emptyArray;
}
}
}
}
// Read-only property describing how many elements are in the List.
public int Count => _size;
bool IList.IsFixedSize => false;
// Is this List read-only?
bool ICollection<T>.IsReadOnly => false;
bool IList.IsReadOnly => false;
// Is this List synchronized (thread-safe)?
bool ICollection.IsSynchronized => false;
// Synchronization root for this object.
object ICollection.SyncRoot => this;
// Sets or Gets the element at the given index.
public T this[int index]
{
get
{
// Following trick can reduce the range check by one
if ((uint)index >= (uint)_size)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
return _items[index];
}
set
{
if ((uint)index >= (uint)_size)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
_items[index] = value;
_version++;
}
}
private static bool IsCompatibleObject(object value)
{
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
try
{
this[index] = (T)value;
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
}
}
}
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(T item)
{
_version++;
T[] array = _items;
int size = _size;
if ((uint)size < (uint)array.Length)
{
_size = size + 1;
array[size] = item;
}
else
{
AddWithResize(item);
}
}
// Non-inline from List.Add to improve its code quality as uncommon path
[MethodImpl(MethodImplOptions.NoInlining)]
private void AddWithResize(T item)
{
int size = _size;
EnsureCapacity(size + 1);
_size = size + 1;
_items[size] = item;
}
int IList.Add(object item)
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item);
try
{
Add((T)item);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
}
return Count - 1;
}
// Adds the elements of the given collection to the end of this list. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger.
//
public void AddRange(IEnumerable<T> collection)
=> InsertRange(_size, collection);
public ReadOnlyCollection<T> AsReadOnly()
=> new ReadOnlyCollection<T>(this);
// Searches a section of the list for a given element using a binary search
// algorithm. Elements of the list are compared to the search value using
// the given IComparer interface. If comparer is null, elements of
// the list are compared to the search value using the IComparable
// interface, which in that case must be implemented by all elements of the
// list and the given search value. This method assumes that the given
// section of the list is already sorted; if this is not the case, the
// result will be incorrect.
//
// The method returns the index of the given value in the list. If the
// list does not contain the given value, the method returns a negative
// integer. The bitwise complement operator (~) can be applied to a
// negative result to produce the index of the first element (if any) that
// is larger than the given search value. This is also the index at which
// the search value should be inserted into the list in order for the list
// to remain sorted.
//
// The method uses the Array.BinarySearch method to perform the
// search.
//
public int BinarySearch(int index, int count, T item, IComparer<T> comparer)
{
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (count < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
return Array.BinarySearch<T>(_items, index, count, item, comparer);
}
public int BinarySearch(T item)
=> BinarySearch(0, Count, item, null);
public int BinarySearch(T item, IComparer<T> comparer)
=> BinarySearch(0, Count, item, comparer);
// Clears the contents of List.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear()
{
_version++;
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
int size = _size;
_size = 0;
if (size > 0)
{
Array.Clear(_items, 0, size); // Clear the elements so that the gc can reclaim the references.
}
}
else
{
_size = 0;
}
}
// Contains returns true if the specified element is in the List.
// It does a linear, O(n) search. Equality is determined by calling
// EqualityComparer<T>.Default.Equals().
//
public bool Contains(T item)
{
// PERF: IndexOf calls Array.IndexOf, which internally
// calls EqualityComparer<T>.Default.IndexOf, which
// is specialized for different types. This
// boosts performance since instead of making a
// virtual method call each iteration of the loop,
// via EqualityComparer<T>.Default.Equals, we
// only make one virtual call to EqualityComparer.IndexOf.
return _size != 0 && IndexOf(item) != -1;
}
bool IList.Contains(object item)
{
if (IsCompatibleObject(item))
{
return Contains((T)item);
}
return false;
}
public List<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter)
{
if (converter == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
}
List<TOutput> list = new List<TOutput>(_size);
for (int i = 0; i < _size; i++)
{
list._items[i] = converter(_items[i]);
}
list._size = _size;
return list;
}
// Copies this List into array, which must be of a
// compatible array type.
public void CopyTo(T[] array)
=> CopyTo(array, 0);
// Copies this List into array, which must be of a
// compatible array type.
void ICollection.CopyTo(Array array, int arrayIndex)
{
if ((array != null) && (array.Rank != 1))
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
try
{
// Array.Copy will check for NULL.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
// Copies a section of this list to the given array at the given index.
//
// The method uses the Array.Copy method to copy the elements.
//
public void CopyTo(int index, T[] array, int arrayIndex, int count)
{
if (_size - index < count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, index, array, arrayIndex, count);
}
public void CopyTo(T[] array, int arrayIndex)
{
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
// Ensures that the capacity of this 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)
{
if (_items.Length < min)
{
int newCapacity = _items.Length == 0 ? DefaultCapacity : _items.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 > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
}
public bool Exists(Predicate<T> match)
=> FindIndex(match) != -1;
public T Find(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
for (int i = 0; i < _size; i++)
{
if (match(_items[i]))
{
return _items[i];
}
}
return default;
}
public List<T> FindAll(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
List<T> list = new List<T>();
for (int i = 0; i < _size; i++)
{
if (match(_items[i]))
{
list.Add(_items[i]);
}
}
return list;
}
public int FindIndex(Predicate<T> match)
=> FindIndex(0, _size, match);
public int FindIndex(int startIndex, Predicate<T> match)
=> FindIndex(startIndex, _size - startIndex, match);
public int FindIndex(int startIndex, int count, Predicate<T> match)
{
if ((uint)startIndex > (uint)_size)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if (count < 0 || startIndex > _size - count)
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
int endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++)
{
if (match(_items[i])) return i;
}
return -1;
}
public T FindLast(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
for (int i = _size - 1; i >= 0; i--)
{
if (match(_items[i]))
{
return _items[i];
}
}
return default;
}
public int FindLastIndex(Predicate<T> match)
=> FindLastIndex(_size - 1, _size, match);
public int FindLastIndex(int startIndex, Predicate<T> match)
=> FindLastIndex(startIndex, startIndex + 1, match);
public int FindLastIndex(int startIndex, int count, Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
if (_size == 0)
{
// Special case for 0 length List
if (startIndex != -1)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
else
{
// Make sure we're not out of range
if ((uint)startIndex >= (uint)_size)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
int endIndex = startIndex - count;
for (int i = startIndex; i > endIndex; i--)
{
if (match(_items[i]))
{
return i;
}
}
return -1;
}
public void ForEach(Action<T> action)
{
if (action == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action);
}
int version = _version;
for (int i = 0; i < _size; i++)
{
if (version != _version)
{
break;
}
action(_items[i]);
}
if (version != _version)
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
// Returns an enumerator for this list with the given
// permission for removal of elements. If modifications made to the list
// while an enumeration is in progress, the MoveNext and
// GetObject methods of the enumerator will throw an exception.
//
public Enumerator GetEnumerator()
=> new Enumerator(this);
IEnumerator<T> IEnumerable<T>.GetEnumerator()
=> new Enumerator(this);
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(this);
public List<T> GetRange(int index, int count)
{
if (index < 0)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (count < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
List<T> list = new List<T>(count);
Array.Copy(_items, index, list._items, 0, count);
list._size = count;
return list;
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards from beginning to end.
// The elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item)
=> Array.IndexOf(_items, item, 0, _size);
int IList.IndexOf(object item)
{
if (IsCompatibleObject(item))
{
return IndexOf((T)item);
}
return -1;
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and ending at count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item, int index)
{
if (index > _size)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
return Array.IndexOf(_items, item, index, _size - index);
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and upto count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item, int index, int count)
{
if (index > _size)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
if (count < 0 || index > _size - count)
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
return Array.IndexOf(_items, item, index, count);
}
// Inserts an element into this list at a given index. The size of the list
// is increased by one. If required, the capacity of the list is doubled
// before inserting the new element.
//
public void Insert(int index, T item)
{
// Note that insertions at the end are legal.
if ((uint)index > (uint)_size)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);
}
if (_size == _items.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = item;
_size++;
_version++;
}
void IList.Insert(int index, object item)
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item);
try
{
Insert(index, (T)item);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
}
}
// Inserts the elements of the given collection at a given index. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger. Ranges may be added
// to the end of the list by setting index to the List's size.
//
public void InsertRange(int index, IEnumerable<T> collection)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
if ((uint)index > (uint)_size)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
if (collection is ICollection<T> c)
{
int count = c.Count;
if (count > 0)
{
EnsureCapacity(_size + count);
if (index < _size)
{
Array.Copy(_items, index, _items, index + count, _size - index);
}
// If we're inserting a List into itself, we want to be able to deal with that.
if (this == c)
{
// Copy first part of _items to insert location
Array.Copy(_items, 0, _items, index, index);
// Copy last part of _items back to inserted location
Array.Copy(_items, index + count, _items, index * 2, _size - index);
}
else
{
c.CopyTo(_items, index);
}
_size += count;
}
}
else
{
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Insert(index++, en.Current);
}
}
}
_version++;
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at the end
// and ending at the first element in the list. The elements of the list
// are compared to the given value using the Object.Equals method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
//
public int LastIndexOf(T item)
{
if (_size == 0)
{ // Special case for empty list
return -1;
}
else
{
return LastIndexOf(item, _size - 1, _size);
}
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at index
// index and ending at the first element in the list. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
//
public int LastIndexOf(T item, int index)
{
if (index >= _size)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
return LastIndexOf(item, index, index + 1);
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at index
// index and upto count elements. The elements of
// the list are compared to the given value using the Object.Equals
// method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
//
public int LastIndexOf(T item, int index, int count)
{
if ((Count != 0) && (index < 0))
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if ((Count != 0) && (count < 0))
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size == 0)
{ // Special case for empty list
return -1;
}
if (index >= _size)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection);
}
if (count > index + 1)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection);
}
return Array.LastIndexOf(_items, item, index, count);
}
// Removes the element at the given index. The size of the list is
// decreased by one.
public bool Remove(T item)
{
int index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
void IList.Remove(object item)
{
if (IsCompatibleObject(item))
{
Remove((T)item);
}
}
// This method removes all items which matches the predicate.
// The complexity is O(n).
public int RemoveAll(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
int freeIndex = 0; // the first free slot in items array
// Find the first item which needs to be removed.
while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++;
if (freeIndex >= _size) return 0;
int current = freeIndex + 1;
while (current < _size)
{
// Find the first item which needs to be kept.
while (current < _size && match(_items[current])) current++;
if (current < _size)
{
// copy item to the free slot.
_items[freeIndex++] = _items[current++];
}
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
Array.Clear(_items, freeIndex, _size - freeIndex); // Clear the elements so that the gc can reclaim the references.
}
int result = _size - freeIndex;
_size = freeIndex;
_version++;
return result;
}
// Removes the element at the given index. The size of the list is
// decreased by one.
public void RemoveAt(int index)
{
if ((uint)index >= (uint)_size)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
_size--;
if (index < _size)
{
Array.Copy(_items, index + 1, _items, index, _size - index);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
_items[_size] = default;
}
_version++;
}
// Removes a range of elements from this list.
public void RemoveRange(int index, int count)
{
if (index < 0)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (count < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
if (count > 0)
{
_size -= count;
if (index < _size)
{
Array.Copy(_items, index + count, _items, index, _size - index);
}
_version++;
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
Array.Clear(_items, _size, count);
}
}
}
// Reverses the elements in this list.
public void Reverse()
=> Reverse(0, Count);
// Reverses the elements in a range of this list. Following a call to this
// method, an element in the range given by index and count
// which was previously located at index i will now be located at
// index index + (index + count - i - 1).
//
public void Reverse(int index, int count)
{
if (index < 0)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (count < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
if (count > 1)
{
Array.Reverse(_items, index, count);
}
_version++;
}
// Sorts the elements in this list. Uses the default comparer and
// Array.Sort.
public void Sort()
=> Sort(0, Count, null);
// Sorts the elements in this list. Uses Array.Sort with the
// provided comparer.
public void Sort(IComparer<T> comparer)
=> Sort(0, Count, comparer);
// Sorts the elements in a section of this list. The sort compares the
// elements to each other using the given IComparer interface. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented by all
// elements of the list.
//
// This method uses the Array.Sort method to sort the elements.
//
public void Sort(int index, int count, IComparer<T> comparer)
{
if (index < 0)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (count < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
if (count > 1)
{
Array.Sort<T>(_items, index, count, comparer);
}
_version++;
}
public void Sort(Comparison<T> comparison)
{
if (comparison == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison);
}
if (_size > 1)
{
ArraySortHelper<T>.Sort(_items, 0, _size, comparison);
}
_version++;
}
// ToArray returns an array containing the contents of the List.
// This requires copying the List, which is an O(n) operation.
public T[] ToArray()
{
if (_size == 0)
{
return s_emptyArray;
}
T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
return array;
}
// Sets the capacity of this list to the size of the list. This method can
// be used to minimize a list's memory overhead once it is known that no
// new elements will be added to the list. To completely clear a list and
// release all memory referenced by the list, execute the following
// statements:
//
// list.Clear();
// list.TrimExcess();
//
public void TrimExcess()
{
int threshold = (int)(((double)_items.Length) * 0.9);
if (_size < threshold)
{
Capacity = _size;
}
}
public bool TrueForAll(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
for (int i = 0; i < _size; i++)
{
if (!match(_items[i]))
{
return false;
}
}
return true;
}
public struct Enumerator : IEnumerator<T>, IEnumerator
{
private readonly List<T> _list;
private int _index;
private readonly int _version;
private T _current;
internal Enumerator(List<T> list)
{
_list = list;
_index = 0;
_version = list._version;
_current = default;
}
public void Dispose()
{
}
public bool MoveNext()
{
List<T> localList = _list;
if (_version == localList._version && ((uint)_index < (uint)localList._size))
{
_current = localList._items[_index];
_index++;
return true;
}
return MoveNextRare();
}
private bool MoveNextRare()
{
if (_version != _list._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = _list._size + 1;
_current = default;
return false;
}
public T Current => _current;
object IEnumerator.Current
{
get
{
if (_index == 0 || _index == _list._size + 1)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return Current;
}
}
void IEnumerator.Reset()
{
if (_version != _list._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_current = default;
}
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Xml;
using System.Data;
using System.Collections;
namespace Reporting.Data
{
/// <summary>
/// FileDirCommand allows specifying the command for the web log.
/// </summary>
public class FileDirCommand : IDbCommand
{
FileDirConnection _fdc; // connection we're running under
string _cmd; // command to execute
// parsed constituents of the command
string _Directory; // Directory
string _FilePattern; // SearchPattern when doing the file lookup
string _DirectoryPattern; // SearchPattern when doing the directory lookup
string _TrimEmpty="yes"; // Directory with no files will be omitted from result set
DataParameterCollection _Parameters = new DataParameterCollection();
public FileDirCommand(FileDirConnection conn)
{
_fdc = conn;
}
internal string Directory
{
get
{
// Check to see if "Directory" or "@Directory" is a parameter
IDbDataParameter dp= _Parameters["Directory"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@Directory"] as IDbDataParameter;
// Then check to see if the Directory value is a parameter?
if (dp == null)
dp = _Parameters[_Directory] as IDbDataParameter;
if (dp != null)
return dp.Value != null? dp.Value.ToString(): _Directory; // don't pass null; pass existing value
return _Directory == null? _fdc.Directory: _Directory;
}
set {_Directory = value;}
}
internal string FilePattern
{
get
{
// Check to see if "FilePattern" or "@FilePattern" is a parameter
IDbDataParameter dp= _Parameters["FilePattern"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@FilePattern"] as IDbDataParameter;
// Then check to see if the FilePattern value is a parameter?
if (dp == null)
dp = _Parameters[_FilePattern] as IDbDataParameter;
if (dp != null)
return dp.Value as string;
return _FilePattern;
}
set {_FilePattern = value;}
}
internal string DirectoryPattern
{
get
{
// Check to see if "DirectoryPattern" or "@DirectoryPattern" is a parameter
IDbDataParameter dp= _Parameters["DirectoryPattern"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@DirectoryPattern"] as IDbDataParameter;
// Then check to see if the DirectoryPattern value is a parameter?
if (dp == null)
dp = _Parameters[_DirectoryPattern] as IDbDataParameter;
if (dp != null)
return dp.Value as string;
return _DirectoryPattern;
}
set {_DirectoryPattern = value;}
}
internal bool TrimEmpty
{
get
{
// Check to see if "TrimEmpty" or "@TrimEmpty" is a parameter
IDbDataParameter dp= _Parameters["TrimEmpty"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@TrimEmpty"] as IDbDataParameter;
// Then check to see if the TrimEmpty value is a parameter?
if (dp == null)
dp = _Parameters[_TrimEmpty] as IDbDataParameter;
if (dp != null)
{
string tf = dp.Value as string;
if (tf == null)
return false;
tf = tf.ToLower();
return (tf == "true" || tf == "yes");
}
return _TrimEmpty=="yes"? true: false; // the value must be a constant
}
set {_TrimEmpty = value? "yes": "no";}
}
#region IDbCommand Members
public void Cancel()
{
throw new NotImplementedException("Cancel not implemented");
}
public void Prepare()
{
return; // Prepare is a noop
}
public System.Data.CommandType CommandType
{
get
{
throw new NotImplementedException("CommandType not implemented");
}
set
{
throw new NotImplementedException("CommandType not implemented");
}
}
public IDataReader ExecuteReader(System.Data.CommandBehavior behavior)
{
if (!(behavior == CommandBehavior.SingleResult ||
behavior == CommandBehavior.SchemaOnly))
throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only.");
return new FileDirDataReader(behavior, _fdc, this);
}
IDataReader System.Data.IDbCommand.ExecuteReader()
{
return ExecuteReader(System.Data.CommandBehavior.SingleResult);
}
public object ExecuteScalar()
{
throw new NotImplementedException("ExecuteScalar not implemented");
}
public int ExecuteNonQuery()
{
throw new NotImplementedException("ExecuteNonQuery not implemented");
}
public int CommandTimeout
{
get
{
return 0;
}
set
{
throw new NotImplementedException("CommandTimeout not implemented");
}
}
public IDbDataParameter CreateParameter()
{
return new FileDirDataParameter();
}
public IDbConnection Connection
{
get
{
return this._fdc;
}
set
{
throw new NotImplementedException("Setting Connection not implemented");
}
}
public System.Data.UpdateRowSource UpdatedRowSource
{
get
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
set
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
}
public string CommandText
{
get
{
return this._cmd;
}
set
{
// Parse the command string for keyword value pairs separated by ';'
_FilePattern = null;
_DirectoryPattern = null;
_Directory = null;
string[] args = value.Split(';');
foreach(string arg in args)
{
string[] param = arg.Trim().Split('=');
if (param == null || param.Length != 2)
continue;
string key = param[0].Trim().ToLower();
string val = param[1];
switch (key)
{
case "directory":
_Directory = val;
break;
case "filepattern":
_FilePattern = val;
break;
case "directorypattern":
_DirectoryPattern = val;
break;
default:
throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0]));
}
}
// User must specify both the url and the RowsXPath
if (_Directory == null && this._fdc.Directory == null)
{
if (_Directory == null)
throw new ArgumentException("CommandText requires a 'Directory=' parameter.");
}
_cmd = value;
}
}
public IDataParameterCollection Parameters
{
get
{
return _Parameters;
}
}
public IDbTransaction Transaction
{
get
{
throw new NotImplementedException("Transaction not implemented");
}
set
{
throw new NotImplementedException("Transaction not implemented");
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
// nothing to dispose of
}
#endregion
}
}
| |
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TVHeadEnd.DataHelper;
using TVHeadEnd.Helper;
using TVHeadEnd.HTSP;
using TVHeadEnd.HTSP_Responses;
using TVHeadEnd.TimeoutHelper;
namespace TVHeadEnd
{
/// <summary>
/// Class LiveTvService
/// </summary>
public class LiveTvService : ILiveTvService, HTSConnectionListener
{
private readonly TimeSpan TIMEOUT = TimeSpan.FromMinutes(5);
private volatile Boolean _connected = false;
private volatile Boolean _initialLoadFinished = false;
private volatile int _subscriptionId = 0;
private readonly ILogger _logger;
private HTSConnectionAsync _htsConnection;
private int _priority;
private string _profile;
private string _httpBaseUrl;
// Data helpers
private readonly ChannelDataHelper _channelDataHelper;
private readonly TunerDataHelper _tunerDataHelper;
private readonly DvrDataHelper _dvrDataHelper;
private readonly AutorecDataHelper _autorecDataHelper;
public LiveTvService(ILogger logger)
{
_logger = logger;
_tunerDataHelper = new TunerDataHelper(logger);
_channelDataHelper = new ChannelDataHelper(logger, _tunerDataHelper);
_dvrDataHelper = new DvrDataHelper(logger);
_autorecDataHelper = new AutorecDataHelper(logger);
createHTSConnection();
}
private void createHTSConnection()
{
_logger.Info("[TVHclient] LiveTvService.createHTSConnection()");
Version version = Assembly.GetEntryAssembly().GetName().Version;
_htsConnection = new HTSConnectionAsync(this, "TVHclient4Emby", version.ToString(), _logger);
_connected = false;
}
private void ensureConnection()
{
if (_htsConnection == null)
{
return;
}
if (_htsConnection.needsRestart())
{
createHTSConnection();
}
lock (_htsConnection)
{
if (!_connected)
{
var config = Plugin.Instance.Configuration;
if (string.IsNullOrEmpty(config.TVH_ServerName))
{
string message = "[TVHclient] LiveTvService.ensureConnection: TVH-Server name must be configured.";
_logger.Error(message);
throw new InvalidOperationException(message);
}
if (string.IsNullOrEmpty(config.Username))
{
string message = "[TVHclient] LiveTvService.ensureConnection: Username must be configured.";
_logger.Error(message);
throw new InvalidOperationException(message);
}
if (string.IsNullOrEmpty(config.Password))
{
string message = "[TVHclient] LiveTvService.ensureConnection: Password must be configured.";
_logger.Error(message);
throw new InvalidOperationException(message);
}
_priority = config.Priority;
_profile = config.Profile.Trim();
_channelDataHelper.setChannelType4Other(config.ChannelType.Trim());
if (_priority < 0 || _priority > 4)
{
_priority = 2;
_logger.Info("[TVHclient] LiveTvService.ensureConnection: Priority was out of range [0-4] - set to 2");
}
string tvhServerName = config.TVH_ServerName.Trim();
int httpPort = config.HTTP_Port;
int htspPort = config.HTSP_Port;
string userName = config.Username.Trim();
string password = config.Password.Trim();
_httpBaseUrl = "http://" + tvhServerName + ":" + httpPort;
_logger.Info("[TVHclient] LiveTvService.ensureConnection: Used connection parameters: " +
"TVH Server = '" + tvhServerName + "'; " +
"HTTP Port = '" + httpPort + "'; " +
"HTSP Port = '" + htspPort + "'; " +
"User = '" + userName + "'; " +
"Password set = '" + (password.Length > 0) + "'");
_htsConnection.open(tvhServerName, htspPort);
_connected = _htsConnection.authenticate(userName, password);
_logger.Info("[TVHclient] LiveTvService.ensureConnection: connection established " + _connected);
_channelDataHelper.clean();
_dvrDataHelper.clean();
_autorecDataHelper.clean();
}
}
}
/// <summary>
/// Gets the channels async.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{IEnumerable{ChannelInfo}}.</returns>
public async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
{
ensureConnection();
int timeOut = await WaitForInitialLoadTask(cancellationToken);
if (timeOut == -1 || cancellationToken.IsCancellationRequested)
{
_logger.Info("[TVHclient] GetChannelsAsync, call canceled or timed out - returning empty list.");
return new List<ChannelInfo>();
}
//IEnumerable<ChannelInfo> data = await _channelDataHelper.buildChannelInfos(cancellationToken);
//return data;
TaskWithTimeoutRunner<IEnumerable<ChannelInfo>> twtr = new TaskWithTimeoutRunner<IEnumerable<ChannelInfo>>(TIMEOUT);
TaskWithTimeoutResult<IEnumerable<ChannelInfo>> twtRes = await
twtr.RunWithTimeout(_channelDataHelper.buildChannelInfos(cancellationToken));
if (twtRes.HasTimeout)
{
return new List<ChannelInfo>();
}
return twtRes.Result;
}
private Task<int> WaitForInitialLoadTask(CancellationToken cancellationToken)
{
return Task.Factory.StartNew<int>(() =>
{
DateTime start = DateTime.Now;
while (!_initialLoadFinished || cancellationToken.IsCancellationRequested)
{
Thread.Sleep(500);
TimeSpan duration = DateTime.Now - start;
long durationInSec = duration.Ticks / TimeSpan.TicksPerSecond;
if (durationInSec > 60 * 15) // 15 Min timeout, should be enough to load huge data count
{
return -1;
}
}
return 0;
});
}
/// <summary>
/// Gets the Recordings async
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{IEnumerable{RecordingInfo}}</returns>
public async Task<IEnumerable<RecordingInfo>> GetRecordingsAsync(CancellationToken cancellationToken)
{
// retrieve all 'Pending', 'Inprogress' and 'Completed' recordings
// we don't deliver the 'Pending' recordings
ensureConnection();
int timeOut = await WaitForInitialLoadTask(cancellationToken);
if (timeOut == -1 || cancellationToken.IsCancellationRequested)
{
_logger.Info("[TVHclient] GetRecordingsAsync, call canceled or timed out - returning empty list.");
return new List<RecordingInfo>();
}
//IEnumerable<RecordingInfo> data = await _dvrDataHelper.buildDvrInfos(cancellationToken);
//return data;
TaskWithTimeoutRunner<IEnumerable<RecordingInfo>> twtr = new TaskWithTimeoutRunner<IEnumerable<RecordingInfo>>(TIMEOUT);
TaskWithTimeoutResult<IEnumerable<RecordingInfo>> twtRes = await
twtr.RunWithTimeout(_dvrDataHelper.buildDvrInfos(cancellationToken));
if (twtRes.HasTimeout)
{
return new List<RecordingInfo>();
}
return twtRes.Result;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get { return "TVHclient"; }
}
/// <summary>
/// Delete the Recording async from the disk
/// </summary>
/// <param name="recordingId">The recordingId</param>
/// <param name="cancellationToken">The cancellationToken</param>
/// <returns></returns>
public async Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken)
{
ensureConnection();
int timeOut = await WaitForInitialLoadTask(cancellationToken);
if (timeOut == -1 || cancellationToken.IsCancellationRequested)
{
_logger.Info("[TVHclient] DeleteRecordingAsync, call canceled or timed out.");
return;
}
HTSMessage deleteRecordingMessage = new HTSMessage();
deleteRecordingMessage.Method = "deleteDvrEntry";
deleteRecordingMessage.putField("id", recordingId);
//HTSMessage deleteRecordingResponse = await Task.Factory.StartNew<HTSMessage>(() =>
//{
// LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
// _htsConnection.sendMessage(deleteRecordingMessage, lbrh);
// return lbrh.getResponse();
//});
TaskWithTimeoutRunner<HTSMessage> twtr = new TaskWithTimeoutRunner<HTSMessage>(TIMEOUT);
TaskWithTimeoutResult<HTSMessage> twtRes = await twtr.RunWithTimeout(Task.Factory.StartNew<HTSMessage>(() =>
{
LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
_htsConnection.sendMessage(deleteRecordingMessage, lbrh);
return lbrh.getResponse();
}));
if (twtRes.HasTimeout)
{
_logger.Error("[TVHclient] Can't delete recording because of timeout");
}
else
{
HTSMessage deleteRecordingResponse = twtRes.Result;
Boolean success = deleteRecordingResponse.getInt("success", 0) == 1;
if (!success)
{
_logger.Error("[TVHclient] Can't delete recording: '" + deleteRecordingResponse.getString("error") + "'");
}
}
}
/// <summary>
/// Cancel pending scheduled Recording
/// </summary>
/// <param name="timerId">The timerId</param>
/// <param name="cancellationToken">The cancellationToken</param>
/// <returns></returns>
public async Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
{
ensureConnection();
int timeOut = await WaitForInitialLoadTask(cancellationToken);
if (timeOut == -1 || cancellationToken.IsCancellationRequested)
{
_logger.Info("[TVHclient] CancelTimerAsync, call canceled or timed out.");
return;
}
HTSMessage cancelTimerMessage = new HTSMessage();
cancelTimerMessage.Method = "cancelDvrEntry";
cancelTimerMessage.putField("id", timerId);
//HTSMessage cancelTimerResponse = await Task.Factory.StartNew<HTSMessage>(() =>
//{
// LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
// _htsConnection.sendMessage(cancelTimerMessage, lbrh);
// return lbrh.getResponse();
//});
TaskWithTimeoutRunner<HTSMessage> twtr = new TaskWithTimeoutRunner<HTSMessage>(TIMEOUT);
TaskWithTimeoutResult<HTSMessage> twtRes = await twtr.RunWithTimeout(Task.Factory.StartNew<HTSMessage>(() =>
{
LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
_htsConnection.sendMessage(cancelTimerMessage, lbrh);
return lbrh.getResponse();
}));
if (twtRes.HasTimeout)
{
_logger.Error("[TVHclient] Can't cancel timer because of timeout");
}
else
{
HTSMessage cancelTimerResponse = twtRes.Result;
Boolean success = cancelTimerResponse.getInt("success", 0) == 1;
if (!success)
{
_logger.Error("[TVHclient] Can't cancel timer: '" + cancelTimerResponse.getString("error") + "'");
}
}
}
/// <summary>
/// Create a new recording
/// </summary>
/// <param name="info">The TimerInfo</param>
/// <param name="cancellationToken">The cancellationToken</param>
/// <returns></returns>
public async Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
{
ensureConnection();
int timeOut = await WaitForInitialLoadTask(cancellationToken);
if (timeOut == -1 || cancellationToken.IsCancellationRequested)
{
_logger.Info("[TVHclient] CreateTimerAsync, call canceled or timed out.");
return;
}
HTSMessage createTimerMessage = new HTSMessage();
createTimerMessage.Method = "addDvrEntry";
createTimerMessage.putField("channelId", info.ChannelId);
createTimerMessage.putField("start", DateTimeHelper.getUnixUTCTimeFromUtcDateTime(info.StartDate));
createTimerMessage.putField("stop", DateTimeHelper.getUnixUTCTimeFromUtcDateTime(info.EndDate));
createTimerMessage.putField("startExtra", (long)(info.PrePaddingSeconds / 60));
createTimerMessage.putField("stopExtra", (long)(info.PostPaddingSeconds / 60));
createTimerMessage.putField("priority", _priority); // info.Priority delivers always 0 - no GUI
createTimerMessage.putField("configName", _profile);
createTimerMessage.putField("description", info.Overview);
createTimerMessage.putField("title", info.Name);
createTimerMessage.putField("creator", Plugin.Instance.Configuration.Username);
//HTSMessage createTimerResponse = await Task.Factory.StartNew<HTSMessage>(() =>
//{
// LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
// _htsConnection.sendMessage(createTimerMessage, lbrh);
// return lbrh.getResponse();
//});
TaskWithTimeoutRunner<HTSMessage> twtr = new TaskWithTimeoutRunner<HTSMessage>(TIMEOUT);
TaskWithTimeoutResult<HTSMessage> twtRes = await twtr.RunWithTimeout(Task.Factory.StartNew<HTSMessage>(() =>
{
LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
_htsConnection.sendMessage(createTimerMessage, lbrh);
return lbrh.getResponse();
}));
if (twtRes.HasTimeout)
{
_logger.Error("[TVHclient] Can't create timer because of timeout");
}
else
{
HTSMessage createTimerResponse = twtRes.Result;
Boolean success = createTimerResponse.getInt("success", 0) == 1;
if (!success)
{
_logger.Error("[TVHclient] Can't create timer: '" + createTimerResponse.getString("error") + "'");
}
}
}
/// <summary>
/// Update a single Timer
/// </summary>
/// <param name="info">The program info</param>
/// <param name="cancellationToken">The CancellationToken</param>
/// <returns></returns>
public async Task UpdateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
{
ensureConnection();
int timeOut = await WaitForInitialLoadTask(cancellationToken);
if (timeOut == -1 || cancellationToken.IsCancellationRequested)
{
_logger.Info("[TVHclient] UpdateTimerAsync, call canceled or timed out.");
return;
}
HTSMessage updateTimerMessage = new HTSMessage();
updateTimerMessage.Method = "updateDvrEntry";
updateTimerMessage.putField("id", info.Id);
updateTimerMessage.putField("startExtra", (long)(info.PrePaddingSeconds / 60));
updateTimerMessage.putField("stopExtra", (long)(info.PostPaddingSeconds / 60));
//HTSMessage updateTimerResponse = await Task.Factory.StartNew<HTSMessage>(() =>
//{
// LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
// _htsConnection.sendMessage(updateTimerMessage, lbrh);
// return lbrh.getResponse();
//});
TaskWithTimeoutRunner<HTSMessage> twtr = new TaskWithTimeoutRunner<HTSMessage>(TIMEOUT);
TaskWithTimeoutResult<HTSMessage> twtRes = await twtr.RunWithTimeout(Task.Factory.StartNew<HTSMessage>(() =>
{
LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
_htsConnection.sendMessage(updateTimerMessage, lbrh);
return lbrh.getResponse();
}));
if (twtRes.HasTimeout)
{
_logger.Error("[TVHclient] Can't update timer because of timeout");
}
else
{
HTSMessage updateTimerResponse = twtRes.Result;
Boolean success = updateTimerResponse.getInt("success", 0) == 1;
if (!success)
{
_logger.Error("[TVHclient] Can't update timer: '" + updateTimerResponse.getString("error") + "'");
}
}
}
/// <summary>
/// Get the pending Recordings.
/// </summary>
/// <param name="cancellationToken">The CancellationToken</param>
/// <returns></returns>
public async Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
{
// retrieve the 'Pending' recordings");
ensureConnection();
int timeOut = await WaitForInitialLoadTask(cancellationToken);
if (timeOut == -1 || cancellationToken.IsCancellationRequested)
{
_logger.Info("[TVHclient] GetTimersAsync, call canceled or timed out - returning empty list.");
return new List<TimerInfo>();
}
//IEnumerable<TimerInfo> data = await _dvrDataHelper.buildPendingTimersInfos(cancellationToken);
//return data;
TaskWithTimeoutRunner<IEnumerable<TimerInfo>> twtr = new TaskWithTimeoutRunner<IEnumerable<TimerInfo>>(TIMEOUT);
TaskWithTimeoutResult<IEnumerable<TimerInfo>> twtRes = await
twtr.RunWithTimeout(_dvrDataHelper.buildPendingTimersInfos(cancellationToken));
if (twtRes.HasTimeout)
{
return new List<TimerInfo>();
}
return twtRes.Result;
}
/// <summary>
/// Get the recurrent recordings
/// </summary>
/// <param name="cancellationToken">The CancellationToken</param>
/// <returns></returns>
public async Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
{
ensureConnection();
int timeOut = await WaitForInitialLoadTask(cancellationToken);
if (timeOut == -1 || cancellationToken.IsCancellationRequested)
{
_logger.Info("[TVHclient] GetSeriesTimersAsync, call canceled ot timed out - returning empty list.");
return new List<SeriesTimerInfo>();
}
//IEnumerable<SeriesTimerInfo> data = await _autorecDataHelper.buildAutorecInfos(cancellationToken);
//return data;
TaskWithTimeoutRunner<IEnumerable<SeriesTimerInfo>> twtr = new TaskWithTimeoutRunner<IEnumerable<SeriesTimerInfo>>(TIMEOUT);
TaskWithTimeoutResult<IEnumerable<SeriesTimerInfo>> twtRes = await
twtr.RunWithTimeout(_autorecDataHelper.buildAutorecInfos(cancellationToken));
if (twtRes.HasTimeout)
{
return new List<SeriesTimerInfo>();
}
return twtRes.Result;
}
/// <summary>
/// Create a recurrent recording
/// </summary>
/// <param name="info">The recurrend program info</param>
/// <param name="cancellationToken">The CancelationToken</param>
/// <returns></returns>
public async Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
{
// Dummy method to avoid warnings
await Task.Factory.StartNew<int>(() => { return 0; });
throw new NotImplementedException();
//ensureConnection();
//int timeOut = await WaitForInitialLoadTask(cancellationToken);
//if (timeOut == -1 || cancellationToken.IsCancellationRequested)
//{
// _logger.Info("[TVHclient] CreateSeriesTimerAsync, call canceled or timed out - returning empty list.");
// return;
//}
////_logger.Info("[TVHclient] CreateSeriesTimerAsync: got SeriesTimerInfo: " + dump(info));
//HTSMessage createSeriesTimerMessage = new HTSMessage();
//createSeriesTimerMessage.Method = "addAutorecEntry";
//createSeriesTimerMessage.putField("title", info.Name);
//if (!info.RecordAnyChannel)
//{
// createSeriesTimerMessage.putField("channelId", info.ChannelId);
//}
//createSeriesTimerMessage.putField("minDuration", 0);
//createSeriesTimerMessage.putField("maxDuration", 0);
//int tempPriority = info.Priority;
//if (tempPriority == 0)
//{
// tempPriority = _priority; // info.Priority delivers 0 if timers is newly created - no GUI
//}
//createSeriesTimerMessage.putField("priority", tempPriority);
//createSeriesTimerMessage.putField("configName", _profile);
//createSeriesTimerMessage.putField("daysOfWeek", AutorecDataHelper.getDaysOfWeekFromList(info.Days));
//if (!info.RecordAnyTime)
//{
// createSeriesTimerMessage.putField("approxTime", AutorecDataHelper.getMinutesFromMidnight(info.StartDate));
//}
//createSeriesTimerMessage.putField("startExtra", (long)(info.PrePaddingSeconds / 60L));
//createSeriesTimerMessage.putField("stopExtra", (long)(info.PostPaddingSeconds / 60L));
//createSeriesTimerMessage.putField("comment", info.Overview);
////_logger.Info("[TVHclient] CreateSeriesTimerAsync: created HTSP message: " + createSeriesTimerMessage.ToString());
///*
// public DateTime EndDate { get; set; }
// public string ProgramId { get; set; }
// public bool RecordNewOnly { get; set; }
// */
////HTSMessage createSeriesTimerResponse = await Task.Factory.StartNew<HTSMessage>(() =>
////{
//// LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
//// _htsConnection.sendMessage(createSeriesTimerMessage, lbrh);
//// return lbrh.getResponse();
////});
//TaskWithTimeoutRunner<HTSMessage> twtr = new TaskWithTimeoutRunner<HTSMessage>(TIMEOUT);
//TaskWithTimeoutResult<HTSMessage> twtRes = await twtr.RunWithTimeout(Task.Factory.StartNew<HTSMessage>(() =>
//{
// LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
// _htsConnection.sendMessage(createSeriesTimerMessage, lbrh);
// return lbrh.getResponse();
//}));
//if (twtRes.HasTimeout)
//{
// _logger.Error("[TVHclient] Can't create series because of timeout");
//}
//else
//{
// HTSMessage createSeriesTimerResponse = twtRes.Result;
// Boolean success = createSeriesTimerResponse.getInt("success", 0) == 1;
// if (!success)
// {
// _logger.Error("[TVHclient] Can't create series timer: '" + createSeriesTimerResponse.getString("error") + "'");
// }
//}
}
private string dump(SeriesTimerInfo sti)
{
StringBuilder sb = new StringBuilder();
sb.Append("\n<SeriesTimerInfo>\n");
sb.Append(" Id: " + sti.Id + "\n");
sb.Append(" Name: " + sti.Name + "\n");
sb.Append(" Overview: " + sti.Overview + "\n");
sb.Append(" Priority: " + sti.Priority + "\n");
sb.Append(" ChannelId: " + sti.ChannelId + "\n");
sb.Append(" ProgramId: " + sti.ProgramId + "\n");
sb.Append(" Days: " + dump(sti.Days) + "\n");
sb.Append(" StartDate: " + sti.StartDate + "\n");
sb.Append(" EndDate: " + sti.EndDate + "\n");
sb.Append(" IsPrePaddingRequired: " + sti.IsPrePaddingRequired + "\n");
sb.Append(" PrePaddingSeconds: " + sti.PrePaddingSeconds + "\n");
sb.Append(" IsPostPaddingRequired: " + sti.IsPrePaddingRequired + "\n");
sb.Append(" PostPaddingSeconds: " + sti.PostPaddingSeconds + "\n");
sb.Append(" RecordAnyChannel: " + sti.RecordAnyChannel + "\n");
sb.Append(" RecordAnyTime: " + sti.RecordAnyTime + "\n");
sb.Append(" RecordNewOnly: " + sti.RecordNewOnly + "\n");
sb.Append("</SeriesTimerInfo>\n");
return sb.ToString();
}
private string dump(List<DayOfWeek> days)
{
StringBuilder sb = new StringBuilder();
foreach (DayOfWeek dow in days)
{
sb.Append(dow + ", ");
}
string tmpResult = sb.ToString();
if (tmpResult.EndsWith(","))
{
tmpResult = tmpResult.Substring(0, tmpResult.Length - 2);
}
return tmpResult;
}
/// <summary>
/// Update the series Timer
/// </summary>
/// <param name="info">The series program info</param>
/// <param name="cancellationToken">The CancellationToken</param>
/// <returns></returns>
public async Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
{
// Dummy method to avoid warnings
await Task.Factory.StartNew<int>(() => { return 0; });
throw new NotImplementedException();
//await CancelSeriesTimerAsync(info.Id, cancellationToken);
//await CreateSeriesTimerAsync(info, cancellationToken);
}
/// <summary>
/// Cancel the Series Timer
/// </summary>
/// <param name="timerId">The Timer Id</param>
/// <param name="cancellationToken">The CancellationToken</param>
/// <returns></returns>
public async Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken)
{
ensureConnection();
int timeOut = await WaitForInitialLoadTask(cancellationToken);
if (timeOut == -1 || cancellationToken.IsCancellationRequested)
{
_logger.Info("[TVHclient] CancelSeriesTimerAsync, call canceled or timed out.");
return;
}
HTSMessage deleteAutorecMessage = new HTSMessage();
deleteAutorecMessage.Method = "deleteAutorecEntry";
deleteAutorecMessage.putField("id", timerId);
//HTSMessage deleteAutorecResponse = await Task.Factory.StartNew<HTSMessage>(() =>
//{
// LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
// _htsConnection.sendMessage(deleteAutorecMessage, lbrh);
// return lbrh.getResponse();
//});
TaskWithTimeoutRunner<HTSMessage> twtr = new TaskWithTimeoutRunner<HTSMessage>(TIMEOUT);
TaskWithTimeoutResult<HTSMessage> twtRes = await twtr.RunWithTimeout(Task.Factory.StartNew<HTSMessage>(() =>
{
LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
_htsConnection.sendMessage(deleteAutorecMessage, lbrh);
return lbrh.getResponse();
}));
if (twtRes.HasTimeout)
{
_logger.Error("[TVHclient] Can't delete recording because of timeout");
}
else
{
HTSMessage deleteAutorecResponse = twtRes.Result;
Boolean success = deleteAutorecResponse.getInt("success", 0) == 1;
if (!success)
{
_logger.Error("[TVHclient] Can't cancel timer: '" + deleteAutorecResponse.getString("error") + "'");
}
}
}
public Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public async Task<MediaSourceInfo> GetChannelStream(string channelId, string mediaSourceId, CancellationToken cancellationToken)
{
ensureConnection();
HTSMessage getTicketMessage = new HTSMessage();
getTicketMessage.Method = "getTicket";
getTicketMessage.putField("channelId", channelId);
//HTSMessage getTicketResponse = await Task.Factory.StartNew<HTSMessage>(() =>
//{
// LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
// _htsConnection.sendMessage(getTicketMessage, lbrh);
// return lbrh.getResponse();
//});
TaskWithTimeoutRunner<HTSMessage> twtr = new TaskWithTimeoutRunner<HTSMessage>(TIMEOUT);
TaskWithTimeoutResult<HTSMessage> twtRes = await twtr.RunWithTimeout(Task.Factory.StartNew<HTSMessage>(() =>
{
LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
_htsConnection.sendMessage(getTicketMessage, lbrh);
return lbrh.getResponse();
}));
if (twtRes.HasTimeout)
{
_logger.Error("[TVHclient] Can't delete recording because of timeout");
}
else
{
HTSMessage getTicketResponse = twtRes.Result;
if (_subscriptionId == int.MaxValue)
{
_subscriptionId = 0;
}
int currSubscriptionId = _subscriptionId++;
return new MediaSourceInfo
{
Id = "" + currSubscriptionId,
Path = _httpBaseUrl + getTicketResponse.getString("path") + "?ticket=" + getTicketResponse.getString("ticket"),
Protocol = MediaProtocol.Http,
MediaStreams = new List<MediaStream>
{
new MediaStream
{
Type = MediaStreamType.Video,
// Set the index to -1 because we don't know the exact index of the video stream within the container
Index = -1,
// Set to true if unknown to enable deinterlacing
IsInterlaced = true
},
new MediaStream
{
Type = MediaStreamType.Audio,
// Set the index to -1 because we don't know the exact index of the audio stream within the container
Index = -1
}
}
};
}
throw new TimeoutException("");
}
public async Task<MediaSourceInfo> GetRecordingStream(string recordingId, string mediaSourceId, CancellationToken cancellationToken)
{
ensureConnection();
HTSMessage getTicketMessage = new HTSMessage();
getTicketMessage.Method = "getTicket";
getTicketMessage.putField("dvrId", recordingId);
//HTSMessage getTicketResponse = await Task.Factory.StartNew<HTSMessage>(() =>
//{
// LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
// _htsConnection.sendMessage(getTicketMessage, lbrh);
// return lbrh.getResponse();
//});
TaskWithTimeoutRunner<HTSMessage> twtr = new TaskWithTimeoutRunner<HTSMessage>(TIMEOUT);
TaskWithTimeoutResult<HTSMessage> twtRes = await twtr.RunWithTimeout(Task.Factory.StartNew<HTSMessage>(() =>
{
LoopBackResponseHandler lbrh = new LoopBackResponseHandler();
_htsConnection.sendMessage(getTicketMessage, lbrh);
return lbrh.getResponse();
}));
if (twtRes.HasTimeout)
{
_logger.Error("[TVHclient] Can't delete recording because of timeout");
}
else
{
HTSMessage getTicketResponse = twtRes.Result;
if (_subscriptionId == int.MaxValue)
{
_subscriptionId = 0;
}
int currSubscriptionId = _subscriptionId++;
return new MediaSourceInfo
{
Id = "" + currSubscriptionId,
Path = _httpBaseUrl + getTicketResponse.getString("path") + "?ticket=" + getTicketResponse.getString("ticket"),
Protocol = MediaProtocol.Http,
MediaStreams = new List<MediaStream>
{
new MediaStream
{
Type = MediaStreamType.Video,
// Set the index to -1 because we don't know the exact index of the video stream within the container
Index = -1,
// Set to true if unknown to enable deinterlacing
IsInterlaced = true
},
new MediaStream
{
Type = MediaStreamType.Audio,
// Set the index to -1 because we don't know the exact index of the audio stream within the container
Index = -1
}
}
};
}
throw new TimeoutException();
}
public async Task CloseLiveStream(string subscriptionId, CancellationToken cancellationToken)
{
await Task.Factory.StartNew<string>(() =>
{
//_logger.Info("[TVHclient] CloseLiveStream for subscriptionId = " + subscriptionId);
return subscriptionId;
});
}
public async Task CopyFilesAsync(StreamReader source, StreamWriter destination)
{
char[] buffer = new char[0x1000];
int numRead;
while ((numRead = await source.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
await destination.WriteAsync(buffer, 0, numRead);
}
}
public async Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
{
return await Task.Factory.StartNew<SeriesTimerInfo>(() =>
{
return new SeriesTimerInfo
{
PostPaddingSeconds = 0,
PrePaddingSeconds = 0,
RecordAnyChannel = true,
RecordAnyTime = true,
RecordNewOnly = false
};
});
}
public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
{
ensureConnection();
int timeOut = await WaitForInitialLoadTask(cancellationToken);
if (timeOut == -1 || cancellationToken.IsCancellationRequested)
{
_logger.Info("[TVHclient] GetProgramsAsync, call canceled or timed out - returning empty list.");
return new List<ProgramInfo>();
}
GetEventsResponseHandler currGetEventsResponseHandler = new GetEventsResponseHandler(startDateUtc, endDateUtc, _logger, cancellationToken);
HTSMessage queryEvents = new HTSMessage();
queryEvents.Method = "getEvents";
queryEvents.putField("channelId", Convert.ToInt32(channelId));
_htsConnection.sendMessage(queryEvents, currGetEventsResponseHandler);
//IEnumerable<ProgramInfo> pi = await currGetEventsResponseHandler.GetEvents(cancellationToken);
//return pi;
TaskWithTimeoutRunner<IEnumerable<ProgramInfo>> twtr = new TaskWithTimeoutRunner<IEnumerable<ProgramInfo>>(TIMEOUT);
TaskWithTimeoutResult<IEnumerable<ProgramInfo>> twtRes = await
twtr.RunWithTimeout(currGetEventsResponseHandler.GetEvents(cancellationToken));
if (twtRes.HasTimeout)
{
return new List<ProgramInfo>();
}
return twtRes.Result;
}
public Task RecordLiveStream(string id, CancellationToken cancellationToken)
{
_logger.Info("[TVHclient] RecordLiveStream " + id);
throw new NotImplementedException();
}
public async Task<LiveTvServiceStatusInfo> GetStatusInfoAsync(CancellationToken cancellationToken)
{
ensureConnection();
int timeOut = await WaitForInitialLoadTask(cancellationToken);
if (timeOut == -1 || cancellationToken.IsCancellationRequested)
{
_logger.Info("[TVHclient] GetStatusInfoAsync, call canceled or timed out.");
return new LiveTvServiceStatusInfo
{
Status = LiveTvServiceStatus.Unavailable
};
}
string serverName = _htsConnection.getServername();
string serverVersion = _htsConnection.getServerversion();
int serverProtokollVersion = _htsConnection.getServerProtocolVersion();
string diskSpace = _htsConnection.getDiskspace();
string serverVersionMessage = "<p>" + serverName + " " + serverVersion + "</p>"
+ "<p>HTSP protokoll version: " + serverProtokollVersion + "</p>"
+ "<p>Free diskspace: " + diskSpace + "</p>";
//List<LiveTvTunerInfo> tvTunerInfos = await _tunerDataHelper.buildTunerInfos(cancellationToken);
TaskWithTimeoutRunner<List<LiveTvTunerInfo>> twtr = new TaskWithTimeoutRunner<List<LiveTvTunerInfo>>(TIMEOUT);
TaskWithTimeoutResult<List<LiveTvTunerInfo>> twtRes = await
twtr.RunWithTimeout(_tunerDataHelper.buildTunerInfos(cancellationToken));
List<LiveTvTunerInfo> tvTunerInfos;
if (twtRes.HasTimeout)
{
tvTunerInfos = new List<LiveTvTunerInfo>();
}
else
{
tvTunerInfos = twtRes.Result;
}
return new LiveTvServiceStatusInfo
{
Version = serverVersionMessage,
Tuners = tvTunerInfos,
Status = LiveTvServiceStatus.Ok,
};
}
public string HomePageUrl
{
get { return "http://tvheadend.org/"; }
}
public Task ResetTuner(string id, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
{
string piconData = _channelDataHelper.getPiconData(channelId);
if (piconData == null)
{
// Leave as is. This is handled by supplying image url to ChannelInfo
throw new NotImplementedException();
}
_logger.Info("[TVHclient] LiveTvService.GetChannelImageAsync called for channelID '" + channelId + "' piconData '" + piconData + "'");
throw new NotImplementedException();
}
public Task<ImageStream> GetProgramImageAsync(string programId, string channelId, CancellationToken cancellationToken)
{
// Leave as is. This is handled by supplying image url to ProgramInfo
throw new NotImplementedException();
}
public Task<ImageStream> GetRecordingImageAsync(string recordingId, CancellationToken cancellationToken)
{
// Leave as is. This is handled by supplying image url to RecordingInfo
throw new NotImplementedException();
}
public Task<ChannelMediaInfo> GetChannelStream(string channelId, CancellationToken cancellationToken)
{
_logger.Fatal("[TVHclient] LiveTvService.GetChannelStream called for channelID '" + channelId + "'");
throw new NotImplementedException();
}
public Task<ChannelMediaInfo> GetRecordingStream(string recordingId, CancellationToken cancellationToken)
{
_logger.Fatal("[TVHclient] LiveTvService.GetRecordingStream called for recordingId '" + recordingId + "'");
throw new NotImplementedException();
}
public event EventHandler DataSourceChanged;
private void sendDataSourceChanged()
{
try
{
EventHandler handler = DataSourceChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
catch (Exception ex)
{
_logger.Error("[TVHclient] LiveTvService.sendDataSourceChanged caught exception: " + ex.Message);
}
}
public event EventHandler<RecordingStatusChangedEventArgs> RecordingStatusChanged;
private void sendRecordingStatusChanged()
{
EventHandler<RecordingStatusChangedEventArgs> handler = RecordingStatusChanged;
if (handler != null)
{
handler(this, new RecordingStatusChangedEventArgs());
}
}
public void onMessage(HTSMessage response)
{
if (response != null)
{
switch (response.Method)
{
case "tagAdd":
case "tagUpdate":
case "tagDelete":
//_logger.Fatal("[TVHclient] tad add/update/delete" + response.ToString());
break;
case "channelAdd":
case "channelUpdate":
_channelDataHelper.add(response);
break;
case "dvrEntryAdd":
_dvrDataHelper.dvrEntryAdd(response);
sendRecordingStatusChanged();
break;
case "dvrEntryUpdate":
_dvrDataHelper.dvrEntryUpdate(response);
sendRecordingStatusChanged();
break;
case "dvrEntryDelete":
_dvrDataHelper.dvrEntryDelete(response);
sendRecordingStatusChanged();
break;
case "autorecEntryAdd":
_autorecDataHelper.autorecEntryAdd(response);
sendRecordingStatusChanged();
break;
case "autorecEntryUpdate":
_autorecDataHelper.autorecEntryUpdate(response);
sendRecordingStatusChanged();
break;
case "autorecEntryDelete":
_autorecDataHelper.autorecEntryDelete(response);
sendRecordingStatusChanged();
break;
case "eventAdd":
case "eventUpdate":
case "eventDelete":
// should not happen as we don't subscribe for this events.
break;
//case "subscriptionStart":
//case "subscriptionGrace":
//case "subscriptionStop":
//case "subscriptionSkip":
//case "subscriptionSpeed":
//case "subscriptionStatus":
// _logger.Fatal("[TVHclient] subscription events " + response.ToString());
// break;
//case "queueStatus":
// _logger.Fatal("[TVHclient] queueStatus event " + response.ToString());
// break;
//case "signalStatus":
// _logger.Fatal("[TVHclient] signalStatus event " + response.ToString());
// break;
//case "timeshiftStatus":
// _logger.Fatal("[TVHclient] timeshiftStatus event " + response.ToString());
// break;
//case "muxpkt": // streaming data
// _logger.Fatal("[TVHclient] muxpkt event " + response.ToString());
// break;
case "initialSyncCompleted":
_initialLoadFinished = true;
break;
default:
//_logger.Fatal("[TVHclient] Method '" + response.Method + "' not handled in LiveTvService.cs");
break;
}
}
}
public void onError(Exception ex)
{
_logger.ErrorException("[TVHclient] HTSP error: " + ex.Message, ex);
_htsConnection.stop();
_connected = false;
sendDataSourceChanged();
ensureConnection();
throw ex;
}
}
}
| |
/***************************************************************************
copyright : (C) 2006 Novell, Inc.
email : Aaron Bockover <abockover@novell.com>
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
* USA *
***************************************************************************/
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
namespace TagLib
{
public class ListBase<T> : IList<T> where T : IComparable<T>
{
protected List<T> data = new List<T>();
#region Constructors
public ListBase()
{
}
public ListBase(T s)
{
Add(s);
}
public ListBase(ListBase<T> s)
{
Add(s);
}
public ListBase(T [] s)
{
Add(s);
}
#endregion
#region Properties
public bool IsEmpty {
get { return Count == 0; }
}
#endregion
#region Methods
public void Add(ListBase<T> list)
{
if(list != null) {
data.AddRange(list);
}
}
public void Add(T [] list)
{
if(list != null) {
data.AddRange(list);
}
}
public virtual void SortedInsert(T s, bool unique)
{
int i = 0;
for(; i < data.Count; i++) {
if(s.CompareTo(data[i]) == 0 && unique) {
return;
}
if(s.CompareTo(data[i]) <= 0) {
break;
}
}
Insert(i, s);
}
public void SortedInsert(T s)
{
SortedInsert(s, false);
}
public T [] ToArray()
{
return data.ToArray();
}
#endregion
#region IList<T>
public bool IsReadOnly {
get { return false; }
}
public bool IsFixedSize {
get { return false; }
}
public T this[int index] {
get { return data[index]; }
set { data[index] = value; }
}
public void Add(T value)
{
data.Add(value);
}
public void Clear()
{
data.Clear();
}
public bool Contains(T value)
{
return data.Contains(value);
}
public int IndexOf(T value)
{
return data.IndexOf(value);
}
public void Insert(int index, T value)
{
data.Insert(index, value);
}
public bool Remove(T value)
{
return data.Remove(value);
}
public void RemoveAt(int index)
{
data.RemoveAt(index);
}
public string ToString(string separator)
{
StringBuilder builder = new StringBuilder();
for(int i = 0; i < Count; i++) {
if(i != 0) {
builder.Append(separator);
}
builder.Append(this[i].ToString());
}
return builder.ToString();
}
public override string ToString()
{
return ToString(", ");
}
#endregion
#region ICollection<T>
public int Count {
get { return data.Count; }
}
public bool IsSynchronized {
get { return false; }
}
public object SyncRoot {
get { return this; }
}
public void CopyTo(T [] array, int index)
{
data.CopyTo(array, index);
}
#endregion
#region IEnumerable<T>
IEnumerator IEnumerable.GetEnumerator()
{
return data.GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return data.GetEnumerator();
}
#endregion
}
}
| |
namespace Sample
{
public class Shakespeare
{
public static string[] Titles =
{
"Henry IV (1)",
"Henry V",
"Henry VIII",
"Richard II",
"Richard III",
"Merchant of Venice",
"Othello",
"King Lear"
};
public static string[] Dialogue =
{
"So shaken as we are, so wan with care," +
"Find we a time for frighted peace to pant," +
"And breathe short-winded accents of new broils" +
"To be commenced in strands afar remote." +
"No more the thirsty entrance of this soil" +
"Shall daub her lips with her own children's blood;" +
"Nor more shall trenching war channel her fields," +
"Nor bruise her flowerets with the armed hoofs" +
"Of hostile paces: those opposed eyes," +
"Which, like the meteors of a troubled heaven," +
"All of one nature, of one substance bred," +
"Did lately meet in the intestine shock" +
"And furious close of civil butchery" +
"Shall now, in mutual well-beseeming ranks," +
"March all one way and be no more opposed" +
"Against acquaintance, kindred and allies:" +
"The edge of war, like an ill-sheathed knife," +
"No more shall cut his master. Therefore, friends," +
"As far as to the sepulchre of Christ," +
"Whose soldier now, under whose blessed cross" +
"We are impressed and engaged to fight," +
"Forthwith a power of English shall we levy;" +
"Whose arms were moulded in their mothers' womb" +
"To chase these pagans in those holy fields" +
"Over whose acres walk'd those blessed feet" +
"Which fourteen hundred years ago were nail'd" +
"For our advantage on the bitter cross." +
"But this our purpose now is twelve month old," +
"And bootless 'tis to tell you we will go:" +
"Therefore we meet not now. Then let me hear" +
"Of you, my gentle cousin Westmoreland," +
"What yesternight our council did decree" +
"In forwarding this dear expedience.",
"Hear him but reason in divinity," +
"And all-admiring with an inward wish" +
"You would desire the king were made a prelate:" +
"Hear him debate of commonwealth affairs," +
"You would say it hath been all in all his study:" +
"List his discourse of war, and you shall hear" +
"A fearful battle render'd you in music:" +
"Turn him to any cause of policy," +
"The Gordian knot of it he will unloose," +
"Familiar as his garter: that, when he speaks," +
"The air, a charter'd libertine, is still," +
"And the mute wonder lurketh in men's ears," +
"To steal his sweet and honey'd sentences;" +
"So that the art and practic part of life" +
"Must be the mistress to this theoric:" +
"Which is a wonder how his grace should glean it," +
"Since his addiction was to courses vain," +
"His companies unletter'd, rude and shallow," +
"His hours fill'd up with riots, banquets, sports," +
"And never noted in him any study," +
"Any retirement, any sequestration" +
"From open haunts and popularity.",
"I come no more to make you laugh: things now," +
"That bear a weighty and a serious brow," +
"Sad, high, and working, full of state and woe," +
"Such noble scenes as draw the eye to flow," +
"We now present. Those that can pity, here" +
"May, if they think it well, let fall a tear;" +
"The subject will deserve it. Such as give" +
"Their money out of hope they may believe," +
"May here find truth too. Those that come to see" +
"Only a show or two, and so agree" +
"The play may pass, if they be still and willing," +
"I'll undertake may see away their shilling" +
"Richly in two short hours. Only they" +
"That come to hear a merry bawdy play," +
"A noise of targets, or to see a fellow" +
"In a long motley coat guarded with yellow," +
"Will be deceived; for, gentle hearers, know," +
"To rank our chosen truth with such a show" +
"As fool and fight is, beside forfeiting" +
"Our own brains, and the opinion that we bring," +
"To make that only true we now intend," +
"Will leave us never an understanding friend." +
"Therefore, for goodness' sake, and as you are known" +
"The first and happiest hearers of the town," +
"Be sad, as we would make ye: think ye see" +
"The very persons of our noble story" +
"As they were living; think you see them great," +
"And follow'd with the general throng and sweat" +
"Of thousand friends; then in a moment, see" +
"How soon this mightiness meets misery:" +
"And, if you can be merry then, I'll say" +
"A man may weep upon his wedding-day.",
"First, heaven be the record to my speech!" +
"In the devotion of a subject's love," +
"Tendering the precious safety of my prince," +
"And free from other misbegotten hate," +
"Come I appellant to this princely presence." +
"Now, Thomas Mowbray, do I turn to thee," +
"And mark my greeting well; for what I speak" +
"My body shall make good upon this earth," +
"Or my divine soul answer it in heaven." +
"Thou art a traitor and a miscreant," +
"Too good to be so and too bad to live," +
"Since the more fair and crystal is the sky," +
"The uglier seem the clouds that in it fly." +
"Once more, the more to aggravate the note," +
"With a foul traitor's name stuff I thy throat;" +
"And wish, so please my sovereign, ere I move," +
"What my tongue speaks my right drawn sword may prove.",
"Now is the winter of our discontent" +
"Made glorious summer by this sun of York;" +
"And all the clouds that lour'd upon our house" +
"In the deep bosom of the ocean buried." +
"Now are our brows bound with victorious wreaths;" +
"Our bruised arms hung up for monuments;" +
"Our stern alarums changed to merry meetings," +
"Our dreadful marches to delightful measures." +
"Grim-visaged war hath smooth'd his wrinkled front;" +
"And now, instead of mounting barded steeds" +
"To fright the souls of fearful adversaries," +
"He capers nimbly in a lady's chamber" +
"To the lascivious pleasing of a lute." +
"But I, that am not shaped for sportive tricks," +
"Nor made to court an amorous looking-glass;" +
"I, that am rudely stamp'd, and want love's majesty" +
"To strut before a wanton ambling nymph;" +
"I, that am curtail'd of this fair proportion," +
"Cheated of feature by dissembling nature," +
"Deformed, unfinish'd, sent before my time" +
"Into this breathing world, scarce half made up," +
"And that so lamely and unfashionable" +
"That dogs bark at me as I halt by them;" +
"Why, I, in this weak piping time of peace," +
"Have no delight to pass away the time," +
"Unless to spy my shadow in the sun" +
"And descant on mine own deformity:" +
"And therefore, since I cannot prove a lover," +
"To entertain these fair well-spoken days," +
"I am determined to prove a villain" +
"And hate the idle pleasures of these days." +
"Plots have I laid, inductions dangerous," +
"By drunken prophecies, libels and dreams," +
"To set my brother Clarence and the king" +
"In deadly hate the one against the other:" +
"And if King Edward be as true and just" +
"As I am subtle, false and treacherous," +
"This day should Clarence closely be mew'd up," +
"About a prophecy, which says that 'G'" +
"Of Edward's heirs the murderer shall be." +
"Dive, thoughts, down to my soul: here" +
"Clarence comes.",
"To bait fish withal: if it will feed nothing else," +
"it will feed my revenge. He hath disgraced me, and" +
"hindered me half a million; laughed at my losses," +
"mocked at my gains, scorned my nation, thwarted my" +
"bargains, cooled my friends, heated mine" +
"enemies; and what's his reason? I am a Jew. Hath" +
"not a Jew eyes? hath not a Jew hands, organs," +
"dimensions, senses, affections, passions? fed with" +
"the same food, hurt with the same weapons, subject" +
"to the same diseases, healed by the same means," +
"warmed and cooled by the same winter and summer, as" +
"a Christian is? If you prick us, do we not bleed?" +
"if you tickle us, do we not laugh? if you poison" +
"us, do we not die? and if you wrong us, shall we not" +
"revenge? If we are like you in the rest, we will" +
"resemble you in that. If a Jew wrong a Christian," +
"what is his humility? Revenge. If a Christian" +
"wrong a Jew, what should his sufferance be by" +
"Christian example? Why, revenge. The villany you" +
"teach me, I will execute, and it shall go hard but I" +
"will better the instruction.",
"Virtue! a fig! 'tis in ourselves that we are thus" +
"or thus. Our bodies are our gardens, to the which" +
"our wills are gardeners: so that if we will plant" +
"nettles, or sow lettuce, set hyssop and weed up" +
"thyme, supply it with one gender of herbs, or" +
"distract it with many, either to have it sterile" +
"with idleness, or manured with industry, why, the" +
"power and corrigible authority of this lies in our" +
"wills. If the balance of our lives had not one" +
"scale of reason to poise another of sensuality, the" +
"blood and baseness of our natures would conduct us" +
"to most preposterous conclusions: but we have" +
"reason to cool our raging motions, our carnal" +
"stings, our unbitted lusts, whereof I take this that" +
"you call love to be a sect or scion.",
"Blow, winds, and crack your cheeks! rage! blow!" +
"You cataracts and hurricanoes, spout" +
"Till you have drench'd our steeples, drown'd the cocks!" +
"You sulphurous and thought-executing fires," +
"Vaunt-couriers to oak-cleaving thunderbolts," +
"Singe my white head! And thou, all-shaking thunder," +
"Smite flat the thick rotundity o' the world!" +
"Crack nature's moulds, an germens spill at once," +
"That make ingrateful man!"
};
}
}
| |
// Copyright 2008 Adrian Akison
// Distributed under license terms of CPOL http://www.codeproject.com/info/cpol10.aspx
using System;
using System.Collections.Generic;
using System.Text;
namespace MCEBuddy.Util.Combinatorics {
/// <summary>
/// Variations defines a meta-collection, typically a list of lists, of all possible
/// ordered subsets of a particular size from the set of values.
/// This list is enumerable and allows the scanning of all possible Variations using a simple
/// foreach() loop even though the variations are not all in memory.
/// </summary>
/// <remarks>
/// The MetaCollectionType parameter of the constructor allows for the creation of
/// normal Variations and Variations with Repetition.
///
/// When given an input collect {A B C} and lower index of 2, the following sets are generated:
/// MetaCollectionType.WithoutRepetition generates 6 sets: =>
/// {A B}, {A B}, {B A}, {B C}, {C A}, {C B}
/// MetaCollectionType.WithRepetition generates 9 sets:
/// {A A}, {A B}, {A B}, {B A}, {B B }, {B C}, {C A}, {C B}, {C C}
///
/// The equality of multiple inputs is not considered when generating variations.
/// </remarks>
/// <typeparam name="T">The type of the values within the list.</typeparam>
public class Variations<T> : IMetaCollection<T> {
#region Constructors
/// <summary>
/// No default constructor, must provided a list of values and size.
/// </summary>
protected Variations() {
;
}
/// <summary>
/// Create a variation set from the indicated list of values.
/// The upper index is calculated as values.Count, the lower index is specified.
/// Collection type defaults to MetaCollectionType.WithoutRepetition
/// </summary>
/// <param name="values">List of values to select Variations from.</param>
/// <param name="lowerIndex">The size of each variation set to return.</param>
public Variations(IList<T> values, int lowerIndex) {
Initialize(values, lowerIndex, GenerateOption.WithoutRepetition);
}
/// <summary>
/// Create a variation set from the indicated list of values.
/// The upper index is calculated as values.Count, the lower index is specified.
/// </summary>
/// <param name="values">List of values to select variations from.</param>
/// <param name="lowerIndex">The size of each vatiation set to return.</param>
/// <param name="type">Type indicates whether to use repetition in set generation.</param>
public Variations(IList<T> values, int lowerIndex, GenerateOption type) {
Initialize(values, lowerIndex, type);
}
#endregion
#region IEnumerable Interface
/// <summary>
/// Gets an enumerator for the collection of Variations.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<IList<T>> GetEnumerator() {
if(Type == GenerateOption.WithRepetition) {
return new EnumeratorWithRepetition(this);
}
else {
return new EnumeratorWithoutRepetition(this);
}
}
/// <summary>
/// Gets an enumerator for the collection of Variations.
/// </summary>
/// <returns>The enumerator.</returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
if(Type == GenerateOption.WithRepetition) {
return new EnumeratorWithRepetition(this);
}
else {
return new EnumeratorWithoutRepetition(this);
}
}
#endregion
#region Enumerator Inner Class
/// <summary>
/// An enumerator for Variations when the type is set to WithRepetition.
/// </summary>
public class EnumeratorWithRepetition : IEnumerator<IList<T>> {
#region Constructors
/// <summary>
/// Construct a enumerator with the parent object.
/// </summary>
/// <param name="source">The source Variations object.</param>
public EnumeratorWithRepetition(Variations<T> source) {
myParent = source;
Reset();
}
#endregion
#region IEnumerator interface
/// <summary>
/// Resets the Variations enumerator to the first variation.
/// </summary>
public void Reset() {
myCurrentList = null;
myListIndexes = null;
}
/// <summary>
/// Advances to the next variation.
/// </summary>
/// <returns>True if successfully moved to next variation, False if no more variations exist.</returns>
/// <remarks>
/// Increments the internal myListIndexes collection by incrementing the last index
/// and overflow/carrying into others just like grade-school arithemtic. If the
/// finaly carry flag is set, then we would wrap around and are therefore done.
/// </remarks>
public bool MoveNext() {
int carry = 1;
if(myListIndexes == null) {
myListIndexes = new List<int>();
for(int i = 0; i < myParent.LowerIndex; ++i) {
myListIndexes.Add(0);
}
carry = 0;
}
else {
for(int i = myListIndexes.Count - 1; i >= 0 && carry > 0; --i) {
myListIndexes[i] += carry;
carry = 0;
if(myListIndexes[i] >= myParent.UpperIndex) {
myListIndexes[i] = 0;
carry = 1;
}
}
}
myCurrentList = null;
return carry != 1;
}
/// <summary>
/// The current variation
/// </summary>
public IList<T> Current {
get {
ComputeCurrent();
return myCurrentList;
}
}
/// <summary>
/// The current variation.
/// </summary>
object System.Collections.IEnumerator.Current {
get {
ComputeCurrent();
return myCurrentList;
}
}
/// <summary>
/// Cleans up non-managed resources, of which there are none used here.
/// </summary>
public void Dispose() {
;
}
#endregion
#region Heavy Lifting Members
/// <summary>
/// Computes the current list based on the internal list index.
/// </summary>
private void ComputeCurrent() {
if(myCurrentList == null) {
myCurrentList = new List<T>();
foreach(int index in myListIndexes) {
myCurrentList.Add(myParent.myValues[index]);
}
}
}
#endregion
#region Data
/// <summary>
/// Parent object this is an enumerator for.
/// </summary>
private Variations<T> myParent;
/// <summary>
/// The current list of values, this is lazy evaluated by the Current property.
/// </summary>
private List<T> myCurrentList;
/// <summary>
/// An enumertor of the parents list of lexicographic orderings.
/// </summary>
private List<int> myListIndexes;
#endregion
}
/// <summary>
/// An enumerator for Variations when the type is set to WithoutRepetition.
/// </summary>
public class EnumeratorWithoutRepetition : IEnumerator<IList<T>> {
#region Constructors
/// <summary>
/// Construct a enumerator with the parent object.
/// </summary>
/// <param name="source">The source Variations object.</param>
public EnumeratorWithoutRepetition(Variations<T> source) {
myParent = source;
myPermutationsEnumerator = (Permutations<int>.Enumerator)myParent.myPermutations.GetEnumerator();
}
#endregion
#region IEnumerator interface
/// <summary>
/// Resets the Variations enumerator to the first variation.
/// </summary>
public void Reset() {
myPermutationsEnumerator.Reset();
}
/// <summary>
/// Advances to the next variation.
/// </summary>
/// <returns>True if successfully moved to next variation, False if no more variations exist.</returns>
public bool MoveNext() {
bool ret = myPermutationsEnumerator.MoveNext();
myCurrentList = null;
return ret;
}
/// <summary>
/// The current variation.
/// </summary>
public IList<T> Current {
get {
ComputeCurrent();
return myCurrentList;
}
}
/// <summary>
/// The current variation.
/// </summary>
object System.Collections.IEnumerator.Current {
get {
ComputeCurrent();
return myCurrentList;
}
}
/// <summary>
/// Cleans up non-managed resources, of which there are none used here.
/// </summary>
public void Dispose() {
;
}
#endregion
#region Heavy Lifting Members
/// <summary>
/// Creates a list of original values from the int permutation provided.
/// The exception for accessing current (InvalidOperationException) is generated
/// by the call to .Current on the underlying enumeration.
/// </summary>
/// <remarks>
/// To compute the current list of values, the element to use is determined by
/// a permutation position with a non-MaxValue value. It is placed at the position in the
/// output that the index value indicates.
///
/// E.g. Variations of 6 choose 3 without repetition
/// Input array: {A B C D E F}
/// Permutations: {- 1 - - 3 2} (- is Int32.MaxValue)
/// Generates set: {B F E}
/// </remarks>
private void ComputeCurrent() {
if(myCurrentList == null) {
myCurrentList = new List<T>();
int index = 0;
IList<int> currentPermutation = (IList<int>)myPermutationsEnumerator.Current;
for(int i = 0; i < myParent.LowerIndex; ++i) {
myCurrentList.Add(myParent.myValues[0]);
}
for(int i = 0; i < currentPermutation.Count; ++i) {
int position = currentPermutation[i];
if(position != Int32.MaxValue) {
myCurrentList[position] = myParent.myValues[index];
if(myParent.Type == GenerateOption.WithoutRepetition) {
++index;
}
}
else {
++index;
}
}
}
}
#endregion
#region Data
/// <summary>
/// Parent object this is an enumerator for.
/// </summary>
private Variations<T> myParent;
/// <summary>
/// The current list of values, this is lazy evaluated by the Current property.
/// </summary>
private List<T> myCurrentList;
/// <summary>
/// An enumertor of the parents list of lexicographic orderings.
/// </summary>
private Permutations<int>.Enumerator myPermutationsEnumerator;
#endregion
}
#endregion
#region IMetaList Interface
/// <summary>
/// The number of unique variations that are defined in this meta-collection.
/// </summary>
/// <remarks>
/// Variations with repetitions does not behave like other meta-collections and it's
/// count is equal to N^P, where N is the upper index and P is the lower index.
/// </remarks>
public long Count {
get {
if(Type == GenerateOption.WithoutRepetition) {
return myPermutations.Count;
}
else {
return (long)Math.Pow(UpperIndex, LowerIndex);
}
}
}
/// <summary>
/// The type of Variations set that is generated.
/// </summary>
public GenerateOption Type {
get {
return myMetaCollectionType;
}
}
/// <summary>
/// The upper index of the meta-collection, equal to the number of items in the initial set.
/// </summary>
public int UpperIndex {
get {
return myValues.Count;
}
}
/// <summary>
/// The lower index of the meta-collection, equal to the number of items returned each iteration.
/// </summary>
public int LowerIndex {
get {
return myLowerIndex;
}
}
#endregion
#region Heavy Lifting Members
/// <summary>
/// Initialize the variations for constructors.
/// </summary>
/// <param name="values">List of values to select variations from.</param>
/// <param name="lowerIndex">The size of each variation set to return.</param>
/// <param name="type">The type of variations set to generate.</param>
private void Initialize(IList<T> values, int lowerIndex, GenerateOption type) {
myMetaCollectionType = type;
myLowerIndex = lowerIndex;
myValues = new List<T>();
myValues.AddRange(values);
if(type == GenerateOption.WithoutRepetition) {
List<int> myMap = new List<int>();
int index = 0;
for(int i = 0; i < myValues.Count; ++i) {
if(i >= myValues.Count - myLowerIndex) {
myMap.Add(index++);
}
else {
myMap.Add(Int32.MaxValue);
}
}
myPermutations = new Permutations<int>(myMap);
}
else {
; // myPermutations isn't used.
}
}
#endregion
#region Data
/// <summary>
/// Copy of values object is intialized with, required for enumerator reset.
/// </summary>
private List<T> myValues;
/// <summary>
/// Permutations object that handles permutations on int for variation inclusion and ordering.
/// </summary>
private Permutations<int> myPermutations;
/// <summary>
/// The type of the variation collection.
/// </summary>
private GenerateOption myMetaCollectionType;
/// <summary>
/// The lower index defined in the constructor.
/// </summary>
private int myLowerIndex;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Pkcs.Tests
{
public static partial class SignerInfoTests
{
[Fact]
public static void SignerInfo_SignedAttributes_Cached_WhenEmpty()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo signer = cms.SignerInfos[0];
CryptographicAttributeObjectCollection attrs = signer.SignedAttributes;
CryptographicAttributeObjectCollection attrs2 = signer.SignedAttributes;
Assert.Same(attrs, attrs2);
Assert.Empty(attrs);
}
[Fact]
public static void SignerInfo_SignedAttributes_Cached_WhenNonEmpty()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPssDocument);
SignerInfo signer = cms.SignerInfos[0];
CryptographicAttributeObjectCollection attrs = signer.SignedAttributes;
CryptographicAttributeObjectCollection attrs2 = signer.SignedAttributes;
Assert.Same(attrs, attrs2);
Assert.Equal(4, attrs.Count);
}
[Fact]
public static void SignerInfo_UnsignedAttributes_Cached_WhenEmpty()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo signer = cms.SignerInfos[0];
CryptographicAttributeObjectCollection attrs = signer.UnsignedAttributes;
CryptographicAttributeObjectCollection attrs2 = signer.UnsignedAttributes;
Assert.Same(attrs, attrs2);
Assert.Empty(attrs);
Assert.Empty(attrs2);
}
[Fact]
public static void SignerInfo_UnsignedAttributes_Cached_WhenNonEmpty()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);
SignerInfo signer = cms.SignerInfos[0];
CryptographicAttributeObjectCollection attrs = signer.UnsignedAttributes;
CryptographicAttributeObjectCollection attrs2 = signer.UnsignedAttributes;
Assert.Same(attrs, attrs2);
Assert.Single(attrs);
}
[Fact]
public static void SignerInfo_CounterSignerInfos_UniquePerCall_WhenEmpty()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo signer = cms.SignerInfos[0];
SignerInfoCollection counterSigners = signer.CounterSignerInfos;
SignerInfoCollection counterSigners2 = signer.CounterSignerInfos;
Assert.NotSame(counterSigners, counterSigners2);
Assert.Empty(counterSigners);
Assert.Empty(counterSigners2);
}
[Fact]
public static void SignerInfo_CounterSignerInfos_UniquePerCall_WhenNonEmpty()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);
SignerInfo signer = cms.SignerInfos[0];
SignerInfoCollection counterSigners = signer.CounterSignerInfos;
SignerInfoCollection counterSigners2 = signer.CounterSignerInfos;
Assert.NotSame(counterSigners, counterSigners2);
Assert.Single(counterSigners);
Assert.Single(counterSigners2);
for (int i = 0; i < counterSigners.Count; i++)
{
SignerInfo counterSigner = counterSigners[i];
SignerInfo counterSigner2 = counterSigners2[i];
Assert.NotSame(counterSigner, counterSigner2);
Assert.NotSame(counterSigner.Certificate, counterSigner2.Certificate);
Assert.Equal(counterSigner.Certificate, counterSigner2.Certificate);
#if NETCOREAPP
byte[] signature = counterSigner.GetSignature();
byte[] signature2 = counterSigner2.GetSignature();
Assert.NotSame(signature, signature2);
Assert.Equal(signature, signature2);
#endif
}
}
#if NETCOREAPP
[Fact]
public static void SignerInfo_GetSignature_UniquePerCall()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);
SignerInfo signer = cms.SignerInfos[0];
byte[] signature = signer.GetSignature();
byte[] signature2 = signer.GetSignature();
Assert.NotSame(signature, signature2);
Assert.Equal(signature, signature2);
}
#endif
[Fact]
public static void SignerInfo_DigestAlgorithm_NotSame()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);
SignerInfo signer = cms.SignerInfos[0];
Oid oid = signer.DigestAlgorithm;
Oid oid2 = signer.DigestAlgorithm;
Assert.NotSame(oid, oid2);
}
#if NETCOREAPP
[Fact]
public static void SignerInfo_SignatureAlgorithm_NotSame()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);
SignerInfo signer = cms.SignerInfos[0];
Oid oid = signer.SignatureAlgorithm;
Oid oid2 = signer.SignatureAlgorithm;
Assert.NotSame(oid, oid2);
}
#endif
[Fact]
public static void SignerInfo_Certificate_Same()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);
SignerInfo signer = cms.SignerInfos[0];
X509Certificate2 cert = signer.Certificate;
X509Certificate2 cert2 = signer.Certificate;
Assert.Same(cert, cert2);
}
[Fact]
public static void CheckSignature_ThrowsOnNullStore()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPssDocument);
SignerInfo signer = cms.SignerInfos[0];
AssertExtensions.Throws<ArgumentNullException>(
"extraStore",
() => signer.CheckSignature(null, true));
AssertExtensions.Throws<ArgumentNullException>(
"extraStore",
() => signer.CheckSignature(null, false));
}
[Fact]
public static void CheckSignature_ExtraStore_IsAdditional()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo signer = cms.SignerInfos[0];
Assert.NotNull(signer.Certificate);
// Assert.NotThrows
signer.CheckSignature(true);
// Assert.NotThrows
signer.CheckSignature(new X509Certificate2Collection(), true);
}
[Fact]
public static void CheckSignature_MD5WithRSA()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.MD5WithRSADigestAlgorithm);
SignerInfo signer = cms.SignerInfos[0];
Assert.Equal(Oids.RsaPkcs1Md5, signer.DigestAlgorithm.Value);
Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value);
//Assert.NotThrows
signer.CheckSignature(true);
}
[Fact]
public static void CheckSignature_SHA1WithRSA()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.SHA1WithRSADigestAlgorithm);
SignerInfo signer = cms.SignerInfos[0];
Assert.Equal(Oids.RsaPkcs1Sha1, signer.DigestAlgorithm.Value);
Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value);
//Assert.NotThrows
signer.CheckSignature(true);
}
[Fact]
public static void CheckSignature_SHA256WithRSA()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.SHA256WithRSADigestAlgorithm);
SignerInfo signer = cms.SignerInfos[0];
Assert.Equal(Oids.RsaPkcs1Sha256, signer.DigestAlgorithm.Value);
Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value);
//Assert.NotThrows
signer.CheckSignature(true);
}
[Fact]
public static void CheckSignature_SHA384WithRSA()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.SHA384WithRSADigestAlgorithm);
SignerInfo signer = cms.SignerInfos[0];
Assert.Equal(Oids.RsaPkcs1Sha384, signer.DigestAlgorithm.Value);
Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value);
//Assert.NotThrows
signer.CheckSignature(true);
}
[Fact]
public static void CheckSignature_SHA512WithRSA()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.SHA512WithRSADigestAlgorithm);
SignerInfo signer = cms.SignerInfos[0];
Assert.Equal(Oids.RsaPkcs1Sha512, signer.DigestAlgorithm.Value);
Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value);
//Assert.NotThrows
signer.CheckSignature(true);
}
[Fact]
public static void CheckSignature_SHA256WithRSADigest_And_RSA256WithRSASignature()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.SHA256withRSADigestAndSHA256WithRSASignatureAlgorithm);
SignerInfo signer = cms.SignerInfos[0];
Assert.Equal(Oids.RsaPkcs1Sha256, signer.DigestAlgorithm.Value);
Assert.Equal(Oids.RsaPkcs1Sha256, signer.SignatureAlgorithm.Value);
//Assert.NotThrows
signer.CheckSignature(true);
}
[Fact]
public static void CheckSignature_ECDSA256SignedWithRSASha256HashIdentifier()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.SHA256ECDSAWithRsaSha256DigestIdentifier);
SignerInfo signer = cms.SignerInfos[0];
Assert.Equal(Oids.RsaPkcs1Sha256, signer.DigestAlgorithm.Value);
Assert.Equal(Oids.EcdsaSha256, signer.SignatureAlgorithm.Value);
// Assert.NotThrows
signer.CheckSignature(true);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")]
public static void RemoveCounterSignature_MatchesIssuerAndSerialNumber()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signerInfo = cms.SignerInfos[0];
SignerInfo counterSigner = signerInfo.CounterSignerInfos[1];
Assert.Equal(
SubjectIdentifierType.IssuerAndSerialNumber,
counterSigner.SignerIdentifier.Type);
int countBefore = cms.Certificates.Count;
Assert.NotEqual(signerInfo.Certificate, counterSigner.Certificate);
signerInfo.RemoveCounterSignature(counterSigner);
Assert.Single(cms.SignerInfos);
// Removing a CounterSigner doesn't update the current object, it updates
// the underlying SignedCms object, and a new signer has to be retrieved.
Assert.Equal(2, signerInfo.CounterSignerInfos.Count);
Assert.Single(cms.SignerInfos[0].CounterSignerInfos);
Assert.Equal(countBefore, cms.Certificates.Count);
// Assert.NotThrows
cms.CheckSignature(true);
cms.CheckHash();
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")]
public static void RemoveCounterSignature_MatchesSubjectKeyIdentifier()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signerInfo = cms.SignerInfos[0];
SignerInfo counterSigner = signerInfo.CounterSignerInfos[0];
Assert.Equal(
SubjectIdentifierType.SubjectKeyIdentifier,
counterSigner.SignerIdentifier.Type);
int countBefore = cms.Certificates.Count;
Assert.Equal(signerInfo.Certificate, counterSigner.Certificate);
signerInfo.RemoveCounterSignature(counterSigner);
Assert.Single(cms.SignerInfos);
// Removing a CounterSigner doesn't update the current object, it updates
// the underlying SignedCms object, and a new signer has to be retrieved.
Assert.Equal(2, signerInfo.CounterSignerInfos.Count);
Assert.Single(cms.SignerInfos[0].CounterSignerInfos);
// This certificate is still in use, since we counter-signed ourself,
// and the remaining countersigner is us.
Assert.Equal(countBefore, cms.Certificates.Count);
// Assert.NotThrows
cms.CheckSignature(true);
cms.CheckHash();
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")]
public static void RemoveCounterSignature_MatchesNoSignature()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1CounterSignedWithNoSignature);
SignerInfo signerInfo = cms.SignerInfos[0];
SignerInfo counterSigner = signerInfo.CounterSignerInfos[0];
Assert.Single(signerInfo.CounterSignerInfos);
Assert.Equal(SubjectIdentifierType.NoSignature, counterSigner.SignerIdentifier.Type);
int countBefore = cms.Certificates.Count;
// cms.CheckSignature fails because there's a NoSignature countersigner:
Assert.Throws<CryptographicException>(() => cms.CheckSignature(true));
signerInfo.RemoveCounterSignature(counterSigner);
// Removing a CounterSigner doesn't update the current object, it updates
// the underlying SignedCms object, and a new signer has to be retrieved.
Assert.Single(signerInfo.CounterSignerInfos);
Assert.Empty(cms.SignerInfos[0].CounterSignerInfos);
// This certificate is still in use, since we counter-signed ourself,
// and the remaining countersigner is us.
Assert.Equal(countBefore, cms.Certificates.Count);
// And we succeed now, because we got rid of the NoSignature signer.
cms.CheckSignature(true);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")]
public static void RemoveCounterSignature_UsesLiveState()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signerInfo = cms.SignerInfos[0];
SignerInfo counterSigner = signerInfo.CounterSignerInfos[0];
Assert.Equal(
SubjectIdentifierType.SubjectKeyIdentifier,
counterSigner.SignerIdentifier.Type);
int countBefore = cms.Certificates.Count;
Assert.Equal(signerInfo.Certificate, counterSigner.Certificate);
signerInfo.RemoveCounterSignature(counterSigner);
Assert.Single(cms.SignerInfos);
// Removing a CounterSigner doesn't update the current object, it updates
// the underlying SignedCms object, and a new signer has to be retrieved.
Assert.Equal(2, signerInfo.CounterSignerInfos.Count);
Assert.Single(cms.SignerInfos[0].CounterSignerInfos);
Assert.Equal(countBefore, cms.Certificates.Count);
// Even though the CounterSignerInfos collection still contains this, the live
// document doesn't.
Assert.Throws<CryptographicException>(
() => signerInfo.RemoveCounterSignature(counterSigner));
// Assert.NotThrows
cms.CheckSignature(true);
cms.CheckHash();
}
[Fact]
public static void RemoveCounterSignature_WithNoMatch()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signerInfo = cms.SignerInfos[0];
// Even though we counter-signed ourself, the counter-signer version of us
// is SubjectKeyIdentifier, and we're IssuerAndSerialNumber, so no match.
Assert.Throws<CryptographicException>(
() => signerInfo.RemoveCounterSignature(signerInfo));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug")]
public static void RemoveCounterSignature_EncodedInSingleAttribute(int indexToRemove)
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1TwoCounterSignaturesInSingleAttribute);
SignerInfo signerInfo = cms.SignerInfos[0];
Assert.Equal(2, signerInfo.CounterSignerInfos.Count);
signerInfo.RemoveCounterSignature(indexToRemove);
Assert.Equal(1, signerInfo.CounterSignerInfos.Count);
cms.CheckSignature(true);
}
[Fact]
public static void RemoveCounterSignature_Null()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
Assert.Equal(2, cms.SignerInfos[0].CounterSignerInfos.Count);
AssertExtensions.Throws<ArgumentNullException>(
"counterSignerInfo",
() => cms.SignerInfos[0].RemoveCounterSignature(null));
Assert.Equal(2, cms.SignerInfos[0].CounterSignerInfos.Count);
}
[Fact]
public static void RemoveCounterSignature_Negative()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signer = cms.SignerInfos[0];
ArgumentOutOfRangeException ex = AssertExtensions.Throws<ArgumentOutOfRangeException>(
"childIndex",
() => signer.RemoveCounterSignature(-1));
Assert.Null(ex.ActualValue);
}
[Fact]
public static void RemoveCounterSignature_TooBigByValue()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signer = cms.SignerInfos[0];
Assert.Throws<CryptographicException>(
() => signer.RemoveCounterSignature(2));
signer.RemoveCounterSignature(1);
Assert.Equal(2, signer.CounterSignerInfos.Count);
Assert.Throws<CryptographicException>(
() => signer.RemoveCounterSignature(1));
}
[Fact]
public static void RemoveCounterSignature_TooBigByValue_Past0()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signer = cms.SignerInfos[0];
signer.RemoveCounterSignature(0);
signer.RemoveCounterSignature(0);
Assert.Equal(2, signer.CounterSignerInfos.Count);
Assert.Throws<CryptographicException>(
() => signer.RemoveCounterSignature(0));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")]
public static void RemoveCounterSignature_TooBigByMatch()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signer = cms.SignerInfos[0];
SignerInfo counterSigner = signer.CounterSignerInfos[1];
// This succeeeds, but reduces the real count to 1.
signer.RemoveCounterSignature(counterSigner);
Assert.Equal(2, signer.CounterSignerInfos.Count);
Assert.Single(cms.SignerInfos[0].CounterSignerInfos);
Assert.Throws<CryptographicException>(
() => signer.RemoveCounterSignature(counterSigner));
}
[Fact]
public static void RemoveCounterSignature_BySignerInfo_OnRemovedSigner()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signer = cms.SignerInfos[0];
SignerInfo counterSigner = signer.CounterSignerInfos[0];
cms.RemoveSignature(signer);
Assert.NotEmpty(signer.CounterSignerInfos);
Assert.Throws<CryptographicException>(
() => signer.RemoveCounterSignature(counterSigner));
}
[Fact]
public static void RemoveCounterSignature_ByIndex_OnRemovedSigner()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signer = cms.SignerInfos[0];
cms.RemoveSignature(signer);
Assert.NotEmpty(signer.CounterSignerInfos);
Assert.Throws<CryptographicException>(
() => signer.RemoveCounterSignature(0));
}
[Fact]
public static void AddCounterSigner_DuplicateCert_RSA()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.Single(cms.Certificates);
SignerInfo firstSigner = cms.SignerInfos[0];
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert);
firstSigner.ComputeCounterSignature(signer);
}
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
SignerInfo firstSigner2 = cms.SignerInfos[0];
Assert.Single(firstSigner2.CounterSignerInfos);
Assert.Single(firstSigner2.UnsignedAttributes);
SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0];
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, counterSigner.SignerIdentifier.Type);
// On NetFx there will be two attributes, because Windows emits the
// content-type attribute even for counter-signers.
int expectedAttrCount = 1;
// One of them is a V3 signer.
#if NETFRAMEWORK
expectedAttrCount = 2;
#endif
Assert.Equal(expectedAttrCount, counterSigner.SignedAttributes.Count);
Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedAttrCount - 1].Oid.Value);
Assert.Equal(firstSigner2.Certificate, counterSigner.Certificate);
Assert.Single(cms.Certificates);
counterSigner.CheckSignature(true);
firstSigner2.CheckSignature(true);
cms.CheckSignature(true);
}
[Theory]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier)]
public static void AddCounterSigner_RSA(SubjectIdentifierType identifierType)
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.Single(cms.Certificates);
SignerInfo firstSigner = cms.SignerInfos[0];
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(identifierType, signerCert);
firstSigner.ComputeCounterSignature(signer);
}
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
SignerInfo firstSigner2 = cms.SignerInfos[0];
Assert.Single(firstSigner2.CounterSignerInfos);
Assert.Single(firstSigner2.UnsignedAttributes);
SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0];
Assert.Equal(identifierType, counterSigner.SignerIdentifier.Type);
// On NetFx there will be two attributes, because Windows emits the
// content-type attribute even for counter-signers.
int expectedCount = 1;
#if NETFRAMEWORK
expectedCount = 2;
#endif
Assert.Equal(expectedCount, counterSigner.SignedAttributes.Count);
Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedCount - 1].Oid.Value);
Assert.NotEqual(firstSigner2.Certificate, counterSigner.Certificate);
Assert.Equal(2, cms.Certificates.Count);
counterSigner.CheckSignature(true);
firstSigner2.CheckSignature(true);
cms.CheckSignature(true);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Not supported by crypt32")]
public static void AddCounterSignerToUnsortedAttributeSignature()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.DigiCertTimeStampToken);
// Assert.NoThrows
cms.CheckSignature(true);
SignerInfoCollection signers = cms.SignerInfos;
Assert.Equal(1, signers.Count);
SignerInfo signerInfo = signers[0];
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
signerInfo.ComputeCounterSignature(
new CmsSigner(
SubjectIdentifierType.IssuerAndSerialNumber,
cert));
signerInfo.ComputeCounterSignature(
new CmsSigner(
SubjectIdentifierType.SubjectKeyIdentifier,
cert));
}
// Assert.NoThrows
cms.CheckSignature(true);
byte[] exported = cms.Encode();
cms = new SignedCms();
cms.Decode(exported);
// Assert.NoThrows
cms.CheckSignature(true);
}
[Fact]
public static void AddCounterSigner_DSA()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.Single(cms.Certificates);
SignerInfo firstSigner = cms.SignerInfos[0];
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
using (X509Certificate2 signerCert = Certificates.Dsa1024.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert);
signer.IncludeOption = X509IncludeOption.EndCertOnly;
// Best compatibility for DSA is SHA-1 (FIPS 186-2)
signer.DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1);
firstSigner.ComputeCounterSignature(signer);
}
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
SignerInfo firstSigner2 = cms.SignerInfos[0];
Assert.Single(firstSigner2.CounterSignerInfos);
Assert.Single(firstSigner2.UnsignedAttributes);
Assert.Single(cms.SignerInfos);
Assert.Equal(2, cms.Certificates.Count);
SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0];
Assert.Equal(1, counterSigner.Version);
// On NetFx there will be two attributes, because Windows emits the
// content-type attribute even for counter-signers.
int expectedCount = 1;
#if NETFRAMEWORK
expectedCount = 2;
#endif
Assert.Equal(expectedCount, counterSigner.SignedAttributes.Count);
Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedCount - 1].Oid.Value);
Assert.NotEqual(firstSigner2.Certificate, counterSigner.Certificate);
Assert.Equal(2, cms.Certificates.Count);
#if NETCOREAPP
byte[] signature = counterSigner.GetSignature();
Assert.NotEmpty(signature);
// DSA PKIX signature format is a DER SEQUENCE.
Assert.Equal(0x30, signature[0]);
#endif
cms.CheckSignature(true);
byte[] encoded = cms.Encode();
cms.Decode(encoded);
cms.CheckSignature(true);
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, Oids.Sha1)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, Oids.Sha1)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, Oids.Sha256)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, Oids.Sha256)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, Oids.Sha384)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, Oids.Sha384)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, Oids.Sha512)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, Oids.Sha512)]
public static void AddCounterSigner_ECDSA(SubjectIdentifierType identifierType, string digestOid)
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.Single(cms.Certificates);
SignerInfo firstSigner = cms.SignerInfos[0];
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
using (X509Certificate2 signerCert = Certificates.ECDsaP256Win.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(identifierType, signerCert);
signer.IncludeOption = X509IncludeOption.EndCertOnly;
signer.DigestAlgorithm = new Oid(digestOid, digestOid);
firstSigner.ComputeCounterSignature(signer);
}
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
SignerInfo firstSigner2 = cms.SignerInfos[0];
Assert.Single(firstSigner2.CounterSignerInfos);
Assert.Single(firstSigner2.UnsignedAttributes);
Assert.Single(cms.SignerInfos);
Assert.Equal(2, cms.Certificates.Count);
SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0];
int expectedVersion = identifierType == SubjectIdentifierType.IssuerAndSerialNumber ? 1 : 3;
Assert.Equal(expectedVersion, counterSigner.Version);
// On NetFx there will be two attributes, because Windows emits the
// content-type attribute even for counter-signers.
int expectedCount = 1;
#if NETFRAMEWORK
expectedCount = 2;
#endif
Assert.Equal(expectedCount, counterSigner.SignedAttributes.Count);
Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedCount - 1].Oid.Value);
Assert.NotEqual(firstSigner2.Certificate, counterSigner.Certificate);
Assert.Equal(2, cms.Certificates.Count);
#if NETCOREAPP
byte[] signature = counterSigner.GetSignature();
Assert.NotEmpty(signature);
// DSA PKIX signature format is a DER SEQUENCE.
Assert.Equal(0x30, signature[0]);
// ECDSA Oids are all under 1.2.840.10045.4.
Assert.StartsWith("1.2.840.10045.4.", counterSigner.SignatureAlgorithm.Value);
#endif
cms.CheckSignature(true);
byte[] encoded = cms.Encode();
cms.Decode(encoded);
cms.CheckSignature(true);
}
[Fact]
public static void AddFirstCounterSigner_NoSignature_NoPrivateKey()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo firstSigner = cms.SignerInfos[0];
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate())
{
Action sign = () =>
firstSigner.ComputeCounterSignature(
new CmsSigner(
SubjectIdentifierType.NoSignature,
cert)
{
IncludeOption = X509IncludeOption.None,
});
if (PlatformDetection.IsFullFramework)
{
Assert.ThrowsAny<CryptographicException>(sign);
}
else
{
sign();
cms.CheckHash();
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
firstSigner.CheckSignature(true);
}
}
}
[Fact]
public static void AddFirstCounterSigner_NoSignature()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo firstSigner = cms.SignerInfos[0];
// A certificate shouldn't really be required here, but on .NET Framework
// it will prompt for the counter-signer's certificate if it's null,
// even if the signature type is NoSignature.
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
firstSigner.ComputeCounterSignature(
new CmsSigner(
SubjectIdentifierType.NoSignature,
cert)
{
IncludeOption = X509IncludeOption.None,
});
}
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
cms.CheckHash();
byte[] encoded = cms.Encode();
cms = new SignedCms();
cms.Decode(encoded);
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
cms.CheckHash();
firstSigner = cms.SignerInfos[0];
firstSigner.CheckSignature(verifySignatureOnly: true);
Assert.ThrowsAny<CryptographicException>(() => firstSigner.CheckHash());
SignerInfo firstCounterSigner = firstSigner.CounterSignerInfos[0];
Assert.ThrowsAny<CryptographicException>(() => firstCounterSigner.CheckSignature(true));
if (PlatformDetection.IsFullFramework)
{
// NetFX's CheckHash only looks at top-level SignerInfos to find the
// crypt32 CMS signer ID, so it fails on any check from a countersigner.
Assert.ThrowsAny<CryptographicException>(() => firstCounterSigner.CheckHash());
}
else
{
firstCounterSigner.CheckHash();
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public static void AddSecondCounterSignature_NoSignature_WithCert(bool addExtraCert)
{
AddSecondCounterSignature_NoSignature(withCertificate: true, addExtraCert);
}
[Theory]
// On .NET Framework it will prompt for the counter-signer's certificate if it's null,
// even if the signature type is NoSignature, so don't run the test there.
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[InlineData(false)]
[InlineData(true)]
public static void AddSecondCounterSignature_NoSignature_WithoutCert(bool addExtraCert)
{
AddSecondCounterSignature_NoSignature(withCertificate: false, addExtraCert);
}
private static void AddSecondCounterSignature_NoSignature(bool withCertificate, bool addExtraCert)
{
X509Certificate2Collection certs;
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo firstSigner = cms.SignerInfos[0];
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
using (X509Certificate2 cert2 = Certificates.DHKeyAgree1.GetCertificate())
{
firstSigner.ComputeCounterSignature(
new CmsSigner(cert)
{
IncludeOption = X509IncludeOption.None,
});
CmsSigner counterSigner;
if (withCertificate)
{
counterSigner = new CmsSigner(SubjectIdentifierType.NoSignature, cert);
}
else
{
counterSigner = new CmsSigner(SubjectIdentifierType.NoSignature);
}
if (addExtraCert)
{
counterSigner.Certificates.Add(cert2);
}
firstSigner.ComputeCounterSignature(counterSigner);
certs = cms.Certificates;
if (addExtraCert)
{
Assert.Equal(2, certs.Count);
Assert.NotEqual(cert2.RawData, certs[0].RawData);
Assert.Equal(cert2.RawData, certs[1].RawData);
}
else
{
Assert.Equal(1, certs.Count);
Assert.NotEqual(cert2.RawData, certs[0].RawData);
}
}
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
cms.CheckHash();
byte[] encoded = cms.Encode();
cms = new SignedCms();
cms.Decode(encoded);
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
cms.CheckHash();
firstSigner = cms.SignerInfos[0];
firstSigner.CheckSignature(verifySignatureOnly: true);
Assert.ThrowsAny<CryptographicException>(() => firstSigner.CheckHash());
// The NoSignature CounterSigner sorts first.
SignerInfo firstCounterSigner = firstSigner.CounterSignerInfos[0];
Assert.Equal(SubjectIdentifierType.NoSignature, firstCounterSigner.SignerIdentifier.Type);
Assert.ThrowsAny<CryptographicException>(() => firstCounterSigner.CheckSignature(true));
if (PlatformDetection.IsFullFramework)
{
// NetFX's CheckHash only looks at top-level SignerInfos to find the
// crypt32 CMS signer ID, so it fails on any check from a countersigner.
Assert.ThrowsAny<CryptographicException>(() => firstCounterSigner.CheckHash());
}
else
{
firstCounterSigner.CheckHash();
}
certs = cms.Certificates;
if (addExtraCert)
{
Assert.Equal(2, certs.Count);
Assert.Equal("CN=DfHelleKeyAgreement1", certs[1].SubjectName.Name);
}
else
{
Assert.Equal(1, certs.Count);
}
Assert.Equal("CN=RSAKeyTransferCapi1", certs[0].SubjectName.Name);
}
[Fact]
public static void EnsureExtraCertsAdded()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneDsa1024);
int preCount = cms.Certificates.Count;
using (X509Certificate2 unrelated1 = Certificates.DHKeyAgree1.GetCertificate())
using (X509Certificate2 unrelated1Copy = Certificates.DHKeyAgree1.GetCertificate())
using (X509Certificate2 unrelated2 = Certificates.RSAKeyTransfer2.GetCertificate())
using (X509Certificate2 unrelated3 = Certificates.RSAKeyTransfer3.GetCertificate())
using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
var signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert);
signer.Certificates.Add(unrelated1);
signer.Certificates.Add(unrelated2);
signer.Certificates.Add(unrelated3);
signer.Certificates.Add(unrelated1Copy);
cms.SignerInfos[0].ComputeCounterSignature(signer);
bool ExpectCopyRemoved =
#if NETFRAMEWORK
false
#else
true
#endif
;
int expectedAddedCount = 4;
if (!ExpectCopyRemoved)
{
expectedAddedCount++;
}
// Since adding a counter-signer DER-normalizes the document the certificates
// get rewritten to be smallest cert first.
X509Certificate2Collection certs = cms.Certificates;
List<X509Certificate2> certList = new List<X509Certificate2>(certs.OfType<X509Certificate2>());
int lastSize = -1;
for (int i = 0; i < certList.Count; i++)
{
byte[] rawData = certList[i].RawData;
Assert.True(
rawData.Length >= lastSize,
$"Certificate {i} has an encoded size ({rawData.Length}) no smaller than its predecessor ({lastSize})");
}
Assert.Contains(unrelated1, certList);
Assert.Contains(unrelated2, certList);
Assert.Contains(unrelated3, certList);
Assert.Contains(signerCert, certList);
Assert.Equal(ExpectCopyRemoved ? 1 : 2, certList.Count(c => c.Equals(unrelated1)));
}
cms.CheckSignature(true);
}
}
}
| |
using System;
using System.Data;
using System.Data.Odbc;
using ByteFX.Data.MySqlClient;
using ByteFX.Data;
using System.Collections;
namespace JCSLA{
public class CatLists : BusinessCollectionBase {
#region Instant Data
const string _table = "lists";
MySqlConnection _conn;
#endregion
#region Collection Members
public CatList AddNew(string listName) {
CatList cl= new CatList(listName, true, _conn);
List.Add(cl); return cl;
}
public bool Contains(CatList cl) {
foreach(CatList obj in List) {
if (cl.Equals(obj)){
return true;
}
}
return false;
}
public bool Contains(string listName) {
foreach(CatList obj in List) {
if (obj.ListName.ToUpper() == listName.ToUpper().Trim()){
return true;
}
}
return false;
}
public CatList this[int id] {
get{
return (CatList) List[id];
}
}
public CatList item(string listName) {
foreach(CatList cl in List) {
if (cl.ListName == listName)
return cl;
}
return null;
}
#endregion
#region DB Access and ctors
public CatLists(MySqlConnection conn) {
_conn = conn;
conn.Open();
ArrayList listNames = new ArrayList();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText ="SELECT DISTINCT ListName FROM " + _table;
MySqlDataReader dr = cmd.ExecuteReader();
while(dr.Read()) {
listNames.Add(Convert.ToString(dr["ListName"]));
}
dr.Close();
conn.Close();
foreach(string listName in listNames){
List.Add(new CatList(listName, false, conn));
}
}
public void Update() {
foreach (CatList obj in List) {
obj.Update();
}
}
#endregion
#region Business Members
#endregion
}
public class CatList : BusinessBase {
#region Instant Data
const string _table = "lists";
Entries _ents;
MySqlDBLayer _dbLayer;
string _listName = "";
MySqlConnection _conn;
BusinessCollectionBase _businessCollection;
#endregion
#region DB Access / ctors
public override void SetId(int id) {
/* This function is required by the base class but is not needed here */
}
public override BusinessCollectionBase BusinessCollection {
get{
return _businessCollection;
}
set {
_businessCollection = value;
}
}
public override object Conn {
get {
return _conn;
}
}
public override string Table {
get {
return _table;
}
}
private void Setup(MySqlConnection conn, string listName) {
_conn = conn; _listName = listName;
_ents = new Entries(this);
if (_dbLayer == null) {
_dbLayer = new MySqlDBLayer(this);
}
}
public CatList(string listName, bool create, MySqlConnection conn) {
Setup(conn, listName);
if (create){
base.MarkNew();
}else{
this.Load(listName);
}
}
public CatList(string listName, MySqlConnection conn) {
Setup(conn, listName);
this.Load(listName);
}
public void Load(string listName) {
_listName = listName;
MySqlConnection conn = (MySqlConnection)this.Conn;
MySqlDataReader dr = MySqlDBLayer.LoadWhereColumnIs(conn, _table, "listName",listName);
while(dr.Read()) {
_ents.Add(new Entry(dr, this));
}
conn.Close();
}
public void Reload() {
_ents.Clear();
Load(this.ListName);
}
public override void Update(){
foreach(Entry ent in _ents) {
ent.Update();
}
}
public string ListName{
get{
return _listName;
}
}
#endregion
#region Business Properties
public override int Id {
get {
/* This is required by base class but not needed here */
return 0;
}
}
public Entries Entries{
get{
return _ents;
}
}
public Entries RootEntries{
get{
Entries ents =new Entries(this);
foreach(Entry ent in _ents) {
if (ent.Parent == null) {
ents.Add(ent);
}
}
return ents;
}
}
public Entry AddRoot(string key) {
Entry ent = new Entry(key, this);
ent.IsLeaf = false;
ent.Value = "";
ent.BusinessCollection = this.Entries;
this.Entries.Add(ent);
return ent;
}
public Entry Entry(string key) {
Entry ent;
Entry root = new Entry();
key = key.ToUpper();
string[] path = key.Split("/".ToCharArray());
foreach(Entry rootEnt in this.RootEntries) {
if (rootEnt.Key.ToUpper() == path[1]){
root = rootEnt; break;
}
}
if (root != null){
ent = root;
for(int i = 2; i<path.Length; i++){
foreach (Entry child in ent.Entries) {
if (child.Key.ToUpper() == path[i]){
ent = child; break;
}
}
}
/* I don't know why I did this but it didn't work when I wanted to get a category entry with this method
if (ent.IsLeaf)
return ent;
else
return null;*/
return ent;
}
return null;
}
#endregion
#region Validation Management
public override bool IsValid {
get {
return (this.BrokenRules.Count == 0);
}
}
public override BrokenRules BrokenRules {
get {
BrokenRules br = new BrokenRules();
return br;
}
}
public override Hashtable ParamHash{
get {
/* This is required by base class but not needed here */
return new Hashtable();
}
}
#endregion
#region System.Object overrides
public override string ToString(){
return this.ListName;
}
#endregion
}
public class Entries : BusinessCollectionBase {
#region Instant Data
const string _table = "lists";
CatList _catList;
Entry _parEnt;
#endregion
#region Collection Members
public Entry Add(Entry ent) {
/* Used by CatList.Entries. See Entries.Add(string key)*/
ent.BusinessCollection = this;
List.Add(ent); return ent;
}
public Entry Add(string key) {
/* Used to add a new leaf entry to an existing entry: ent.Entries.Add("MyNewEntry"); */
Entry ent = new Entry(key, this._catList);
ent.ParentId = _parEnt.Id;
ent.IsLeaf = false;
this._catList.Entries.Add(ent);
ent.BusinessCollection = this._catList.Entries;
List.Add(ent); return ent;
}
public Entry Add(string key, string val) {
/* Used to add a new category entry to an existing entry: ent.Entries.Add("myKey", "myVal"); */
Entry ent = new Entry(key, this._catList);
ent.Value = val;
ent.IsLeaf = true;
ent.ParentId = _parEnt.Id;
this._catList.Entries.Add(ent);
ent.BusinessCollection = this._catList.Entries;
List.Add(ent); return ent;
}
public bool Contains(Entry obj) {
foreach(Entry ent in List) {
if (ent.Equals(obj)){
return true;
}
}
return false;
}
public bool Contains(string key) {
foreach(Entry ent in List) {
if (ent.Key.ToUpper() == key.ToUpper()){
return true;
}
}
return false;
}
public Entry this[int id] {
get{
return (Entry) List[id];
}
}
public Entry item(int id) {
foreach(Entry obj in List) {
if (obj.Id == id)
return obj;
}
return null;
}
#endregion
#region Business Members
#endregion
#region DB Access and ctors
public Entries(CatList cl) {
_catList = cl;
}
public Entries(Entry ent, CatList cl) {
_parEnt = ent;
_catList = cl;
}
public void Update() {
foreach (Entry obj in List) {
obj.Update();
}
}
#endregion
}
public class Entry : BusinessBase {
#region Instant Data
const string _table = "lists";
MySqlDBLayer _dbLayer;
int _id;
CatList _catList;
string _listName = "";
string _key = "";
string _value = "";
bool _leaf = false;
int _parId = -1;
BusinessCollectionBase _businessCollection;
#endregion
#region DB Access / ctors
public override object Conn {
get {
return this.CatList.Conn;
}
}
public override string Table {
get {
return _table;
}
}
private void Setup() {
if (_dbLayer == null) {
_dbLayer = new MySqlDBLayer(this);
}
}
public override void SetId(int id) {
/* This function is public for technical reasons. It is intended to be used only by the db
* layer*/
_id = id;
}
public override BusinessCollectionBase BusinessCollection {
get{
return _businessCollection;
}
set {
_businessCollection = value;
}
}
public Entry() {
Setup();
base.MarkNew();
}
public Entry(string key, CatList catList) {
Setup();
_key = key;
_catList = catList;
base.MarkNew();
}
public Entry(MySqlDataReader dr, CatList catList) {
Setup();
_catList = catList;
this.Load(dr);
}
private void Load(MySqlDataReader dr) {
SetId(Convert.ToInt32(dr["Id"]));
this._key = Convert.ToString(dr["key_"]);
this._value = Convert.ToString(dr["value"]);
this._leaf = Convert.ToBoolean(dr["leaf"]);
this._listName = Convert.ToString(dr["listName"]);
this._parId = Convert.ToInt32(dr["parId"]);
MarkOld();
}
public override void Update(){
if (this.IsMarkedForDeletion){
Entries allDesc = this.AllDescendents;
int allDescCount = allDesc.Count;
Entry ent;
for (int i=allDescCount-1; i>-1; i--){
ent = allDesc[i];
ent.MarkDeleted();
System.Diagnostics.Debug.WriteLine(ent.Id);
ent.DirectUpdate();
//ent.CatList.Entries.Remove(ent);
}
this.DirectUpdate();
//this.CatList.Entries.Remove(this);
}else{
_dbLayer.Update();
}
}
internal void DirectUpdate(){
_dbLayer.Update();
}
public Entries AllDescendents{
get{
Entries ents = new Entries(this.CatList);
foreach (Entry ent in this.Entries) {
_allDescendents(ent, ents);
}
return ents;
}
}
private void _allDescendents(Entry ent, Entries ents) {
ents.Add(ent);
foreach (Entry child in ent.Entries) {
_allDescendents(child, ents);
}
}
public override Hashtable ParamHash {
get {
Hashtable paramHash = new Hashtable();
paramHash.Add("@Id", this.Id);
paramHash.Add("@ListName", this.ListName);
paramHash.Add("@leaf", this.IsLeaf);
paramHash.Add("@Key_", this.Key);
paramHash.Add("@Value", this.Value);
paramHash.Add("@ParId", this._parId);
return paramHash;
}
}
#endregion
#region Business Properties
public override int Id {
get {
return _id;
}
}
public Entries Entries{
get {
Entries cl = new Entries(this, this.CatList);
foreach(Entry ent in this.CatList.Entries) {
if (ent.ParentId == this.Id){
cl.Add(ent);
}
}
return cl;
}
}
public Entry SubEntry(string key) {
key = this.Path + "/" + key;
return this.CatList.Entry(key);
}
public Entries Leafs{
get {
Entries cl = new Entries(this, this.CatList);
foreach(Entry ent in this.CatList.Entries) {
if (ent.ParentId == this.Id && ent.IsLeaf){
cl.Add(ent);
}
}
return cl;
}
}
public Entries Categories{
get {
Entries cl = new Entries(this, this.CatList);
foreach(Entry ent in this.CatList.Entries) {
if (ent.ParentId == this.Id && !ent.IsLeaf){
cl.Add(ent);
}
}
return cl;
}
}
public Entry Parent {
get{
Entries cl = new Entries(this.CatList);
foreach(Entry ent in this.CatList.Entries) {
if (ent.Id == this.ParentId){
return ent;
}
}
return null;
}
}
public int ParentId {
get{
return _parId;
}
set{
base.SetValue(ref _parId, value);
}
}
public string ListName{
get{
return this.CatList.ListName;
}
}
public string Key{
get{
return _key;
}
set{
base.SetValue(ref _key, value);
}
}
public string Value{
get{
return _value;
}
set{
base.SetValue(ref _value, value);
}
}
public bool IsLeaf
{
get{
return _leaf;
}
set{
base.SetValue(ref _leaf, value);
}
}
public bool IsRoot{
get{
return (_parId == -1);
}
}
public Entries Siblings{
get{
Entries ret = new Entries(this.CatList);
Entries sybEnts;
if (this.IsRoot)
sybEnts = this.CatList.RootEntries;
else
sybEnts = this.Parent.Entries;
foreach(Entry sybEnt in sybEnts) {
if (this != sybEnt) {
ret.Add(sybEnt);
}
}
return ret;
}
}
public CatList CatList {
get{
return _catList;
}
}
public string Path{
get {
string ret;
Entry par;
ret = this.Key;
par = this.Parent;
while (par != null) {
ret = par.Key + "/" + ret;
par = par.Parent;
}
ret = "/" + ret;
return ret;
}
}
#endregion
#region Validation Management
public override bool IsValid {
get {
return (this.BrokenRules.Count == 0);
}
}
public override BrokenRules BrokenRules {
get {
BrokenRules br = new BrokenRules();
br.Assert("LIST_NAME_EMPTY", "List name must be specified", this.ListName == "");
br.Assert("KEY_NAME_EMPTY", "Category or key name must be specified", this.Key == "");
br.Assert("NO_CATLIST", "Entry is not part of a CatList", this.CatList == null);
br.Assert("LEAF_HASNT_VAL", "Leafs must have values", this.Value == "" && this.IsLeaf);
br.Assert("CAT_HAS_VAL", "Categories can't have values", this.Value != "" && !this.IsLeaf);
br.Assert("LEAF_HAS_CHILDREN", "Leafs can't have child entries.", this.Entries.Count != 0 && this.IsLeaf);
br.Assert("DUP_NAME", "There is aleady a category or key with this name.", this.Siblings.Contains(this.Key));
return br;
}
}
#endregion
#region System.Object overrides
public override string ToString(){
return this.Key;
}
#endregion
}
}
| |
//
// ArtistListActions.cs
//
// Authors:
// Aaron Bockover <abockover@novell.com>
// Alexander Hixon <hixon.alexander@mediati.org>
// Frank Ziegler <funtastix@googlemail.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
// Copyright (C) 2013 Frank Ziegler
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using Mono.Addins;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Widgets;
using Banshee.Collection.Gui;
using Banshee.Widgets;
using Banshee.Configuration;
using Banshee.ServiceStack;
namespace Banshee.Gui
{
public class ArtistListModeChangedEventArgs : EventArgs
{
public IArtistListRenderer Renderer { get; set; }
}
public class ArtistListActions : BansheeActionGroup, IEnumerable<RadioAction>
{
private class ArtistListActionProxy : CustomActionProxy
{
private ArtistListActions actions;
private ComplexMenuItem last_item;
public ArtistListActions ListActions {
set {
value.ArtistListModeChanged += (o, args) => {
if (last_item != null) {
actions.AttachSubmenu (last_item);
}
};
actions = value;
}
}
public ArtistListActionProxy (UIManager ui, Gtk.Action action) : base (ui, action)
{
}
protected override void InsertProxy (Gtk.Action menuAction, Widget parent, Widget afterItem)
{
int position = 0;
Widget item = null;
if (parent is MenuItem || parent is Menu) {
Menu parent_menu = ((parent is MenuItem) ? (parent as MenuItem).Submenu : parent) as Menu;
position = (afterItem != null) ? Array.IndexOf (parent_menu.Children, afterItem as MenuItem) + 1 : 0;
item = GetNewMenuItem ();
if (item != null) {
var separator1 = new SeparatorMenuItem ();
var separator2 = new SeparatorMenuItem ();
//fix for separators that potentially already exist below the insert position
bool alreadyHasSeparator2 = ((parent_menu.Children [position]) as SeparatorMenuItem != null);
parent_menu.Insert (separator2, position);
parent_menu.Insert (item, position);
parent_menu.Insert (separator1, position);
item.Shown += (o, e) => {
separator1.Show ();
if (!alreadyHasSeparator2) {
separator2.Show ();
}
};
item.Hidden += (o, e) => {
separator1.Hide ();
separator2.Hide ();
};
}
}
var activatable = item as IActivatable;
if (activatable != null) {
activatable.RelatedAction = action;
}
}
protected override ComplexMenuItem GetNewMenuItem ()
{
var item = new ComplexMenuItem ();
var box = new HBox ();
box.Spacing = 5;
var label = new Label (action.Label);
box.PackStart (label, false, false, 0);
label.Show ();
box.ShowAll ();
item.Add (box);
last_item = item;
actions.AttachSubmenu (item);
return item;
}
}
private bool service_manager_startup_finished = false;
private ArtistListActionProxy artist_list_proxy;
private RadioAction active_action;
private List<IArtistListRenderer> renderers = new List<IArtistListRenderer> ();
private Dictionary<int, String> rendererActions = new Dictionary<int, String> ();
private Dictionary<TypeExtensionNode, IArtistListRenderer> node_map = new Dictionary<TypeExtensionNode, IArtistListRenderer> ();
public event EventHandler<ArtistListModeChangedEventArgs> ArtistListModeChanged;
public Action<IArtistListRenderer> ArtistListModeAdded;
public Action<IArtistListRenderer> ArtistListModeRemoved;
public RadioAction Active {
get { return active_action; }
set {
active_action = value;
SetRenderer (renderers [active_action.Value]);
}
}
public ArtistListActions () : base ("ArtistList")
{
ServiceManager.StartupFinished += delegate {
service_manager_startup_finished = true;
};
Add (new [] {
new ActionEntry ("ArtistListMenuAction", null, Catalog.GetString ("Artist List View"),
null, null, null)
});
this ["ArtistListMenuAction"].Visible = false;
AddinManager.AddExtensionNodeHandler ("/Banshee/Gui/ArtistListView", OnExtensionChanged);
Actions.UIManager.ActionsChanged += HandleActionsChanged;
}
private void HandleActionsChanged (object sender, EventArgs e)
{
if (Actions.UIManager.GetAction ("/MainMenu/ViewMenu") != null) {
artist_list_proxy = new ArtistListActionProxy (Actions.UIManager, this ["ArtistListMenuAction"]);
artist_list_proxy.ListActions = this;
artist_list_proxy.AddPath ("/MainMenu/ViewMenu", "FullScreen");
artist_list_proxy.AddPath ("/TrackContextMenu", "AddToPlaylist");
Actions.UIManager.ActionsChanged -= HandleActionsChanged;
}
}
private void OnExtensionChanged (object o, ExtensionNodeEventArgs args)
{
var tnode = (TypeExtensionNode)args.ExtensionNode;
IArtistListRenderer changed_renderer = null;
if (args.Change == ExtensionChange.Add) {
lock (renderers) {
try {
changed_renderer = (IArtistListRenderer)tnode.CreateInstance ();
renderers.Add (changed_renderer);
node_map [tnode] = changed_renderer;
} catch (Exception e) {
Log.Error (String.Format ("Failed to load ArtistListRenderer extension: {0}", args.Path), e);
}
}
if (changed_renderer != null) {
var handler = ArtistListModeAdded;
if (handler != null) {
handler (changed_renderer);
}
if (service_manager_startup_finished) {
SetRenderer (changed_renderer);
}
}
} else {
lock (renderers) {
if (node_map.ContainsKey (tnode)) {
changed_renderer = node_map [tnode];
node_map.Remove (tnode);
renderers.Remove (changed_renderer);
if (this.renderer == changed_renderer) {
SetRenderer (renderers [0]);
}
}
}
if (changed_renderer != null) {
var handler = ArtistListModeRemoved;
if (handler != null) {
handler (changed_renderer);
}
}
}
UpdateActions ();
}
private void UpdateActions ()
{
// Clear out the old options
foreach (string id in rendererActions.Values) {
Remove (id);
}
rendererActions.Clear ();
var radio_group = new RadioActionEntry [renderers.Count];
int i = 0;
// Add all the renderer options
foreach (var rendererIterator in renderers) {
string action_name = rendererIterator.GetType ().FullName;
int id = rendererActions.Count;
rendererActions [id] = action_name;
radio_group [i++] = new RadioActionEntry (
action_name, null,
rendererIterator.Name, null,
rendererIterator.Name,
id
);
}
Add (radio_group, 0, OnActionChanged);
var radio_action = this [ArtistListMode.Get ()] as RadioAction;
if (renderers.Count > 0 && radio_action != null) {
this.renderer = renderers [radio_action.Value];
if (this.renderer == null) {
SetRenderer (renderers [0]);
}
var action = this [this.renderer.GetType ().FullName];
if (action is RadioAction) {
Active = (RadioAction)action;
}
Active.Activate ();
}
}
private IArtistListRenderer renderer;
private void SetRenderer (IArtistListRenderer renderer)
{
this.renderer = renderer;
ArtistListMode.Set (renderer.GetType ().FullName);
ThreadAssist.ProxyToMain (() => {
var handler = ArtistListModeChanged;
if (handler != null) {
handler (this, new ArtistListModeChangedEventArgs { Renderer = renderer });
}
});
}
public IArtistListRenderer ArtistListRenderer {
get { return this.renderer; }
}
private void OnActionChanged (object o, ChangedArgs args)
{
Active = args.Current;
}
private void AttachSubmenu (ComplexMenuItem item)
{
MenuItem parent = item;
parent.Submenu = CreateMenu ();
}
private Menu CreateMenu ()
{
var menu = new Gtk.Menu ();
bool separator = false;
foreach (RadioAction action in this) {
menu.Append (action.CreateMenuItem ());
if (!separator) {
separator = true;
menu.Append (new SeparatorMenuItem ());
}
}
menu.ShowAll ();
return menu;
}
public IEnumerator<RadioAction> GetEnumerator ()
{
foreach (string id in rendererActions.Values) {
yield return (RadioAction)this [id];
}
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
public static readonly SchemaEntry<string> ArtistListMode = new SchemaEntry<string> (
"player_window", "artist_list_view_type",
typeof (ColumnCellArtistText).FullName,
"Artist List View Type",
"The view type chosen for the artist list"
);
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
namespace Pathfinding {
/** A path which searches from one point to a number of different targets in one search or from a number of different start points to a single target.
* \ingroup paths
* \astarpro
* \see Seeker.StartMultiTargetPath
* \see \ref MultiTargetPathExample.cs "Example of how to use multi-target-paths" */
public class MultiTargetPath : ABPath {
//public Node startNode;
public OnPathDelegate[] callbacks; /**< Callbacks to call for each individual path */
public Node[] targetNodes; /**< Nearest nodes to the #targetPoints */
protected int targetNodeCount;
public bool[] targetsFound; /**< Indicates if the target has been found. Also true if the target cannot be reached (is in another area) */
public Vector3[] targetPoints; /**< Target points specified when creating the path. These are snapped to the nearest nodes */
public Vector3[] originalTargetPoints; /**< Target points specified when creating the path. These are not snapped to the nearest nodes */
public List<Vector3>[] vectorPaths; /**< Stores all vector paths to the targets. Elements are null if no path was found */
public List<Node>[] nodePaths; /**< Stores all paths to the targets. Elements are null if no path was found */
public int endsFound = 0;
public bool pathsForAll = true; /**< If true, a path to all targets will be returned, otherwise just the one to the closest one */
public int chosenTarget = -1; /**< The closest target (if any was found) when #pathsForAll is false */
public int sequentialTarget = 0; /** Current target for Sequential #heuristicMode. Refers to an item in the targetPoints array */
/** How to calculate the heuristic. The \link #hTarget heuristic target point \endlink can be calculated in different ways, by taking the Average position of all targets, or taking the mid point of them (i.e center of the AABB encapsulating all targets).\n
* The one which works best seems to be Sequential though, it sets #hTarget to the first target, and when that target is found, it moves on to the next one.\n
* Some modes have the option to be 'moving' (e.g 'MovingAverage'), that means that it is updated every time a target is found.\n
* The H score is calculated according to AstarPath.heuristic */
public HeuristicMode heuristicMode = HeuristicMode.Sequential;
public enum HeuristicMode {
None,
Average,
MovingAverage,
Midpoint,
MovingMidpoint,
Sequential
}
/** False if the path goes from one point to multiple targets. True if it goes from multiple start points to one target point */
public bool inverted = true;
public MultiTargetPath () {}
[System.ObsoleteAttribute ("Please use the Construct method instead")]
public MultiTargetPath (Vector3[] startPoints, Vector3 target, OnPathDelegate[] callbackDelegates, OnPathDelegate callbackDelegate = null) : this (target,startPoints,callbackDelegates, callbackDelegate) {
inverted = true;
}
[System.ObsoleteAttribute ("Please use the Construct method instead")]
public MultiTargetPath (Vector3 start, Vector3[] targets, OnPathDelegate[] callbackDelegates, OnPathDelegate callbackDelegate = null) {
}
public static MultiTargetPath Construct (Vector3[] startPoints, Vector3 target, OnPathDelegate[] callbackDelegates, OnPathDelegate callback = null) {
MultiTargetPath p = Construct (target, startPoints, callbackDelegates, callback);
p.inverted = true;
return p;
}
public static MultiTargetPath Construct (Vector3 start, Vector3[] targets, OnPathDelegate[] callbackDelegates, OnPathDelegate callback = null) {
MultiTargetPath p = PathPool<MultiTargetPath>.GetPath ();
p.Setup (start,targets,callbackDelegates,callback);
return p;
}
protected void Setup (Vector3 start, Vector3[] targets, OnPathDelegate[] callbackDelegates, OnPathDelegate callback) {
inverted = false;
this.callback = callback;
callbacks = callbackDelegates;
targetPoints = targets;
originalStartPoint = start;
//originalEndPoint = end;
startPoint = start;
startIntPoint = (Int3)start;
if (targets.Length == 0) {
Error ();
LogError ("No targets were assigned to the MultiTargetPath");
return;
}
endPoint = targets[0];
originalTargetPoints = new Vector3[targetPoints.Length];
for (int i=0;i<targetPoints.Length;i++) {
originalTargetPoints[i] = targetPoints[i];
}
}
protected override void Recycle () {
PathPool<MultiTargetPath>.Recycle (this);
}
public override void OnEnterPool () {
if (vectorPaths != null)
for (int i=0;i<vectorPaths.Length;i++)
if (vectorPaths[i] != null) Util.ListPool<Vector3>.Release (vectorPaths[i]);
vectorPaths = null;
vectorPath = null;
if (nodePaths != null)
for (int i=0;i<nodePaths.Length;i++)
if (nodePaths[i] != null) Util.ListPool<Node>.Release (nodePaths[i]);
nodePaths = null;
path = null;
base.OnEnterPool ();
}
public override void ReturnPath () {
if (error) {
if (callbacks != null) {
for (int i=0;i<callbacks.Length;i++)
if (callbacks[i] != null) callbacks[i] (this);
}
if (callback != null) callback(this);
return;
}
bool anySucceded = false;
Vector3 _originalStartPoint = originalStartPoint;
Vector3 _startPoint = startPoint;
Node _startNode = startNode;
for (int i=0;i<nodePaths.Length;i++) {
path = nodePaths[i];
if (path != null) {
CompleteState = PathCompleteState.Complete;
anySucceded = true;
} else {
CompleteState = PathCompleteState.Error;
}
if (callbacks != null && callbacks[i] != null) {
vectorPath = vectorPaths[i];
//=== SEGMENT - should be identical to the one a few rows below (except "i")
if (inverted) {
endPoint = _startPoint;
endNode = _startNode;//path[0];
startNode = targetNodes[i];//path[path.Length-1];
startPoint = targetPoints[i];
originalEndPoint = _originalStartPoint;
originalStartPoint = originalTargetPoints[i];
} else {
endPoint = targetPoints[i];
originalEndPoint = originalTargetPoints[i];
endNode = targetNodes[i];//path[path.Length-1];
}
callbacks[i] (this);
//In case a modifier changed the vectorPath, update the array of all vectorPaths
vectorPaths[i] = vectorPath;
}
}
if (anySucceded) {
CompleteState = PathCompleteState.Complete;
if (!pathsForAll) {
path = nodePaths[chosenTarget];
vectorPath = vectorPaths[chosenTarget];
//=== SEGMENT - should be identical to the one a few rows above (except "chosenTarget")
if (inverted) {
endPoint = _startPoint;
endNode = _startNode;
startNode = targetNodes[chosenTarget];
startPoint = targetPoints[chosenTarget];
originalEndPoint = _originalStartPoint;
originalStartPoint = originalTargetPoints[chosenTarget];
} else {
endPoint = targetPoints[chosenTarget];
originalEndPoint = originalTargetPoints[chosenTarget];
endNode = targetNodes[chosenTarget];
}
}
} else {
CompleteState = PathCompleteState.Error;
}
if (callback != null) {
callback (this);
}
}
public void FoundTarget (NodeRun nodeR, int i) {
Node node = nodeR.node;
//Debug.Log ("Found target "+i+" "+current.g+" "+current.f);
node.Bit8 = false;//Reset bit 8
Trace (nodeR);
vectorPaths[i] = vectorPath;
nodePaths[i] = path;
vectorPath = Util.ListPool<Vector3>.Claim ();
path = Util.ListPool<Node>.Claim ();
targetsFound[i] = true;
/*for (int j=i;j<targetNodeCount-1;j++) {
targetNodes[j] = targetNodes[j+1];
}*/
targetNodeCount--;
if (!pathsForAll) {
CompleteState = PathCompleteState.Complete;
chosenTarget = i; //Mark which path was found
targetNodeCount = 0;
return;
}
//If there are no more targets to find, return here and avoid calculating a new hTarget
if (targetNodeCount <= 0) {
CompleteState = PathCompleteState.Complete;
return;
}
//No need to check for if pathsForAll is true since the function would have returned by now then
if (heuristicMode == HeuristicMode.MovingAverage) {
Vector3 avg = Vector3.zero;
int count = 0;
for (int j=0;j<targetPoints.Length;j++) {
if (!targetsFound[j]) {
avg += (Vector3)targetNodes[j].position;
count++;
}
}
if (count > 0) {
avg /= count;
}
hTarget = (Int3)avg;
RebuildOpenList ();
} else if (heuristicMode == HeuristicMode.MovingMidpoint) {
Vector3 min = Vector3.zero;
Vector3 max = Vector3.zero;
bool set = false;
for (int j=0;j<targetPoints.Length;j++) {
if (!targetsFound[j]) {
if (!set) {
min = (Vector3)targetNodes[j].position;
max = (Vector3)targetNodes[j].position;
set = true;
} else {
min = Vector3.Min ((Vector3)targetNodes[j].position,min);
max = Vector3.Max ((Vector3)targetNodes[j].position,max);
}
}
}
Int3 midpoint = (Int3)((min+max)*0.5F);
hTarget = (Int3)midpoint;
RebuildOpenList ();
} else if (heuristicMode == HeuristicMode.Sequential) {
//If this was the target hTarget was set to at the moment
if (sequentialTarget == i) {
//Pick a new hTarget
float dist = 0;
for (int j=0;j<targetPoints.Length;j++) {
if (!targetsFound[j]) {
float d = (targetNodes[j].position-startNode.position).sqrMagnitude;
if (d > dist) {
dist = d;
hTarget = (Int3)targetPoints[j];
sequentialTarget = j;
}
}
}
RebuildOpenList ();
}
}
}
public void RebuildOpenList () {
for (int j=1;j<runData.open.numberOfItems;j++) {
NodeRun nodeR = runData.open.GetNode(j);
nodeR.node.UpdateH (hTarget,heuristic,heuristicScale, nodeR);
}
runData.open.Rebuild ();
}
public override void Prepare () {
if (AstarPath.NumParallelThreads > 1) {
LogError ("MultiTargetPath can only be used with at most 1 concurrent pathfinder. Please use no multithreading or only 1 thread.");
Error ();
return;
}
nnConstraint.tags = enabledTags;
NNInfo startNNInfo = AstarPath.active.GetNearest (startPoint,nnConstraint, startHint);
startNode = startNNInfo.node;
if (startNode == null) {
LogError ("Could not find start node for multi target path");
Error ();
return;
}
if (!startNode.walkable) {
LogError ("Nearest node to the start point is not walkable");
Error ();
return;
}
//Tell the NNConstraint which node was found as the start node if it is a PathNNConstraint and not a normal NNConstraint
PathNNConstraint pathNNConstraint = nnConstraint as PathNNConstraint;
if (pathNNConstraint != null) {
pathNNConstraint.SetStart (startNNInfo.node);
}
vectorPaths = new List<Vector3>[targetPoints.Length];
nodePaths = new List<Node>[targetPoints.Length];
targetNodes = new Node[targetPoints.Length];
targetsFound = new bool[targetPoints.Length];
targetNodeCount = targetPoints.Length;
bool anyWalkable = false;
bool anySameArea = false;
bool anyNotNull = false;
for (int i=0;i<targetPoints.Length;i++) {
NNInfo endNNInfo = AstarPath.active.GetNearest (targetPoints[i],nnConstraint);
targetNodes[i] = endNNInfo.node;
//Debug.DrawLine (targetPoints[i],targetNodes[i].position,Color.red);
targetPoints[i] = endNNInfo.clampedPosition;
if (targetNodes[i] != null) {
anyNotNull = true;
endNode = targetNodes[i];
}
bool notReachable = false;
if (endNNInfo.node != null && endNNInfo.node.walkable) {
anyWalkable = true;
} else {
notReachable = true;
}
if (endNNInfo.node != null && endNNInfo.node.area == startNode.area) {
anySameArea = true;
} else {
notReachable = true;
}
if (notReachable) {
targetsFound[i] = true; //Signal that the pathfinder should not look for this node
targetNodeCount--;
}
}
startPoint = startNNInfo.clampedPosition;
startIntPoint = (Int3)startPoint;
//hTarget = (Int3)endPoint;
#if ASTARDEBUG
Debug.DrawLine (startNode.position,startPoint,Color.blue);
//Debug.DrawLine (endNode.position,endPoint,Color.blue);
#endif
if (startNode == null || !anyNotNull) {
LogError ("Couldn't find close nodes to either the start or the end (start = "+(startNode != null ? "found":"not found")+" end = "+(anyNotNull?"at least one found":"none found")+")");
Error ();
return;
}
if (!startNode.walkable) {
LogError ("The node closest to the start point is not walkable");
Error ();
return;
}
if (!anyWalkable) {
LogError ("No target nodes were walkable");
Error ();
return;
}
if (!anySameArea) {
LogError ("There are no valid paths to the targets");
Error ();
return;
}
//=== Calcuate hTarget ===
if (pathsForAll) {
if (heuristicMode == HeuristicMode.None) {
heuristic = Heuristic.None;
heuristicScale = 0F;
} else if (heuristicMode == HeuristicMode.Average || heuristicMode == HeuristicMode.MovingAverage) {
Vector3 avg = Vector3.zero;
for (int i=0;i<targetNodes.Length;i++) {
avg += (Vector3)targetNodes[i].position;
}
avg /= targetNodes.Length;
hTarget = (Int3)avg;
} else if (heuristicMode == HeuristicMode.Midpoint || heuristicMode == HeuristicMode.MovingMidpoint) {
Vector3 min = Vector3.zero;
Vector3 max = Vector3.zero;
bool set = false;
for (int j=0;j<targetPoints.Length;j++) {
if (!targetsFound[j]) {
if (!set) {
min = (Vector3)targetNodes[j].position;
max = (Vector3)targetNodes[j].position;
set = true;
} else {
min = Vector3.Min ((Vector3)targetNodes[j].position,min);
max = Vector3.Max ((Vector3)targetNodes[j].position,max);
}
}
}
Vector3 midpoint = (min+max)*0.5F;
hTarget = (Int3)midpoint;
} else if (heuristicMode == HeuristicMode.Sequential) {
float dist = 0;
for (int j=0;j<targetNodes.Length;j++) {
if (!targetsFound[j]) {
float d = (targetNodes[j].position-startNode.position).sqrMagnitude;
if (d > dist) {
dist = d;
hTarget = (Int3)targetPoints[j];
sequentialTarget = j;
}
}
}
}
} else {
heuristic = Heuristic.None;
heuristicScale = 0.0F;
}
}
public override void Initialize () {
for (int j=0;j < targetNodes.Length;j++) {
if (startNode == targetNodes[j]) {
FoundTarget (startNode.GetNodeRun(runData), j);
} else if (targetNodes[j] != null) {
targetNodes[j].Bit8 = true;
}
}
//Reset Bit8 on all nodes after the pathfinding has completed (no matter if an error occurs or if the path is canceled)
AstarPath.OnPathPostSearch += ResetBit8;
//If all paths have either been invalidated or found already because they were at the same node as the start node
if (targetNodeCount <= 0) {
CompleteState = PathCompleteState.Complete;
return;
}
NodeRun startRNode = startNode.GetNodeRun (runData);
startRNode.pathID = pathID;
startRNode.parent = null;
startRNode.cost = 0;
startRNode.g = startNode.penalty;
startNode.UpdateH (hTarget,heuristic,heuristicScale, startRNode);//Will just set H to zero
//if (recalcStartEndCosts) {
// startNode.InitialOpen (open,hTarget,startIntPoint,this,true);
//} else {
startNode.Open (runData,startRNode,hTarget,this);
//}
searchedNodes++;
//any nodes left to search?
if (runData.open.numberOfItems <= 1) {
LogError ("No open points, the start node didn't open any nodes");
return;
}
currentR = runData.open.Remove ();
}
public void ResetBit8 (Path p) {
AstarPath.OnPathPostSearch -= ResetBit8;
if (p != this) {
Debug.LogError ("This should have been cleared after it was called on 'this' path. Was it not called? Or did the delegate reset not work?");
}
for (int i=0;i<targetNodes.Length;i++) {
if (targetNodes[i] != null) targetNodes[i].Bit8 = false;
}
}
public override void CalculateStep (long targetTick) {
int counter = 0;
//Continue to search while there hasn't ocurred an error and the end hasn't been found
while (!IsDone()) {
//@Performance Just for debug info
searchedNodes++;
if (currentR.node.Bit8) {
//Close the current node, if the current node is the target node then the path is finnished
for (int i=0;i<targetNodes.Length;i++) {
if (!targetsFound[i] && currentR.node == targetNodes[i]) {
FoundTarget (currentR, i);
if (CompleteState != PathCompleteState.NotCalculated) {
break;
}
}
}
if (targetNodeCount <= 0) {
CompleteState = PathCompleteState.Complete;
break;
}
}
//Loop through all walkable neighbours of the node and add them to the open list.
currentR.node.Open (runData,currentR, hTarget,this);
//any nodes left to search?
if (runData.open.numberOfItems <= 1) {
LogError ("No open points, whole area searched");
Error ();
return;
}
//Select the node with the lowest F score and remove it from the open list
currentR = runData.open.Remove ();
//Check for time every 500 nodes, roughly every 0.5 ms usually
if (counter > 500) {
//Have we exceded the maxFrameTime, if so we should wait one frame before continuing the search since we don't want the game to lag
if (System.DateTime.UtcNow.Ticks >= targetTick) {
//Return instead of yield'ing, a separate function handles the yield (CalculatePaths)
return;
}
counter = 0;
}
counter++;
}
}
protected override void Trace (NodeRun node) {
base.Trace (node);
if (inverted) {
//Invert the paths
int half = path.Count/2;
for (int i=0;i<half;i++) {
Node tmp = path[i];
path[i] = path[path.Count-i-1];
path[path.Count-i-1] = tmp;
}
for (int i=0;i<half;i++) {
Vector3 tmp = vectorPath[i];
vectorPath[i] = vectorPath[vectorPath.Count-i-1];
vectorPath[vectorPath.Count-i-1] = tmp;
}
}
}
public override string DebugString (PathLog logMode) {
if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) {
return "";
}
System.Text.StringBuilder text = new System.Text.StringBuilder();
text.Append (error ? "Path Failed : " : "Path Completed : ");
text.Append ("Computation Time ");
text.Append ((duration).ToString (logMode == PathLog.Heavy ? "0.000" : "0.00"));
text.Append (" ms Searched Nodes ");
text.Append (searchedNodes);
if (!error) {
text.Append ("\nLast Found Path Length ");
text.Append (path == null ? "Null" : path.Count.ToString ());
if (logMode == PathLog.Heavy) {
text.Append ("\nSearch Iterations "+searchIterations);
text.Append ("\nPaths (").Append (targetsFound.Length).Append ("):");
for (int i=0;i<targetsFound.Length;i++) {
text.Append ("\n\n Path "+i).Append (" Found: ").Append (targetsFound[i]);
Node node = nodePaths[i] == null ? null : nodePaths[i][nodePaths[i].Count-1];
if (node != null) {
NodeRun nodeR = endNode.GetNodeRun (runData);
text.Append ("\n Length: ");
text.Append (nodePaths[i].Count);
text.Append ("\n End Node");
text.Append ("\n G: ");
text.Append (nodeR.g);
text.Append ("\n H: ");
text.Append (nodeR.h);
text.Append ("\n F: ");
text.Append (nodeR.f);
text.Append ("\n Point: ");
text.Append (((Vector3)endPoint).ToString ());
text.Append ("\n Graph: ");
text.Append (endNode.graphIndex);
}
}
text.Append ("\nStart Node");
text.Append ("\n Point: ");
text.Append (((Vector3)endPoint).ToString ());
text.Append ("\n Graph: ");
text.Append (startNode.graphIndex);
text.Append ("\nBinary Heap size at completion: ");
text.Append (runData.open == null ? "Null" : (runData.open.numberOfItems-2).ToString ());// -2 because numberOfItems includes the next item to be added and item zero is not used
}
}
if (error) {
text.Append ("\nError: ");
text.Append (errorLog);
}
text.Append ("\nPath Number ");
text.Append (pathID);
return text.ToString ();
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Discovery
{
using System;
using System.Collections.ObjectModel;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Xml;
using System.Xml.Linq;
using SR2 = System.ServiceModel.Discovery.SR;
[Fx.Tag.XamlVisible(false)]
public class EndpointDiscoveryMetadata
{
static XmlQualifiedName metadataContractName;
EndpointAddress endpointAddress;
OpenableContractTypeNameCollection contractTypeNames;
OpenableScopeCollection scopes;
OpenableCollection<Uri> listenUris;
OpenableCollection<XElement> extensions;
int metadataVersion;
string[] compiledScopes;
bool isOpen;
public EndpointDiscoveryMetadata()
{
this.endpointAddress = new EndpointAddress(EndpointAddress.AnonymousUri);
}
public Collection<XmlQualifiedName> ContractTypeNames
{
get
{
if (this.contractTypeNames == null)
{
this.contractTypeNames = new OpenableContractTypeNameCollection(this.isOpen);
}
return this.contractTypeNames;
}
}
public EndpointAddress Address
{
get
{
return this.endpointAddress;
}
set
{
ThrowIfOpen();
if (value == null)
{
throw FxTrace.Exception.ArgumentNull("value");
}
this.endpointAddress = value;
}
}
public Collection<XElement> Extensions
{
get
{
if (this.extensions == null)
{
this.extensions = new OpenableCollection<XElement>(this.isOpen);
}
return this.extensions;
}
}
public Collection<Uri> ListenUris
{
get
{
if (this.listenUris == null)
{
this.listenUris = new OpenableCollection<Uri>(this.isOpen);
}
return this.listenUris;
}
}
public Collection<Uri> Scopes
{
get
{
if (this.scopes == null)
{
this.scopes = new OpenableScopeCollection(this.isOpen);
}
return this.scopes;
}
}
public int Version
{
get
{
return this.metadataVersion;
}
set
{
ThrowIfOpen();
if (value < 0)
{
throw FxTrace.Exception.ArgumentOutOfRange("value", value, SR2.DiscoveryMetadataVersionLessThanZero);
}
this.metadataVersion = value;
}
}
internal static XmlQualifiedName MetadataContractName
{
get
{
if (metadataContractName == null)
{
ContractDescription metadataContract = ContractDescription.GetContract(typeof(IMetadataExchange));
metadataContractName = new XmlQualifiedName(metadataContract.Name, metadataContract.Namespace);
}
return metadataContractName;
}
}
internal Collection<XmlQualifiedName> InternalContractTypeNames
{
get
{
return this.contractTypeNames;
}
}
internal string[] CompiledScopes
{
get
{
Fx.Assert(IsOpen, "The CompiledScopes property is valid only if this EndpointDiscoveryMetadata instance is open.");
return this.compiledScopes;
}
}
internal bool IsOpen
{
get
{
return this.isOpen;
}
}
public static EndpointDiscoveryMetadata FromServiceEndpoint(ServiceEndpoint endpoint)
{
if (endpoint == null)
{
throw FxTrace.Exception.ArgumentNull("endpoint");
}
return GetEndpointDiscoveryMetadata(endpoint, endpoint.ListenUri);
}
public static EndpointDiscoveryMetadata FromServiceEndpoint(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
if (endpoint == null)
{
throw FxTrace.Exception.ArgumentNull("endpoint");
}
if (endpointDispatcher == null)
{
throw FxTrace.Exception.ArgumentNull("endpointDispatcher");
}
EndpointDiscoveryMetadata endpointDiscoveryMetadata;
if ((endpointDispatcher.ChannelDispatcher != null) &&
(endpointDispatcher.ChannelDispatcher.Listener != null))
{
endpointDiscoveryMetadata = GetEndpointDiscoveryMetadata(endpoint, endpointDispatcher.ChannelDispatcher.Listener.Uri);
}
else
{
endpointDiscoveryMetadata = GetEndpointDiscoveryMetadata(endpoint, endpoint.ListenUri);
}
if ((endpointDiscoveryMetadata != null) &&
IsMetadataEndpoint(endpoint) &&
CanHaveMetadataEndpoints(endpointDispatcher))
{
AddContractTypeScopes(endpointDiscoveryMetadata, endpointDispatcher.ChannelDispatcher.Host.Description);
}
return endpointDiscoveryMetadata;
}
static EndpointDiscoveryMetadata GetEndpointDiscoveryMetadata(ServiceEndpoint endpoint, Uri listenUri)
{
EndpointDiscoveryMetadata endpointDiscoveryMetadata = new EndpointDiscoveryMetadata();
endpointDiscoveryMetadata.Address = endpoint.Address;
endpointDiscoveryMetadata.ListenUris.Add(listenUri);
EndpointDiscoveryBehavior endpointDiscoveryBehavior = endpoint.Behaviors.Find<EndpointDiscoveryBehavior>();
if (endpointDiscoveryBehavior != null)
{
if (!endpointDiscoveryBehavior.Enabled)
{
if (TD.EndpointDiscoverabilityDisabledIsEnabled())
{
TD.EndpointDiscoverabilityDisabled(endpoint.Address.ToString(), listenUri.ToString());
}
return null;
}
if (TD.EndpointDiscoverabilityEnabledIsEnabled())
{
TD.EndpointDiscoverabilityEnabled(endpoint.Address.ToString(), listenUri.ToString());
}
if (endpointDiscoveryBehavior.InternalContractTypeNames != null)
{
foreach (XmlQualifiedName contractTypeName in endpointDiscoveryBehavior.InternalContractTypeNames)
{
endpointDiscoveryMetadata.ContractTypeNames.Add(contractTypeName);
}
}
if (endpointDiscoveryBehavior.InternalScopes != null)
{
foreach (Uri scope in endpointDiscoveryBehavior.InternalScopes)
{
endpointDiscoveryMetadata.Scopes.Add(scope);
}
}
if (endpointDiscoveryBehavior.InternalExtensions != null)
{
foreach (XElement xElement in endpointDiscoveryBehavior.InternalExtensions)
{
endpointDiscoveryMetadata.Extensions.Add(xElement);
}
}
}
XmlQualifiedName defaultContractTypeName = new XmlQualifiedName(endpoint.Contract.Name, endpoint.Contract.Namespace);
if (!endpointDiscoveryMetadata.ContractTypeNames.Contains(defaultContractTypeName))
{
endpointDiscoveryMetadata.ContractTypeNames.Add(defaultContractTypeName);
}
return endpointDiscoveryMetadata;
}
static void AddContractTypeScopes(EndpointDiscoveryMetadata endpointDiscoveryMetadata, ServiceDescription serviceDescription)
{
foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
{
if (IsMetadataEndpoint(endpoint) || IsDiscoverySystemEndpoint(endpoint))
{
continue;
}
endpointDiscoveryMetadata.Scopes.Add(FindCriteria.GetContractTypeNameScope(
new XmlQualifiedName(endpoint.Contract.Name, endpoint.Contract.Namespace)));
}
}
static bool CanHaveMetadataEndpoints(EndpointDispatcher endpointDispatcher)
{
if ((endpointDispatcher.ChannelDispatcher == null) || (endpointDispatcher.ChannelDispatcher.Host == null))
{
return false;
}
ServiceDescription description = endpointDispatcher.ChannelDispatcher.Host.Description;
if (description.Behaviors != null && description.Behaviors.Find<ServiceMetadataBehavior>() == null)
{
return false;
}
if (description.ServiceType != null && description.ServiceType.GetInterface(typeof(IMetadataExchange).Name) != null)
{
return false;
}
return true;
}
internal static bool IsDiscoverySystemEndpoint(EndpointDispatcher endpointDispatcher)
{
return (endpointDispatcher.IsSystemEndpoint &&
IsDiscoveryContract(endpointDispatcher.ContractName, endpointDispatcher.ContractNamespace));
}
internal static bool IsDiscoverySystemEndpoint(ServiceEndpoint endpoint)
{
return (endpoint.IsSystemEndpoint &&
IsDiscoveryContract(endpoint.Contract.Name, endpoint.Contract.Namespace));
}
static bool IsDiscoveryContract(string contractName, string contractNamespace)
{
return (IsDiscoveryContractName(contractName) && IsDiscoveryContractNamespace(contractNamespace));
}
static bool IsDiscoveryContractName(string contractName)
{
return ((string.CompareOrdinal(contractName, ProtocolStrings.ContractNames.DiscoveryAdhocContractName) == 0) ||
(string.CompareOrdinal(contractName, ProtocolStrings.ContractNames.DiscoveryManagedContractName) == 0));
}
static bool IsDiscoveryContractNamespace(string contractNamespace)
{
return ((string.CompareOrdinal(contractNamespace, ProtocolStrings.VersionApril2005.Namespace) == 0) ||
(string.CompareOrdinal(contractNamespace, ProtocolStrings.Version11.Namespace) == 0) ||
(string.CompareOrdinal(contractNamespace, ProtocolStrings.VersionCD1.Namespace) == 0));
}
internal static bool IsMetadataEndpoint(ServiceEndpoint endpoint)
{
return ((string.CompareOrdinal(endpoint.Contract.Name, MetadataContractName.Name) == 0) &&
(string.CompareOrdinal(endpoint.Contract.Namespace, MetadataContractName.Namespace) == 0));
}
[Fx.Tag.Throws(typeof(XmlException), "throws on incorrect xml data")]
internal void ReadFrom(DiscoveryVersion discoveryVersion, XmlReader reader)
{
ThrowIfOpen();
if (discoveryVersion == null)
{
throw FxTrace.Exception.ArgumentNull("discoveryVersion");
}
if (reader == null)
{
throw FxTrace.Exception.ArgumentNull("reader");
}
this.endpointAddress = new EndpointAddress(EndpointAddress.AnonymousUri);
this.contractTypeNames = null;
this.scopes = null;
this.listenUris = null;
this.metadataVersion = 0;
this.extensions = null;
this.isOpen = false;
reader.MoveToContent();
if (reader.IsEmptyElement)
{
throw FxTrace.Exception.AsError(new XmlException(SR2.DiscoveryXmlEndpointNull));
}
int startDepth = reader.Depth;
reader.ReadStartElement();
this.endpointAddress = SerializationUtility.ReadEndpointAddress(discoveryVersion, reader);
if (reader.IsStartElement(ProtocolStrings.SchemaNames.TypesElement, discoveryVersion.Namespace))
{
this.contractTypeNames = new OpenableContractTypeNameCollection(false);
SerializationUtility.ReadContractTypeNames(this.contractTypeNames, reader);
}
if (reader.IsStartElement(ProtocolStrings.SchemaNames.ScopesElement, discoveryVersion.Namespace))
{
this.scopes = new OpenableScopeCollection(false);
SerializationUtility.ReadScopes(this.scopes, reader);
}
if (reader.IsStartElement(ProtocolStrings.SchemaNames.XAddrsElement, discoveryVersion.Namespace))
{
this.listenUris = new OpenableCollection<Uri>(false);
SerializationUtility.ReadListenUris(listenUris, reader);
}
if (reader.IsStartElement(ProtocolStrings.SchemaNames.MetadataVersionElement, discoveryVersion.Namespace))
{
this.metadataVersion = SerializationUtility.ReadMetadataVersion(reader);
}
while (true)
{
reader.MoveToContent();
if ((reader.NodeType == XmlNodeType.EndElement) && (reader.Depth == startDepth))
{
break;
}
else if (reader.IsStartElement())
{
this.Extensions.Add(XElement.ReadFrom(reader) as XElement);
}
else
{
reader.Read();
}
}
reader.ReadEndElement();
}
internal void WriteTo(DiscoveryVersion discoveryVersion, XmlWriter writer)
{
if (discoveryVersion == null)
{
throw FxTrace.Exception.ArgumentNull("discoveryVersion");
}
if (writer == null)
{
throw FxTrace.Exception.ArgumentNull("writer");
}
SerializationUtility.WriteEndPointAddress(discoveryVersion, this.endpointAddress, writer);
SerializationUtility.WriteContractTypeNames(discoveryVersion, this.contractTypeNames, writer);
SerializationUtility.WriteScopes(discoveryVersion, this.scopes, null, writer);
SerializationUtility.WriteListenUris(discoveryVersion, this.listenUris, writer);
SerializationUtility.WriteMetadataVersion(discoveryVersion, this.metadataVersion, writer);
if (this.extensions != null)
{
foreach (XElement xElement in Extensions)
{
xElement.WriteTo(writer);
}
}
}
internal void Open()
{
if (this.contractTypeNames != null)
{
this.contractTypeNames.Open();
}
if (this.scopes != null)
{
this.scopes.Open();
this.compiledScopes = ScopeCompiler.Compile(this.scopes);
}
if (this.listenUris != null)
{
this.listenUris.Open();
}
if (this.extensions != null)
{
this.extensions.Open();
}
this.isOpen = true;
}
void ThrowIfOpen()
{
if (this.isOpen)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR2.DiscoveryMetadataAlreadyOpen));
}
}
class OpenableCollection<T> : NonNullItemCollection<T>
{
bool isOpen;
public OpenableCollection(bool opened)
{
this.isOpen = opened;
}
void ThrowIfOpen()
{
if (this.isOpen)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR2.DiscoverySdmCollectionIsOpen(typeof(T).Name)));
}
}
internal void Open()
{
this.isOpen = true;
}
protected override void ClearItems()
{
ThrowIfOpen();
base.ClearItems();
}
protected override void InsertItem(int index, T item)
{
ThrowIfOpen();
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
ThrowIfOpen();
base.RemoveItem(index);
}
protected override void SetItem(int index, T item)
{
ThrowIfOpen();
base.SetItem(index, item);
}
}
class OpenableContractTypeNameCollection : OpenableCollection<XmlQualifiedName>
{
public OpenableContractTypeNameCollection(bool opened)
: base(opened)
{
}
protected override void InsertItem(int index, XmlQualifiedName item)
{
if ((item != null) && (item.Name == string.Empty))
{
throw FxTrace.Exception.AsError(new ArgumentException(SR2.DiscoveryArgumentEmptyContractTypeName));
}
base.InsertItem(index, item);
}
protected override void SetItem(int index, XmlQualifiedName item)
{
if ((item != null) && (item.Name == string.Empty))
{
throw FxTrace.Exception.AsError(new ArgumentException(SR2.DiscoveryArgumentEmptyContractTypeName));
}
base.SetItem(index, item);
}
}
class OpenableScopeCollection : OpenableCollection<Uri>
{
public OpenableScopeCollection(bool opened) : base(opened)
{
}
protected override void InsertItem(int index, Uri item)
{
if (item != null && !item.IsAbsoluteUri)
{
throw FxTrace.Exception.AsError(new ArgumentException(SR2.DiscoveryArgumentInvalidScopeUri(item)));
}
base.InsertItem(index, item);
}
protected override void SetItem(int index, Uri item)
{
if (item != null && !item.IsAbsoluteUri)
{
throw FxTrace.Exception.AsError(new ArgumentException(SR2.DiscoveryArgumentInvalidScopeUri(item)));
}
base.SetItem(index, item);
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Targets;
using NLog.Internal.Fakeables;
#if SILVERLIGHT
using System.Windows;
#endif
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public class LogFactory : IDisposable
{
#if !SILVERLIGHT
private const int ReconfigAfterFileChangedTimeout = 1000;
private static TimeSpan defaultFlushTimeout = TimeSpan.FromSeconds(15);
private Timer reloadTimer;
private readonly MultiFileWatcher watcher;
#endif
private static IAppDomain currentAppDomain;
private readonly object syncRoot = new object();
private LoggingConfiguration config;
private LogLevel globalThreshold = LogLevel.MinLevel;
private bool configLoaded;
// TODO: logsEnabled property might be possible to be encapsulated into LogFactory.LogsEnabler class.
private int logsEnabled;
private readonly LoggerCache loggerCache = new LoggerCache();
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged;
#if !SILVERLIGHT
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded;
#endif
/// <summary>
/// Initializes a new instance of the <see cref="LogFactory" /> class.
/// </summary>
public LogFactory()
{
#if !SILVERLIGHT
this.watcher = new MultiFileWatcher();
this.watcher.OnChange += this.ConfigFileChanged;
CurrentAppDomain.DomainUnload += currentAppDomain_DomainUnload;
#endif
}
/// <summary>
/// Initializes a new instance of the <see cref="LogFactory" /> class.
/// </summary>
/// <param name="config">The config.</param>
public LogFactory(LoggingConfiguration config)
: this()
{
this.Configuration = config;
}
/// <summary>
/// Gets the current <see cref="IAppDomain"/>.
/// </summary>
public static IAppDomain CurrentAppDomain
{
get { return currentAppDomain ?? (currentAppDomain = AppDomainWrapper.CurrentDomain); }
set { currentAppDomain = value; }
}
/// <summary>
/// Gets or sets a value indicating whether exceptions should be thrown.
/// </summary>
/// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value>
/// <remarks>By default exceptions are not thrown under any circumstances.</remarks>
public bool ThrowExceptions { get; set; }
/// <summary>
/// Gets or sets the current logging configuration. After setting this property all
/// existing loggers will be re-configured, so that there is no need to call <see cref="ReconfigExistingLoggers" />
/// manually.
/// </summary>
public LoggingConfiguration Configuration
{
get
{
lock (this.syncRoot)
{
if (this.configLoaded)
{
return this.config;
}
this.configLoaded = true;
#if !SILVERLIGHT
if (this.config == null)
{
// Try to load default configuration.
this.config = XmlLoggingConfiguration.AppConfig;
}
#endif
// Retest the condition as we might have loaded a config.
if (this.config == null)
{
foreach (string configFile in GetCandidateConfigFileNames())
{
#if SILVERLIGHT
Uri configFileUri = new Uri(configFile, UriKind.Relative);
if (Application.GetResourceStream(configFileUri) != null)
{
LoadLoggingConfiguration(configFile);
break;
}
#else
if (File.Exists(configFile))
{
LoadLoggingConfiguration(configFile);
break;
}
#endif
}
}
if (this.config != null)
{
#if !SILVERLIGHT
config.Dump();
try
{
this.watcher.Watch(this.config.FileNamesToWatch);
}
catch (Exception exception)
{
InternalLogger.Warn("Cannot start file watching: {0}. File watching is disabled", exception);
}
#endif
this.config.InitializeAll();
}
return this.config;
}
}
set
{
#if !SILVERLIGHT
try
{
this.watcher.StopWatching();
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Cannot stop file watching: {0}", exception);
}
#endif
lock (this.syncRoot)
{
LoggingConfiguration oldConfig = this.config;
if (oldConfig != null)
{
InternalLogger.Info("Closing old configuration.");
#if !SILVERLIGHT
this.Flush();
#endif
oldConfig.Close();
}
this.config = value;
this.configLoaded = true;
if (this.config != null)
{
config.Dump();
this.config.InitializeAll();
this.ReconfigExistingLoggers();
#if !SILVERLIGHT
try
{
this.watcher.Watch(this.config.FileNamesToWatch);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Cannot start file watching: {0}", exception);
}
#endif
}
this.OnConfigurationChanged(new LoggingConfigurationChangedEventArgs(value, oldConfig));
}
}
}
/// <summary>
/// Gets or sets the global log threshold. Log events below this threshold are not logged.
/// </summary>
public LogLevel GlobalThreshold
{
get
{
return this.globalThreshold;
}
set
{
lock (this.syncRoot)
{
this.globalThreshold = value;
this.ReconfigExistingLoggers();
}
}
}
/// <summary>
/// Gets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>.
/// </summary>
/// <value>
/// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/>
/// </value>
[CanBeNull]
public CultureInfo DefaultCultureInfo
{
get
{
var configuration = this.Configuration;
return configuration != null ? configuration.DefaultCultureInfo : null;
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting
/// unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger instance.</returns>
public Logger CreateNullLogger()
{
TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
Logger newLogger = new Logger();
newLogger.Initialize(string.Empty, new LoggerConfiguration(targetsByLevel,false), this);
return newLogger;
}
/// <summary>
/// Gets the logger named after the currently-being-initialized class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public Logger GetCurrentClassLogger()
{
#if SILVERLIGHT
var frame = new StackFrame(1);
#else
var frame = new StackFrame(1, false);
#endif
return this.GetLogger(frame.GetMethod().DeclaringType.FullName);
}
/// <summary>
/// Gets the logger named after the currently-being-initialized class.
/// </summary>
/// <param name="loggerType">The type of the logger to create. The type must inherit from
/// NLog.Logger.</param>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method. Make sure you are not calling this method in a
/// loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public Logger GetCurrentClassLogger(Type loggerType)
{
#if !SILVERLIGHT
var frame = new StackFrame(1, false);
#else
var frame = new StackFrame(1);
#endif
return this.GetLogger(frame.GetMethod().DeclaringType.FullName, loggerType);
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument
/// are not guaranteed to return the same logger reference.</returns>
public Logger GetLogger(string name)
{
return this.GetLogger(new LoggerCacheKey(name, typeof(Logger)));
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The type of the logger to create. The type must inherit from NLog.Logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the
/// same argument aren't guaranteed to return the same logger reference.</returns>
public Logger GetLogger(string name, Type loggerType)
{
return this.GetLogger(new LoggerCacheKey(name, loggerType));
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger and recalculates their
/// target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public void ReconfigExistingLoggers()
{
if (this.config != null)
{
this.config.InitializeAll();
}
//new list to avoid "Collection was modified; enumeration operation may not execute"
var loggers = new List<Logger>(loggerCache.Loggers);
foreach (var logger in loggers)
{
logger.SetConfiguration(this.GetConfigurationForLogger(logger.Name, this.config));
}
}
#if !SILVERLIGHT
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
public void Flush()
{
this.Flush(defaultFlushTimeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time
/// will be discarded.</param>
public void Flush(TimeSpan timeout)
{
try
{
AsyncHelpers.RunSynchronously(cb => this.Flush(cb, timeout));
}
catch (Exception e)
{
if (ThrowExceptions)
{
throw;
}
InternalLogger.Error(e.ToString());
}
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages
/// after that time will be discarded.</param>
public void Flush(int timeoutMilliseconds)
{
this.Flush(TimeSpan.FromMilliseconds(timeoutMilliseconds));
}
#endif
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public void Flush(AsyncContinuation asyncContinuation)
{
this.Flush(asyncContinuation, TimeSpan.MaxValue);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages
/// after that time will be discarded.</param>
public void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
this.Flush(asyncContinuation, TimeSpan.FromMilliseconds(timeoutMilliseconds));
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
try
{
InternalLogger.Trace("LogFactory.Flush({0})", timeout);
var loggingConfiguration = this.Configuration;
if (loggingConfiguration != null)
{
InternalLogger.Trace("Flushing all targets...");
loggingConfiguration.FlushAllTargets(AsyncHelpers.WithTimeout(asyncContinuation, timeout));
}
else
{
asyncContinuation(null);
}
}
catch (Exception e)
{
if (ThrowExceptions)
{
throw;
}
InternalLogger.Error(e.ToString());
}
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>
/// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than
/// or equal to <see cref="SuspendLogging"/> calls.
/// </remarks>
/// <returns>An object that implements IDisposable whose Dispose() method re-enables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
[Obsolete("Use SuspendLogging() instead.")]
public IDisposable DisableLogging()
{
return SuspendLogging();
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>
/// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than
/// or equal to <see cref="SuspendLogging"/> calls.</remarks>
[Obsolete("Use ResumeLogging() instead.")]
public void EnableLogging()
{
ResumeLogging();
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>
/// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than
/// or equal to <see cref="SuspendLogging"/> calls.
/// </remarks>
/// <returns>An object that implements IDisposable whose Dispose() method re-enables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
public IDisposable SuspendLogging()
{
lock (this.syncRoot)
{
this.logsEnabled--;
if (this.logsEnabled == -1)
{
this.ReconfigExistingLoggers();
}
}
return new LogEnabler(this);
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater
/// than or equal to <see cref="SuspendLogging"/> calls.</remarks>
public void ResumeLogging()
{
lock (this.syncRoot)
{
this.logsEnabled++;
if (this.logsEnabled == 0)
{
this.ReconfigExistingLoggers();
}
}
}
/// <summary>
/// Returns <see langword="true" /> if logging is currently enabled.
/// </summary>
/// <returns>A value of <see langword="true" /> if logging is currently enabled,
/// <see langword="false"/> otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater
/// than or equal to <see cref="SuspendLogging"/> calls.</remarks>
public bool IsLoggingEnabled()
{
return this.logsEnabled >= 0;
}
/// <summary>
/// Invoke the Changed event; called whenever list changes
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnConfigurationChanged(LoggingConfigurationChangedEventArgs e)
{
var changed = this.ConfigurationChanged;
if (changed != null)
{
changed(this, e);
}
}
#if !SILVERLIGHT
internal void ReloadConfigOnTimer(object state)
{
LoggingConfiguration configurationToReload = (LoggingConfiguration)state;
InternalLogger.Info("Reloading configuration...");
lock (this.syncRoot)
{
if (this.reloadTimer != null)
{
this.reloadTimer.Dispose();
this.reloadTimer = null;
}
if(IsDisposing)
{
//timer was disposed already.
this.watcher.Dispose();
return;
}
this.watcher.StopWatching();
try
{
if (this.Configuration != configurationToReload)
{
throw new NLogConfigurationException("Config changed in between. Not reloading.");
}
LoggingConfiguration newConfig = configurationToReload.Reload();
//problem: XmlLoggingConfiguration.Initialize eats exception with invalid XML. ALso XmlLoggingConfiguration.Reload never returns null.
//therefor we check the InitializeSucceeded property.
var xmlConfig = newConfig as XmlLoggingConfiguration;
if (xmlConfig != null)
{
if (!xmlConfig.InitializeSucceeded.HasValue || !xmlConfig.InitializeSucceeded.Value)
{
throw new NLogConfigurationException("Configuration.Reload() failed. Invalid XML?");
}
}
if (newConfig != null)
{
this.Configuration = newConfig;
if (this.ConfigurationReloaded != null)
{
this.ConfigurationReloaded(this, new LoggingConfigurationReloadedEventArgs(true, null));
}
}
else
{
throw new NLogConfigurationException("Configuration.Reload() returned null. Not reloading.");
}
}
catch (Exception exception)
{
if (exception is NLogConfigurationException)
{
InternalLogger.Warn(exception.Message);
}
else if (exception.MustBeRethrown())
{
throw;
}
this.watcher.Watch(configurationToReload.FileNamesToWatch);
var configurationReloadedDelegate = this.ConfigurationReloaded;
if (configurationReloadedDelegate != null)
{
configurationReloadedDelegate(this, new LoggingConfigurationReloadedEventArgs(false, exception));
}
}
}
}
#endif
private void GetTargetsByLevelForLogger(string name, IEnumerable<LoggingRule> rules, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel, bool[] suppressedLevels)
{
foreach (LoggingRule rule in rules)
{
if (!rule.NameMatches(name))
{
continue;
}
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
if (i < this.GlobalThreshold.Ordinal || suppressedLevels[i] || !rule.IsLoggingEnabledForLevel(LogLevel.FromOrdinal(i)))
{
continue;
}
if (rule.Final)
suppressedLevels[i] = true;
foreach (Target target in rule.Targets)
{
var awf = new TargetWithFilterChain(target, rule.Filters);
if (lastTargetsByLevel[i] != null)
{
lastTargetsByLevel[i].NextInChain = awf;
}
else
{
targetsByLevel[i] = awf;
}
lastTargetsByLevel[i] = awf;
}
}
// Recursively analyze the child rules.
this.GetTargetsByLevelForLogger(name, rule.ChildRules, targetsByLevel, lastTargetsByLevel, suppressedLevels);
}
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
TargetWithFilterChain tfc = targetsByLevel[i];
if (tfc != null)
{
tfc.PrecalculateStackTraceUsage();
}
}
}
internal LoggerConfiguration GetConfigurationForLogger(string name, LoggingConfiguration configuration)
{
TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
TargetWithFilterChain[] lastTargetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1];
bool[] suppressedLevels = new bool[LogLevel.MaxLevel.Ordinal + 1];
if (configuration != null && this.IsLoggingEnabled())
{
this.GetTargetsByLevelForLogger(name, configuration.LoggingRules, targetsByLevel, lastTargetsByLevel, suppressedLevels);
}
InternalLogger.Debug("Targets for {0} by level:", name);
for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat(CultureInfo.InvariantCulture, "{0} =>", LogLevel.FromOrdinal(i));
for (TargetWithFilterChain afc = targetsByLevel[i]; afc != null; afc = afc.NextInChain)
{
sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", afc.Target.Name);
if (afc.FilterChain.Count > 0)
{
sb.AppendFormat(CultureInfo.InvariantCulture, " ({0} filters)", afc.FilterChain.Count);
}
}
InternalLogger.Debug(sb.ToString());
}
#pragma warning disable 618
return new LoggerConfiguration(targetsByLevel, configuration != null && configuration.ExceptionLoggingOldStyle);
#pragma warning restore 618
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>True</c> to release both managed and unmanaged resources;
/// <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
#if !SILVERLIGHT
if (disposing)
{
this.watcher.Dispose();
if (this.reloadTimer != null)
{
this.reloadTimer.Dispose();
this.reloadTimer = null;
}
}
#endif
}
private static IEnumerable<string> GetCandidateConfigFileNames()
{
#if SILVERLIGHT
yield return "NLog.config";
#else
// NLog.config from application directory
if (CurrentAppDomain.BaseDirectory != null)
{
yield return Path.Combine(CurrentAppDomain.BaseDirectory, "NLog.config");
}
// Current config file with .config renamed to .nlog
string cf = CurrentAppDomain.ConfigurationFile;
if (cf != null)
{
yield return Path.ChangeExtension(cf, ".nlog");
// .nlog file based on the non-vshost version of the current config file
const string vshostSubStr = ".vshost.";
if (cf.Contains(vshostSubStr))
{
yield return Path.ChangeExtension(cf.Replace(vshostSubStr, "."), ".nlog");
}
IEnumerable<string> privateBinPaths = CurrentAppDomain.PrivateBinPath;
if (privateBinPaths != null)
{
foreach (var path in privateBinPaths)
{
if (path != null)
{
yield return Path.Combine(path, "NLog.config");
}
}
}
}
// Get path to NLog.dll.nlog only if the assembly is not in the GAC
var nlogAssembly = typeof(LogFactory).Assembly;
if (!nlogAssembly.GlobalAssemblyCache)
{
if (!string.IsNullOrEmpty(nlogAssembly.Location))
{
yield return nlogAssembly.Location + ".nlog";
}
}
#endif
}
private Logger GetLogger(LoggerCacheKey cacheKey)
{
lock (this.syncRoot)
{
Logger existingLogger = loggerCache.Retrieve(cacheKey);
if (existingLogger != null)
{
// Logger is still in cache and referenced.
return existingLogger;
}
Logger newLogger;
if (cacheKey.ConcreteType != null && cacheKey.ConcreteType != typeof(Logger))
{
try
{
newLogger = (Logger)FactoryHelper.CreateInstance(cacheKey.ConcreteType);
}
catch (Exception ex)
{
if (ex.MustBeRethrown() || ThrowExceptions)
{
throw;
}
InternalLogger.Error("Cannot create instance of specified type. Proceeding with default type instance. Exception : {0}", ex);
// Creating default instance of logger if instance of specified type cannot be created.
cacheKey = new LoggerCacheKey(cacheKey.Name, typeof(Logger));
newLogger = new Logger();
}
}
else
{
newLogger = new Logger();
}
if (cacheKey.ConcreteType != null)
{
newLogger.Initialize(cacheKey.Name, this.GetConfigurationForLogger(cacheKey.Name, this.Configuration), this);
}
// TODO: Clarify what is the intention when cacheKey.ConcreteType = null.
// At the moment, a logger typeof(Logger) will be created but the ConcreteType
// will remain null and inserted into the cache.
// Should we set cacheKey.ConcreteType = typeof(Logger) for default loggers?
loggerCache.InsertOrUpdate(cacheKey, newLogger);
return newLogger;
}
}
#if !SILVERLIGHT
private void ConfigFileChanged(object sender, EventArgs args)
{
InternalLogger.Info("Configuration file change detected! Reloading in {0}ms...", LogFactory.ReconfigAfterFileChangedTimeout);
// In the rare cases we may get multiple notifications here,
// but we need to reload config only once.
//
// The trick is to schedule the reload in one second after
// the last change notification comes in.
lock (this.syncRoot)
{
if (this.reloadTimer == null)
{
this.reloadTimer = new Timer(
this.ReloadConfigOnTimer,
this.Configuration,
LogFactory.ReconfigAfterFileChangedTimeout,
Timeout.Infinite);
}
else
{
this.reloadTimer.Change(
LogFactory.ReconfigAfterFileChangedTimeout,
Timeout.Infinite);
}
}
}
#endif
private void LoadLoggingConfiguration(string configFile)
{
InternalLogger.Debug("Loading config from {0}", configFile);
this.config = new XmlLoggingConfiguration(configFile);
}
#if !SILVERLIGHT
/// <summary>
/// Currenty this logfactory is disposing?
/// </summary>
private bool IsDisposing;
private void currentAppDomain_DomainUnload(object sender, EventArgs e)
{
//stop timer on domain unload, otherwise:
//Exception: System.AppDomainUnloadedException
//Message: Attempted to access an unloaded AppDomain.
lock (this.syncRoot)
{
IsDisposing = true;
if (this.reloadTimer != null)
{
this.reloadTimer.Dispose();
this.reloadTimer = null;
}
}
}
#endif
/// <summary>
/// Logger cache key.
/// </summary>
internal class LoggerCacheKey : IEquatable<LoggerCacheKey>
{
public string Name { get; private set; }
public Type ConcreteType { get; private set; }
public LoggerCacheKey(string name, Type concreteType)
{
this.Name = name;
this.ConcreteType = concreteType;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
return this.ConcreteType.GetHashCode() ^ this.Name.GetHashCode();
}
/// <summary>
/// Determines if two objects are equal in value.
/// </summary>
/// <param name="obj">Other object to compare to.</param>
/// <returns>True if objects are equal, false otherwise.</returns>
public override bool Equals(object obj)
{
LoggerCacheKey key = obj as LoggerCacheKey;
if (ReferenceEquals(key, null))
{
return false;
}
return (this.ConcreteType == key.ConcreteType) && (key.Name == this.Name);
}
/// <summary>
/// Determines if two objects of the same type are equal in value.
/// </summary>
/// <param name="key">Other object to compare to.</param>
/// <returns>True if objects are equal, false otherwise.</returns>
public bool Equals(LoggerCacheKey key)
{
if (ReferenceEquals(key, null))
{
return false;
}
return (this.ConcreteType == key.ConcreteType) && (key.Name == this.Name);
}
}
/// <summary>
/// Logger cache.
/// </summary>
private class LoggerCache
{
// The values of WeakReferences are of type Logger i.e. Directory<LoggerCacheKey, Logger>.
private readonly Dictionary<LoggerCacheKey, WeakReference> loggerCache =
new Dictionary<LoggerCacheKey, WeakReference>();
/// <summary>
/// Inserts or updates.
/// </summary>
/// <param name="cacheKey"></param>
/// <param name="logger"></param>
public void InsertOrUpdate(LoggerCacheKey cacheKey, Logger logger)
{
loggerCache[cacheKey] = new WeakReference(logger);
}
public Logger Retrieve(LoggerCacheKey cacheKey)
{
WeakReference loggerReference;
if (loggerCache.TryGetValue(cacheKey, out loggerReference))
{
// logger in the cache and still referenced
return loggerReference.Target as Logger;
}
return null;
}
public IEnumerable<Logger> Loggers
{
get { return GetLoggers(); }
}
private IEnumerable<Logger> GetLoggers()
{
// TODO: Test if loggerCache.Values.ToList<Logger>() can be used for the conversion instead.
List<Logger> values = new List<Logger>(loggerCache.Count);
foreach (WeakReference loggerReference in loggerCache.Values)
{
Logger logger = loggerReference.Target as Logger;
if (logger != null)
{
values.Add(logger);
}
}
return values;
}
}
/// <summary>
/// Enables logging in <see cref="IDisposable.Dispose"/> implementation.
/// </summary>
private class LogEnabler : IDisposable
{
private LogFactory factory;
/// <summary>
/// Initializes a new instance of the <see cref="LogEnabler" /> class.
/// </summary>
/// <param name="factory">The factory.</param>
public LogEnabler(LogFactory factory)
{
this.factory = factory;
}
/// <summary>
/// Enables logging.
/// </summary>
void IDisposable.Dispose()
{
this.factory.ResumeLogging();
}
}
}
}
| |
using UnityEngine;
using System.Collections;
public class phone_Transform_localRotation : MonoBehaviour {
Quaternion[] animVar;
float deltaTime;
float startTime;
void Start(){
startTime = Time.time;
deltaTime = 1f/60f;
animVar = new Quaternion[560];
animVar[0] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[1] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[2] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[3] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[4] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[5] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[6] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[7] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[8] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[9] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[10] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[11] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[12] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[13] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[14] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[15] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[16] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[17] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[18] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[19] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[20] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[21] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[22] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[23] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[24] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[25] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[26] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[27] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[28] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[29] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[30] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[31] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[32] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[33] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[34] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[35] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[36] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[37] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[38] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[39] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[40] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[41] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[42] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[43] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[44] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[45] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[46] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[47] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[48] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[49] = new Quaternion(-0.707106f,0.000000f,-0.001327f,0.707106f);
animVar[50] = new Quaternion(-0.707106f,-0.000027f,-0.001300f,0.707106f);
animVar[51] = new Quaternion(-0.707106f,-0.000837f,-0.000488f,0.707106f);
animVar[52] = new Quaternion(-0.707103f,-0.002740f,0.001418f,0.707103f);
animVar[53] = new Quaternion(-0.707089f,-0.005697f,0.004381f,0.707089f);
animVar[54] = new Quaternion(-0.707049f,-0.009675f,0.008366f,0.707049f);
animVar[55] = new Quaternion(-0.706968f,-0.014640f,0.013341f,0.706968f);
animVar[56] = new Quaternion(-0.706826f,-0.020564f,0.019276f,0.706826f);
animVar[57] = new Quaternion(-0.706599f,-0.027415f,0.026141f,0.706599f);
animVar[58] = new Quaternion(-0.706263f,-0.035166f,0.033906f,0.706263f);
animVar[59] = new Quaternion(-0.705788f,-0.043785f,0.042543f,0.705788f);
animVar[60] = new Quaternion(-0.705145f,-0.053243f,0.052019f,0.705145f);
animVar[61] = new Quaternion(-0.704303f,-0.063505f,0.062303f,0.704303f);
animVar[62] = new Quaternion(-0.703229f,-0.074537f,0.073357f,0.703229f);
animVar[63] = new Quaternion(-0.701891f,-0.086299f,0.085144f,0.701891f);
animVar[64] = new Quaternion(-0.700257f,-0.098749f,0.097620f,0.700257f);
animVar[65] = new Quaternion(-0.698294f,-0.111839f,0.110739f,0.698294f);
animVar[66] = new Quaternion(-0.695973f,-0.125519f,0.124448f,0.695973f);
animVar[67] = new Quaternion(-0.693268f,-0.139731f,0.138692f,0.693268f);
animVar[68] = new Quaternion(-0.690153f,-0.154415f,0.153409f,0.690153f);
animVar[69] = new Quaternion(-0.686609f,-0.169505f,0.168535f,0.686609f);
animVar[70] = new Quaternion(-0.682622f,-0.184932f,0.183997f,0.682622f);
animVar[71] = new Quaternion(-0.678182f,-0.200621f,0.199725f,0.678182f);
animVar[72] = new Quaternion(-0.673286f,-0.216497f,0.215639f,0.673286f);
animVar[73] = new Quaternion(-0.667939f,-0.232480f,0.231663f,0.667939f);
animVar[74] = new Quaternion(-0.662151f,-0.248492f,0.247716f,0.662151f);
animVar[75] = new Quaternion(-0.655941f,-0.264453f,0.263718f,0.655941f);
animVar[76] = new Quaternion(-0.649334f,-0.280284f,0.279592f,0.649334f);
animVar[77] = new Quaternion(-0.642362f,-0.295910f,0.295260f,0.642362f);
animVar[78] = new Quaternion(-0.635065f,-0.311258f,0.310650f,0.635065f);
animVar[79] = new Quaternion(-0.627486f,-0.326259f,0.325694f,0.627486f);
animVar[80] = new Quaternion(-0.619676f,-0.340852f,0.340329f,0.619676f);
animVar[81] = new Quaternion(-0.611687f,-0.354979f,0.354497f,0.611687f);
animVar[82] = new Quaternion(-0.603576f,-0.368589f,0.368148f,0.603576f);
animVar[83] = new Quaternion(-0.595403f,-0.381639f,0.381238f,0.595403f);
animVar[84] = new Quaternion(-0.587227f,-0.394090f,0.393728f,0.587227f);
animVar[85] = new Quaternion(-0.579109f,-0.405913f,0.405588f,0.579109f);
animVar[86] = new Quaternion(-0.571108f,-0.417081f,0.416792f,0.571108f);
animVar[87] = new Quaternion(-0.563283f,-0.427576f,0.427321f,0.563283f);
animVar[88] = new Quaternion(-0.555692f,-0.437383f,0.437161f,0.555692f);
animVar[89] = new Quaternion(-0.548389f,-0.446492f,0.446301f,0.548389f);
animVar[90] = new Quaternion(-0.541426f,-0.454897f,0.454735f,0.541426f);
animVar[91] = new Quaternion(-0.534855f,-0.462594f,0.462458f,0.534855f);
animVar[92] = new Quaternion(-0.528722f,-0.469580f,0.469468f,0.528722f);
animVar[93] = new Quaternion(-0.523073f,-0.475854f,0.475765f,0.523073f);
animVar[94] = new Quaternion(-0.517950f,-0.481416f,0.481347f,0.517950f);
animVar[95] = new Quaternion(-0.513393f,-0.486264f,0.486213f,0.513393f);
animVar[96] = new Quaternion(-0.509441f,-0.490395f,0.490360f,0.509441f);
animVar[97] = new Quaternion(-0.506131f,-0.493805f,0.493782f,0.506131f);
animVar[98] = new Quaternion(-0.503498f,-0.496484f,0.496471f,0.503498f);
animVar[99] = new Quaternion(-0.501576f,-0.498422f,0.498416f,0.501576f);
animVar[100] = new Quaternion(-0.500399f,-0.499601f,0.499600f,0.500399f);
animVar[101] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[102] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[103] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[104] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[105] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[106] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[107] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[108] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[109] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[110] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[111] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[112] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[113] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[114] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[115] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[116] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[117] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[118] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[119] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[120] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[121] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[122] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[123] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[124] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[125] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[126] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[127] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[128] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[129] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[130] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[131] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[132] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[133] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[134] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[135] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[136] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[137] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[138] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[139] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[140] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[141] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[142] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[143] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[144] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[145] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[146] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[147] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[148] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[149] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[150] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[151] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[152] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[153] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[154] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[155] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[156] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[157] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[158] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[159] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[160] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[161] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[162] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[163] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[164] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[165] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[166] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[167] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[168] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[169] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[170] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[171] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[172] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[173] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[174] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[175] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[176] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[177] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[178] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[179] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[180] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[181] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[182] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[183] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[184] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[185] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[186] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[187] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[188] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[189] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[190] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[191] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[192] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[193] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[194] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[195] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[196] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[197] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[198] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[199] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[200] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[201] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[202] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[203] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[204] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[205] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[206] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[207] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[208] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[209] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[210] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[211] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[212] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[213] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[214] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[215] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[216] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[217] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[218] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[219] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[220] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[221] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[222] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[223] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[224] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[225] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[226] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[227] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[228] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[229] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[230] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[231] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[232] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[233] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[234] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[235] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[236] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[237] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[238] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[239] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[240] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[241] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[242] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[243] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[244] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[245] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[246] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[247] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[248] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[249] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[250] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[251] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[252] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[253] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[254] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[255] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[256] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[257] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[258] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[259] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[260] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[261] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[262] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[263] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[264] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[265] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[266] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[267] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[268] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[269] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[270] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[271] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[272] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[273] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[274] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[275] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[276] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[277] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[278] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[279] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[280] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[281] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[282] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[283] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[284] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[285] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[286] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[287] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[288] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[289] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[290] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[291] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[292] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[293] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[294] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[295] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[296] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[297] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[298] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[299] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[300] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[301] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[302] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[303] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[304] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[305] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[306] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[307] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[308] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[309] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[310] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[311] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[312] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[313] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[314] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[315] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[316] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[317] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[318] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[319] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[320] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[321] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[322] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[323] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[324] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[325] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[326] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[327] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[328] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[329] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[330] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[331] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[332] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[333] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[334] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[335] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[336] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[337] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[338] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[339] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[340] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[341] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[342] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[343] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[344] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[345] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[346] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[347] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[348] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[349] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[350] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[351] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[352] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[353] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[354] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[355] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[356] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[357] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[358] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[359] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[360] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[361] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[362] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[363] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[364] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[365] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[366] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[367] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[368] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[369] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[370] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[371] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[372] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[373] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[374] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[375] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[376] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[377] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[378] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[379] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[380] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[381] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[382] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[383] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[384] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[385] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[386] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[387] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[388] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[389] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[390] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[391] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[392] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[393] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[394] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[395] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[396] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[397] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[398] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[399] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[400] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[401] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[402] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[403] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[404] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[405] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[406] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[407] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[408] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[409] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[410] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[411] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[412] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[413] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[414] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[415] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[416] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[417] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[418] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[419] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[420] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[421] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[422] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[423] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[424] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[425] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[426] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[427] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[428] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[429] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[430] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[431] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[432] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[433] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[434] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[435] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[436] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[437] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[438] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[439] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[440] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[441] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[442] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[443] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[444] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[445] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[446] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[447] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[448] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[449] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[450] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[451] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[452] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[453] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[454] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[455] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[456] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[457] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[458] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[459] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[460] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[461] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[462] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[463] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[464] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[465] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[466] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[467] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[468] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[469] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[470] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[471] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[472] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[473] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[474] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[475] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[476] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[477] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[478] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[479] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[480] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[481] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[482] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[483] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[484] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[485] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[486] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[487] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[488] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[489] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[490] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[491] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[492] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[493] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[494] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[495] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[496] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[497] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[498] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[499] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[500] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[501] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[502] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[503] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[504] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[505] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[506] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[507] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[508] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[509] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[510] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[511] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[512] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[513] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[514] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[515] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[516] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[517] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[518] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[519] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[520] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[521] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[522] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[523] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[524] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[525] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[526] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[527] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[528] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[529] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[530] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[531] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[532] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[533] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[534] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[535] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[536] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[537] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[538] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[539] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[540] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[541] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[542] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[543] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[544] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[545] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[546] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[547] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[548] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[549] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[550] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[551] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[552] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[553] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[554] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[555] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[556] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[557] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[558] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
animVar[559] = new Quaternion(-0.500000f,-0.500000f,0.500000f,0.500000f);
comp = gameObject.GetComponent<Transform>();
}
Transform comp;
public float numFrame;
void Update () {
numFrame = (Time.time-startTime)/deltaTime;
if( numFrame>=(float)animVar.Length-1 ) {numFrame=(float)animVar.Length-1.01f;}
float alpha = numFrame-Mathf.Floor(numFrame)/deltaTime;
comp.localRotation = Quaternion.Slerp(animVar[Mathf.FloorToInt(numFrame)],animVar[Mathf.CeilToInt(numFrame)],alpha);
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Scalars.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Services.Protocols {
using System.Web.Services;
using System.Collections;
using System.Globalization;
using System.Reflection;
using System;
using System.Text;
using System.Threading;
internal class ScalarFormatter {
private ScalarFormatter() { }
internal static string ToString(object value) {
if (value == null)
return string.Empty;
else if (value is string)
return (string)value;
else if (value.GetType().IsEnum)
return EnumToString(value);
else
return (string)Convert.ToString(value, CultureInfo.InvariantCulture);
}
internal static object FromString(string value, Type type) {
try {
if (type == typeof(string))
return value;
else if (type.IsEnum)
return (object)EnumFromString(value, type);
else
return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
throw new ArgumentException(Res.GetString(Res.WebChangeTypeFailed, value, type.FullName), "type", e);
}
}
static object EnumFromString(string value, Type type) {
return Enum.Parse(type, value);
}
static string EnumToString(object value) {
return Enum.Format(value.GetType(), value, "G");
}
// We support: whatever Convert supports, and Enums
internal static bool IsTypeSupported(Type type) {
if (type.IsEnum) return true;
return (
type == typeof(int) ||
type == typeof(string) ||
type == typeof(long) ||
type == typeof(byte) ||
type == typeof(sbyte) ||
type == typeof(short) ||
type == typeof(bool) ||
type == typeof(char) ||
type == typeof(float) ||
type == typeof(decimal) ||
type == typeof(DateTime) ||
type == typeof(UInt16) ||
type == typeof(UInt32) ||
type == typeof(UInt64) ||
type == typeof(double));
}
}
internal class UrlEncoder {
private UrlEncoder() { }
private const int Max16BitUtf8SequenceLength = 4;
internal static string EscapeString(string s, Encoding e) {
return EscapeStringInternal(s, e == null ? new ASCIIEncoding() : e, false);
}
internal static string UrlEscapeString(string s, Encoding e) {
return EscapeStringInternal(s, e == null ? new ASCIIEncoding() : e, true);
}
private static string EscapeStringInternal(string s, Encoding e, bool escapeUriStuff) {
if (s == null) return null;
byte[] bytes = e.GetBytes(s);
StringBuilder sb = new StringBuilder(bytes.Length);
for (int i = 0; i < bytes.Length; i++) {
byte b = bytes[i];
char c = (char)b;
if (b > 0x7f || b < 0x20 || c == '%' || (escapeUriStuff && !IsSafe(c))) {
HexEscape8(sb, c);
}
else {
sb.Append(c);
}
}
return sb.ToString();
}
/*
// [....]: adapted from UrlEscapeStringUnicode below
internal static string EscapeStringUnicode(string s) {
int l = s.Length;
StringBuilder sb = new StringBuilder(l);
for (int i = 0; i < l; i++) {
char ch = s[i];
if ((ch & 0xff80) == 0) {
sb.Append(ch);
}
else {
HexEscape16(sb, ch);
}
}
return sb.ToString();
}
*/
// [....]: copied from System.Web.HttpUtility
internal static string UrlEscapeStringUnicode(string s) {
int l = s.Length;
StringBuilder sb = new StringBuilder(l);
for (int i = 0; i < l; i++) {
char ch = s[i];
if (IsSafe(ch)) {
sb.Append(ch);
}
else if (ch == ' ') {
sb.Append('+');
}
else if ((ch & 0xff80) == 0) { // 7 bit?
HexEscape8(sb, ch);
}
else { // arbitrary Unicode?
HexEscape16(sb, ch);
}
}
return sb.ToString();
}
private static void HexEscape8(StringBuilder sb, char c) {
sb.Append('%');
sb.Append(HexUpperChars[(c >> 4) & 0xf]);
sb.Append(HexUpperChars[(c) & 0xf]);
}
private static void HexEscape16(StringBuilder sb, char c) {
sb.Append("%u");
sb.Append(HexUpperChars[(c >> 12) & 0xf]);
sb.Append(HexUpperChars[(c >> 8) & 0xf]);
sb.Append(HexUpperChars[(c >> 4) & 0xf]);
sb.Append(HexUpperChars[(c) & 0xf]);
}
private static bool IsSafe(char ch) {
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9')
return true;
switch (ch) {
case '-':
case '_':
case '.':
case '!':
case '*':
case '\'':
case '(':
case ')':
return true;
}
return false;
}
internal static readonly char[] HexUpperChars = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
}
internal class ContentType {
private ContentType() { }
internal const string TextBase = "text";
internal const string TextXml = "text/xml";
internal const string TextPlain = "text/plain";
internal const string TextHtml = "text/html";
internal const string ApplicationBase = "application";
internal const string ApplicationXml = "application/xml";
internal const string ApplicationSoap = "application/soap+xml";
internal const string ApplicationOctetStream = "application/octet-stream";
internal const string ContentEncoding = "Content-Encoding";
// this returns the "base" part of the contentType/mimeType, e.g. the "text/xml" part w/o
// the ; CharSet=isoxxx part that sometimes follows.
internal static string GetBase(string contentType) {
int semi = contentType.IndexOf(';');
if (semi >= 0) return contentType.Substring(0, semi);
return contentType;
}
// this returns the "type" part of the contentType/mimeType without subtyape
internal static string GetMediaType(string contentType) {
string baseCT = GetBase(contentType);
int tmp = baseCT.IndexOf('/');
if (tmp >= 0) return baseCT.Substring(0, tmp);
return baseCT;
}
// grabs as follows (and case-insensitive): .*;\s*charset\s*=\s*[\s'"]*(.*)[\s'"]*
internal static string GetCharset(string contentType) {
return GetParameter(contentType, "charset");
}
internal static string GetAction(string contentType) {
return GetParameter(contentType, "action");
}
private static string GetParameter(string contentType, string paramName) {
string[] paramDecls = contentType.Split(new char[] { ';' });
for (int i = 1; i < paramDecls.Length; i++) {
string paramDecl = paramDecls[i].TrimStart(null);
if (String.Compare(paramDecl, 0, paramName, 0, paramName.Length, StringComparison.OrdinalIgnoreCase) == 0) {
int equals = paramDecl.IndexOf('=', paramName.Length);
if (equals >= 0)
return paramDecl.Substring(equals + 1).Trim(new char[] { ' ', '\'', '\"', '\t' });
}
}
return null;
}
internal static bool MatchesBase(string contentType, string baseContentType) {
return string.Compare(GetBase(contentType), baseContentType, StringComparison.OrdinalIgnoreCase) == 0;
}
internal static bool IsApplication(string contentType) {
return string.Compare(GetMediaType(contentType), ApplicationBase, StringComparison.OrdinalIgnoreCase) == 0;
}
internal static bool IsSoap(string contentType) {
string type = GetBase(contentType);
return (String.Compare(type, ContentType.TextXml, StringComparison.OrdinalIgnoreCase) == 0) ||
(String.Compare(type, ContentType.ApplicationSoap, StringComparison.OrdinalIgnoreCase) == 0);
}
internal static bool IsXml(string contentType) {
string type = GetBase(contentType);
return (String.Compare(type, ContentType.TextXml, StringComparison.OrdinalIgnoreCase) == 0) ||
(String.Compare(type, ContentType.ApplicationXml, StringComparison.OrdinalIgnoreCase) == 0);
}
internal static bool IsHtml(string contentType) {
string type = GetBase(contentType);
return String.Compare(type, ContentType.TextHtml, StringComparison.OrdinalIgnoreCase) == 0;
}
internal static string Compose(string contentType, Encoding encoding) {
return Compose(contentType, encoding, null);
}
internal static string Compose(string contentType, Encoding encoding, string action) {
if (encoding == null && action == null) return contentType;
StringBuilder sb = new StringBuilder(contentType);
if (encoding != null) {
sb.Append("; charset=");
sb.Append(encoding.WebName);
}
if (action != null) {
sb.Append("; action=\"");
sb.Append(action);
sb.Append("\"");
}
return sb.ToString();
}
}
internal class MemberHelper {
private MemberHelper() { }
static object[] emptyObjectArray = new object[0];
internal static void SetValue(MemberInfo memberInfo, object target, object value) {
if (memberInfo is FieldInfo ) {
((FieldInfo)memberInfo).SetValue(target, value);
}
else {
((PropertyInfo)memberInfo).SetValue(target, value, emptyObjectArray);
}
}
internal static object GetValue(MemberInfo memberInfo, object target) {
if (memberInfo is FieldInfo) {
return ((FieldInfo)memberInfo).GetValue(target);
}
else {
return ((PropertyInfo)memberInfo).GetValue(target, emptyObjectArray);
}
}
internal static bool IsStatic(MemberInfo memberInfo) {
if (memberInfo is FieldInfo)
return ((FieldInfo)memberInfo).IsStatic;
else
return false;
}
internal static bool CanRead(MemberInfo memberInfo) {
if (memberInfo is FieldInfo)
return true;
else
return ((PropertyInfo)memberInfo).CanRead;
}
internal static bool CanWrite(MemberInfo memberInfo) {
if (memberInfo is FieldInfo)
return true;
else
return ((PropertyInfo)memberInfo).CanWrite;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans.CodeGeneration;
using Orleans.Concurrency;
using Orleans.Metadata;
namespace Orleans.Runtime
{
/// <summary>
/// The central point for creating grain contexts.
/// </summary>
public sealed class GrainContextActivator
{
private readonly object _lockObj = new object();
private readonly IGrainContextActivatorProvider[] _activatorProviders;
private readonly IConfigureGrainContextProvider[] _configuratorProviders;
private readonly GrainPropertiesResolver _resolver;
private ImmutableDictionary<GrainType, ActivatorEntry> _activators = ImmutableDictionary<GrainType, ActivatorEntry>.Empty;
public GrainContextActivator(
IEnumerable<IGrainContextActivatorProvider> providers,
IEnumerable<IConfigureGrainContextProvider> configureContextActions,
GrainPropertiesResolver grainPropertiesResolver)
{
_resolver = grainPropertiesResolver;
_activatorProviders = providers.ToArray();
_configuratorProviders = configureContextActions.ToArray();
}
/// <summary>
/// Creates a new grain context for the provided grain address.
/// </summary>
public IGrainContext CreateInstance(ActivationAddress address)
{
var grainId = address.Grain;
if (!_activators.TryGetValue(grainId.Type, out var activator))
{
activator = this.CreateActivator(grainId.Type);
}
var result = activator.Activator.CreateContext(address);
foreach (var configure in activator.ConfigureActions)
{
configure.Configure(result);
}
return result;
}
private ActivatorEntry CreateActivator(GrainType grainType)
{
lock (_lockObj)
{
if (!_activators.TryGetValue(grainType, out var configuredActivator))
{
IGrainContextActivator unconfiguredActivator = null;
foreach (var provider in this._activatorProviders)
{
if (provider.TryGet(grainType, out unconfiguredActivator))
{
break;
}
}
if (unconfiguredActivator is null)
{
throw new InvalidOperationException($"Unable to find an {nameof(IGrainContextActivatorProvider)} for grain type {grainType}");
}
var properties = _resolver.GetGrainProperties(grainType);
List<IConfigureGrainContext> configureActions = new List<IConfigureGrainContext>();
foreach (var provider in _configuratorProviders)
{
if (provider.TryGetConfigurator(grainType, properties, out var configurator))
{
configureActions.Add(configurator);
}
}
var applicableConfigureActions = configureActions.Count > 0 ? configureActions.ToArray() : Array.Empty<IConfigureGrainContext>();
configuredActivator = new ActivatorEntry(unconfiguredActivator, applicableConfigureActions);
_activators = _activators.SetItem(grainType, configuredActivator);
}
return configuredActivator;
}
}
private readonly struct ActivatorEntry
{
public ActivatorEntry(
IGrainContextActivator activator,
IConfigureGrainContext[] configureActions)
{
this.Activator = activator;
this.ConfigureActions = configureActions;
}
public IGrainContextActivator Activator { get; }
public IConfigureGrainContext[] ConfigureActions { get; }
}
}
/// <summary>
/// Provides a <see cref="IGrainContextActivator"/> for a specified grain type.
/// </summary>
public interface IGrainContextActivatorProvider
{
/// <summary>
/// Returns a grain context activator for the given grain type.
/// </summary>
bool TryGet(GrainType grainType, out IGrainContextActivator activator);
}
/// <summary>
/// Creates a grain context for the given grain address.
/// </summary>
public interface IGrainContextActivator
{
/// <summary>
/// Creates a grain context for the given grain address.
/// </summary>
public IGrainContext CreateContext(ActivationAddress address);
}
/// <summary>
/// Provides a <see cref="IConfigureGrainContext"/> instance for the provided grain type.
/// </summary>
public interface IConfigureGrainContextProvider
{
/// <summary>
/// Provides a <see cref="IConfigureGrainContext"/> instance for the provided grain type.
/// </summary>
bool TryGetConfigurator(GrainType grainType, GrainProperties properties, out IConfigureGrainContext configurator);
}
/// <summary>
/// Configures the provided grain context.
/// </summary>
public interface IConfigureGrainContext
{
/// <summary>
/// Configures the provided grain context.
/// </summary>
void Configure(IGrainContext context);
}
/// <summary>
/// Resolves components which are common to all instances of a given grain type.
/// </summary>
public class GrainTypeComponentsResolver
{
private readonly ConcurrentDictionary<GrainType, GrainTypeComponents> _components = new ConcurrentDictionary<GrainType, GrainTypeComponents>();
private readonly IConfigureGrainTypeComponents[] _configurators;
private readonly GrainPropertiesResolver _resolver;
private readonly Func<GrainType, GrainTypeComponents> _createFunc;
public GrainTypeComponentsResolver(IEnumerable<IConfigureGrainTypeComponents> configurators, GrainPropertiesResolver resolver)
{
_configurators = configurators.ToArray();
_resolver = resolver;
_createFunc = this.Create;
}
/// <summary>
/// Returns shared grain components for the provided grain type.
/// </summary>
public GrainTypeComponents GetComponents(GrainType grainType) => _components.GetOrAdd(grainType, _createFunc);
private GrainTypeComponents Create(GrainType grainType)
{
var result = new GrainTypeComponents();
var properties = _resolver.GetGrainProperties(grainType);
foreach (var configurator in _configurators)
{
configurator.Configure(grainType, properties, result);
}
return result;
}
}
/// <summary>
/// Configures shared components which are common for all instances of a given grain type.
/// </summary>
public interface IConfigureGrainTypeComponents
{
/// <summary>
/// Configures shared components which are common for all instances of a given grain type.
/// </summary>
void Configure(GrainType grainType, GrainProperties properties, GrainTypeComponents shared);
}
/// <summary>
/// Components common to all grains of a given <see cref="GrainType"/>.
/// </summary>
public class GrainTypeComponents
{
private Dictionary<Type, object> _components = new Dictionary<Type, object>();
/// <summary>
/// Gets a component.
/// </summary>
/// <typeparam name="TComponent">The type specified in the corresponding <see cref="SetComponent{TComponent}"/> call.</typeparam>
public TComponent GetComponent<TComponent>()
{
if (_components is null) return default;
_components.TryGetValue(typeof(TComponent), out var resultObj);
return (TComponent)resultObj;
}
/// <summary>
/// Registers a component.
/// </summary>
/// <typeparam name="TComponent">The type which can be used as a key to <see cref="GetComponent{TComponent}"/>.</typeparam>
public void SetComponent<TComponent>(TComponent instance)
{
if (instance == null)
{
_components?.Remove(typeof(TComponent));
return;
}
if (_components is null) _components = new Dictionary<Type, object>();
_components[typeof(TComponent)] = instance;
}
}
internal class ReentrantSharedComponentsConfigurator : IConfigureGrainTypeComponents
{
public void Configure(GrainType grainType, GrainProperties properties, GrainTypeComponents shared)
{
if (properties.Properties.TryGetValue(WellKnownGrainTypeProperties.Reentrant, out var value) && bool.Parse(value))
{
var component = shared.GetComponent<GrainCanInterleave>();
if (component is null)
{
component = new GrainCanInterleave();
shared.SetComponent<GrainCanInterleave>(component);
}
component.MayInterleavePredicates.Add(_ => true);
}
}
}
internal class MayInterleaveConfiguratorProvider : IConfigureGrainContextProvider
{
private readonly GrainClassMap _grainClassMap;
public MayInterleaveConfiguratorProvider(GrainClassMap grainClassMap)
{
_grainClassMap = grainClassMap;
}
public bool TryGetConfigurator(GrainType grainType, GrainProperties properties, out IConfigureGrainContext configurator)
{
if (properties.Properties.TryGetValue(WellKnownGrainTypeProperties.MayInterleavePredicate, out var value)
&& _grainClassMap.TryGetGrainClass(grainType, out var grainClass))
{
var predicate = GetMayInterleavePredicate(grainClass);
configurator = new MayInterleaveConfigurator(message => predicate((InvokeMethodRequest)message.BodyObject));
return true;
}
configurator = null;
return false;
}
/// <summary>
/// Returns interleave predicate depending on whether class is marked with <see cref="MayInterleaveAttribute"/> or not.
/// </summary>
/// <param name="grainType">Grain class.</param>
private static Func<InvokeMethodRequest, bool> GetMayInterleavePredicate(Type grainType)
{
var attribute = grainType.GetCustomAttribute<MayInterleaveAttribute>();
if (attribute is null)
{
return null;
}
var callbackMethodName = attribute.CallbackMethodName;
var method = grainType.GetMethod(callbackMethodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
if (method == null)
{
throw new InvalidOperationException(
$"Class {grainType.FullName} doesn't declare public static method " +
$"with name {callbackMethodName} specified in MayInterleave attribute");
}
if (method.ReturnType != typeof(bool) ||
method.GetParameters().Length != 1 ||
method.GetParameters()[0].ParameterType != typeof(InvokeMethodRequest))
{
throw new InvalidOperationException(
$"Wrong signature of callback method {callbackMethodName} " +
$"specified in MayInterleave attribute for grain class {grainType.FullName}. \n" +
$"Expected: public static bool {callbackMethodName}(InvokeMethodRequest req)");
}
var parameter = Expression.Parameter(typeof(InvokeMethodRequest));
var call = Expression.Call(null, method, parameter);
var predicate = Expression.Lambda<Func<InvokeMethodRequest, bool>>(call, parameter).Compile();
return predicate;
}
}
internal class MayInterleaveConfigurator : IConfigureGrainContext
{
private readonly Func<Message, bool> _mayInterleavePredicate;
public MayInterleaveConfigurator(Func<Message, bool> mayInterleavePredicate)
{
_mayInterleavePredicate = mayInterleavePredicate;
}
public void Configure(IGrainContext context)
{
var component = context.GetComponent<GrainCanInterleave>();
if (component is null)
{
component = new GrainCanInterleave();
context.SetComponent<GrainCanInterleave>(component);
}
component.MayInterleavePredicates.Add(_mayInterleavePredicate);
}
}
internal class GrainCanInterleave
{
public List<Func<Message, bool>> MayInterleavePredicates { get; } = new List<Func<Message, bool>>();
public bool MayInterleave(Message message)
{
foreach (var predicate in this.MayInterleavePredicates)
{
if (predicate(message)) return true;
}
return false;
}
}
internal class ConfigureDefaultGrainActivator : IConfigureGrainTypeComponents
{
private readonly GrainClassMap _grainClassMap;
private readonly ConstructorArgumentFactory _constructorArgumentFactory;
public ConfigureDefaultGrainActivator(GrainClassMap grainClassMap, IServiceProvider serviceProvider)
{
_constructorArgumentFactory = new ConstructorArgumentFactory(serviceProvider);
_grainClassMap = grainClassMap;
}
public void Configure(GrainType grainType, GrainProperties properties, GrainTypeComponents shared)
{
if (shared.GetComponent<IGrainActivator>() is object) return;
if (!_grainClassMap.TryGetGrainClass(grainType, out var grainClass))
{
return;
}
var argumentFactory = _constructorArgumentFactory.CreateFactory(grainClass);
var createGrainInstance = ActivatorUtilities.CreateFactory(grainClass, argumentFactory.ArgumentTypes);
var instanceActivator = new DefaultGrainActivator(createGrainInstance, argumentFactory);
shared.SetComponent<IGrainActivator>(instanceActivator);
}
internal class DefaultGrainActivator : IGrainActivator
{
private readonly ObjectFactory _factory;
private readonly ConstructorArgumentFactory.ArgumentFactory _argumentFactory;
public DefaultGrainActivator(ObjectFactory factory, ConstructorArgumentFactory.ArgumentFactory argumentFactory)
{
_factory = factory;
_argumentFactory = argumentFactory;
}
public object CreateInstance(IGrainContext context)
{
var args = _argumentFactory.CreateArguments(context);
return _factory(context.ActivationServices, args);
}
public async ValueTask DisposeInstance(IGrainContext context, object instance)
{
switch (instance)
{
case IAsyncDisposable asyncDisposable:
await asyncDisposable.DisposeAsync();
break;
case IDisposable disposable:
disposable.Dispose();
break;
}
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// Rfc2898DeriveBytes.cs
//
// This implementation follows RFC 2898 recommendations. See http://www.ietf.org/rfc/Rfc2898.txt
// It uses HMACSHA1 as the underlying pseudorandom function.
namespace System.Security.Cryptography {
using System.Globalization;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography.X509Certificates;
[System.Runtime.InteropServices.ComVisible(true)]
public class Rfc2898DeriveBytes : DeriveBytes
{
private byte[] m_buffer;
private byte[] m_salt;
private HMACSHA1 m_hmacsha1; // The pseudo-random generator function used in PBKDF2
private byte[] m_password;
private CspParameters m_cspParams = new CspParameters();
private uint m_iterations;
private uint m_block;
private int m_startIndex;
private int m_endIndex;
private const int BlockSize = 20;
//
// public constructors
//
public Rfc2898DeriveBytes(string password, int saltSize) : this(password, saltSize, 1000) {}
// This method needs to be safe critical, because in debug builds the C# compiler will include null
// initialization of the _safeProvHandle field in the method. Since SafeProvHandle is critical, a
// transparent reference triggers an error using PasswordDeriveBytes.
[SecuritySafeCritical]
public Rfc2898DeriveBytes(string password, int saltSize, int iterations) {
if (saltSize < 0)
throw new ArgumentOutOfRangeException("saltSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
byte[] salt = new byte[saltSize];
Utils.StaticRandomNumberGenerator.GetBytes(salt);
Salt = salt;
IterationCount = iterations;
m_password = new UTF8Encoding(false).GetBytes(password);
m_hmacsha1 = new HMACSHA1(m_password);
Initialize();
}
public Rfc2898DeriveBytes(string password, byte[] salt) : this(password, salt, 1000) {}
public Rfc2898DeriveBytes(string password, byte[] salt, int iterations) : this (new UTF8Encoding(false).GetBytes(password), salt, iterations) {}
// This method needs to be safe critical, because in debug builds the C# compiler will include null
// initialization of the _safeProvHandle field in the method. Since SafeProvHandle is critical, a
// transparent reference triggers an error using PasswordDeriveBytes.
[SecuritySafeCritical]
public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) {
Salt = salt;
IterationCount = iterations;
m_password = password;
m_hmacsha1 = new HMACSHA1(password);
Initialize();
}
//
// public properties
//
public int IterationCount {
get { return (int) m_iterations; }
set {
if (value <= 0)
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
m_iterations = (uint) value;
Initialize();
}
}
public byte[] Salt {
get { return (byte[]) m_salt.Clone(); }
set {
if (value == null)
throw new ArgumentNullException("value");
if (value.Length < 8)
throw new ArgumentException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_FewBytesSalt"));
Contract.EndContractBlock();
m_salt = (byte[]) value.Clone();
Initialize();
}
}
//
// public methods
//
public override byte[] GetBytes(int cb) {
if (cb <= 0)
throw new ArgumentOutOfRangeException("cb", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
byte[] password = new byte[cb];
int offset = 0;
int size = m_endIndex - m_startIndex;
if (size > 0) {
if (cb >= size) {
Buffer.InternalBlockCopy(m_buffer, m_startIndex, password, 0, size);
m_startIndex = m_endIndex = 0;
offset += size;
} else {
Buffer.InternalBlockCopy(m_buffer, m_startIndex, password, 0, cb);
m_startIndex += cb;
return password;
}
}
Contract.Assert(m_startIndex == 0 && m_endIndex == 0, "Invalid start or end index in the internal buffer." );
while(offset < cb) {
byte[] T_block = Func();
int remainder = cb - offset;
if(remainder > BlockSize) {
Buffer.InternalBlockCopy(T_block, 0, password, offset, BlockSize);
offset += BlockSize;
} else {
Buffer.InternalBlockCopy(T_block, 0, password, offset, remainder);
offset += remainder;
Buffer.InternalBlockCopy(T_block, remainder, m_buffer, m_startIndex, BlockSize - remainder);
m_endIndex += (BlockSize - remainder);
return password;
}
}
return password;
}
public override void Reset() {
Initialize();
}
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
if (disposing) {
if (m_hmacsha1 != null) {
((IDisposable)m_hmacsha1).Dispose();
}
if (m_buffer != null) {
Array.Clear(m_buffer, 0, m_buffer.Length);
}
if (m_salt != null) {
Array.Clear(m_salt, 0, m_salt.Length);
}
}
}
private void Initialize() {
if (m_buffer != null)
Array.Clear(m_buffer, 0, m_buffer.Length);
m_buffer = new byte[BlockSize];
m_block = 1;
m_startIndex = m_endIndex = 0;
}
// This function is defined as follow :
// Func (S, i) = HMAC(S || i) | HMAC2(S || i) | ... | HMAC(iterations) (S || i)
// where i is the block number.
private byte[] Func () {
byte[] INT_block = Utils.Int(m_block);
m_hmacsha1.TransformBlock(m_salt, 0, m_salt.Length, null, 0);
m_hmacsha1.TransformBlock(INT_block, 0, INT_block.Length, null, 0);
m_hmacsha1.TransformFinalBlock(EmptyArray<Byte>.Value, 0, 0);
byte[] temp = m_hmacsha1.HashValue;
m_hmacsha1.Initialize();
byte[] ret = temp;
for (int i = 2; i <= m_iterations; i++) {
m_hmacsha1.TransformBlock(temp, 0, temp.Length, null, 0);
m_hmacsha1.TransformFinalBlock(EmptyArray<Byte>.Value, 0, 0);
temp = m_hmacsha1.HashValue;
for (int j = 0; j < BlockSize; j++) {
ret[j] ^= temp[j];
}
m_hmacsha1.Initialize();
}
// increment the block count.
m_block++;
return ret;
}
[System.Security.SecuritySafeCritical] // auto-generated
public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV)
{
if (keySize < 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
int algidhash = X509Utils.NameOrOidToAlgId(alghashname, OidGroup.HashAlgorithm);
if (algidhash == 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm"));
int algid = X509Utils.NameOrOidToAlgId(algname, OidGroup.AllGroups);
if (algid == 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm"));
// Validate the rgbIV array
if (rgbIV == null)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidIV"));
byte[] key = null;
DeriveKey(ProvHandle, algid, algidhash,
m_password, m_password.Length, keySize << 16, rgbIV, rgbIV.Length,
JitHelpers.GetObjectHandleOnStack(ref key));
return key;
}
[System.Security.SecurityCritical] // auto-generated
private SafeProvHandle _safeProvHandle = null;
private SafeProvHandle ProvHandle
{
[System.Security.SecurityCritical] // auto-generated
get
{
if (_safeProvHandle == null)
{
lock (this)
{
if (_safeProvHandle == null)
{
SafeProvHandle safeProvHandle = Utils.AcquireProvHandle(m_cspParams);
System.Threading.Thread.MemoryBarrier();
_safeProvHandle = safeProvHandle;
}
}
}
return _safeProvHandle;
}
}
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void DeriveKey(SafeProvHandle hProv, int algid, int algidHash,
byte[] password, int cbPassword, int dwFlags, byte[] IV, int cbIV,
ObjectHandleOnStack retKey);
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Internal.Network.Version2017_03_01
{
using Microsoft.Rest.Azure;
using Models;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LoadBalancersOperations operations.
/// </summary>
public partial interface ILoadBalancersOperations
{
/// <summary>
/// Deletes the specified load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<LoadBalancer>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update load balancer
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<LoadBalancer>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the load balancers in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the load balancers in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<LoadBalancer>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update load balancer
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<LoadBalancer>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the load balancers in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the load balancers in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<LoadBalancer>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>PaidOrganicSearchTermView</c> resource.</summary>
public sealed partial class PaidOrganicSearchTermViewName : gax::IResourceName, sys::IEquatable<PaidOrganicSearchTermViewName>
{
/// <summary>The possible contents of <see cref="PaidOrganicSearchTermViewName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/paidOrganicSearchTermViews/{campaign_id}~{ad_group_id}~{base64_search_term}</c>
/// .
/// </summary>
CustomerCampaignAdGroupBase64SearchTerm = 1,
}
private static gax::PathTemplate s_customerCampaignAdGroupBase64SearchTerm = new gax::PathTemplate("customers/{customer_id}/paidOrganicSearchTermViews/{campaign_id_ad_group_id_base64_search_term}");
/// <summary>
/// Creates a <see cref="PaidOrganicSearchTermViewName"/> 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="PaidOrganicSearchTermViewName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static PaidOrganicSearchTermViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new PaidOrganicSearchTermViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="PaidOrganicSearchTermViewName"/> with the pattern
/// <c>customers/{customer_id}/paidOrganicSearchTermViews/{campaign_id}~{ad_group_id}~{base64_search_term}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</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="base64SearchTermId">The <c>Base64SearchTerm</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="PaidOrganicSearchTermViewName"/> constructed from the provided ids.
/// </returns>
public static PaidOrganicSearchTermViewName FromCustomerCampaignAdGroupBase64SearchTerm(string customerId, string campaignId, string adGroupId, string base64SearchTermId) =>
new PaidOrganicSearchTermViewName(ResourceNameType.CustomerCampaignAdGroupBase64SearchTerm, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), base64SearchTermId: gax::GaxPreconditions.CheckNotNullOrEmpty(base64SearchTermId, nameof(base64SearchTermId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PaidOrganicSearchTermViewName"/> with
/// pattern
/// <c>customers/{customer_id}/paidOrganicSearchTermViews/{campaign_id}~{ad_group_id}~{base64_search_term}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</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="base64SearchTermId">The <c>Base64SearchTerm</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PaidOrganicSearchTermViewName"/> with pattern
/// <c>customers/{customer_id}/paidOrganicSearchTermViews/{campaign_id}~{ad_group_id}~{base64_search_term}</c>.
/// </returns>
public static string Format(string customerId, string campaignId, string adGroupId, string base64SearchTermId) =>
FormatCustomerCampaignAdGroupBase64SearchTerm(customerId, campaignId, adGroupId, base64SearchTermId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PaidOrganicSearchTermViewName"/> with
/// pattern
/// <c>customers/{customer_id}/paidOrganicSearchTermViews/{campaign_id}~{ad_group_id}~{base64_search_term}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</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="base64SearchTermId">The <c>Base64SearchTerm</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PaidOrganicSearchTermViewName"/> with pattern
/// <c>customers/{customer_id}/paidOrganicSearchTermViews/{campaign_id}~{ad_group_id}~{base64_search_term}</c>.
/// </returns>
public static string FormatCustomerCampaignAdGroupBase64SearchTerm(string customerId, string campaignId, string adGroupId, string base64SearchTermId) =>
s_customerCampaignAdGroupBase64SearchTerm.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(base64SearchTermId, nameof(base64SearchTermId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="PaidOrganicSearchTermViewName"/> 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}/paidOrganicSearchTermViews/{campaign_id}~{ad_group_id}~{base64_search_term}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="paidOrganicSearchTermViewName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="PaidOrganicSearchTermViewName"/> if successful.</returns>
public static PaidOrganicSearchTermViewName Parse(string paidOrganicSearchTermViewName) =>
Parse(paidOrganicSearchTermViewName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="PaidOrganicSearchTermViewName"/> 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}/paidOrganicSearchTermViews/{campaign_id}~{ad_group_id}~{base64_search_term}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="paidOrganicSearchTermViewName">
/// 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="PaidOrganicSearchTermViewName"/> if successful.</returns>
public static PaidOrganicSearchTermViewName Parse(string paidOrganicSearchTermViewName, bool allowUnparsed) =>
TryParse(paidOrganicSearchTermViewName, allowUnparsed, out PaidOrganicSearchTermViewName 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="PaidOrganicSearchTermViewName"/>
/// 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}/paidOrganicSearchTermViews/{campaign_id}~{ad_group_id}~{base64_search_term}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="paidOrganicSearchTermViewName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PaidOrganicSearchTermViewName"/>, 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 paidOrganicSearchTermViewName, out PaidOrganicSearchTermViewName result) =>
TryParse(paidOrganicSearchTermViewName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PaidOrganicSearchTermViewName"/>
/// 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}/paidOrganicSearchTermViews/{campaign_id}~{ad_group_id}~{base64_search_term}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="paidOrganicSearchTermViewName">
/// 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="PaidOrganicSearchTermViewName"/>, 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 paidOrganicSearchTermViewName, bool allowUnparsed, out PaidOrganicSearchTermViewName result)
{
gax::GaxPreconditions.CheckNotNull(paidOrganicSearchTermViewName, nameof(paidOrganicSearchTermViewName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaignAdGroupBase64SearchTerm.TryParseName(paidOrganicSearchTermViewName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerCampaignAdGroupBase64SearchTerm(resourceName[0], split1[0], split1[1], split1[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(paidOrganicSearchTermViewName, 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 PaidOrganicSearchTermViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string base64SearchTermId = null, string campaignId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AdGroupId = adGroupId;
Base64SearchTermId = base64SearchTermId;
CampaignId = campaignId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="PaidOrganicSearchTermViewName"/> class from the component parts of
/// pattern
/// <c>customers/{customer_id}/paidOrganicSearchTermViews/{campaign_id}~{ad_group_id}~{base64_search_term}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</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="base64SearchTermId">The <c>Base64SearchTerm</c> ID. Must not be <c>null</c> or empty.</param>
public PaidOrganicSearchTermViewName(string customerId, string campaignId, string adGroupId, string base64SearchTermId) : this(ResourceNameType.CustomerCampaignAdGroupBase64SearchTerm, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), base64SearchTermId: gax::GaxPreconditions.CheckNotNullOrEmpty(base64SearchTermId, nameof(base64SearchTermId)))
{
}
/// <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>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>Base64SearchTerm</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string Base64SearchTermId { get; }
/// <summary>
/// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CampaignId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerCampaignAdGroupBase64SearchTerm: return s_customerCampaignAdGroupBase64SearchTerm.Expand(CustomerId, $"{CampaignId}~{AdGroupId}~{Base64SearchTermId}");
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 PaidOrganicSearchTermViewName);
/// <inheritdoc/>
public bool Equals(PaidOrganicSearchTermViewName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(PaidOrganicSearchTermViewName a, PaidOrganicSearchTermViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(PaidOrganicSearchTermViewName a, PaidOrganicSearchTermViewName b) => !(a == b);
}
public partial class PaidOrganicSearchTermView
{
/// <summary>
/// <see cref="PaidOrganicSearchTermViewName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal PaidOrganicSearchTermViewName ResourceNameAsPaidOrganicSearchTermViewName
{
get => string.IsNullOrEmpty(ResourceName) ? null : PaidOrganicSearchTermViewName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
#region BSD License
/*
Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Xml;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using System.IO;
namespace Prebuild.Core.Nodes
{
/// <summary>
///
/// </summary>
[DataNode("Files")]
public class FilesNode : DataNode
{
#region Fields
private StringCollection m_Files;
private Hashtable m_BuildActions;
private Hashtable m_SubTypes;
private Hashtable m_ResourceNames;
private Hashtable m_CopyToOutputs;
private Hashtable m_Links;
private Hashtable m_LinkPaths;
private Hashtable m_PreservePaths;
#endregion
#region Constructors
/// <summary>
///
/// </summary>
public FilesNode()
{
m_Files = new StringCollection();
m_BuildActions = new Hashtable();
m_SubTypes = new Hashtable();
m_ResourceNames = new Hashtable();
m_CopyToOutputs = new Hashtable();
m_Links = new Hashtable();
m_LinkPaths = new Hashtable();
m_PreservePaths = new Hashtable();
}
#endregion
#region Properties
/// <summary>
///
/// </summary>
public int Count
{
get
{
return m_Files.Count;
}
}
#endregion
#region Public Methods
/// <summary>
///
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public BuildAction GetBuildAction(string file)
{
if(!m_BuildActions.ContainsKey(file))
{
return BuildAction.Compile;
}
return (BuildAction)m_BuildActions[file];
}
public CopyToOutput GetCopyToOutput(string file)
{
if (!this.m_CopyToOutputs.ContainsKey(file))
{
return CopyToOutput.Never;
}
return (CopyToOutput) this.m_CopyToOutputs[file];
}
public bool GetIsLink(string file)
{
if (!this.m_Links.ContainsKey(file))
{
return false;
}
return (bool) this.m_Links[file];
}
public string GetLinkPath( string file )
{
if ( !this.m_LinkPaths.ContainsKey( file ) )
{
return string.Empty;
}
return (string)this.m_LinkPaths[ file ];
}
/// <summary>
///
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public SubType GetSubType(string file)
{
if(!m_SubTypes.ContainsKey(file))
{
return SubType.Code;
}
return (SubType)m_SubTypes[file];
}
/// <summary>
///
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public string GetResourceName(string file)
{
if(!m_ResourceNames.ContainsKey(file))
{
return "";
}
return (string)m_ResourceNames[file];
}
/// <summary>
///
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public bool GetPreservePath( string file )
{
if ( !m_PreservePaths.ContainsKey( file ) )
{
return false;
}
return (bool)m_PreservePaths[ file ];
}
/// <summary>
///
/// </summary>
/// <param name="node"></param>
public override void Parse(XmlNode node)
{
if( node == null )
{
throw new ArgumentNullException("node");
}
foreach(XmlNode child in node.ChildNodes)
{
IDataNode dataNode = Kernel.Instance.ParseNode(child, this);
if(dataNode is FileNode)
{
FileNode fileNode = (FileNode)dataNode;
if(fileNode.IsValid)
{
if (!m_Files.Contains(fileNode.Path))
{
m_Files.Add(fileNode.Path);
m_BuildActions[fileNode.Path] = fileNode.BuildAction;
m_SubTypes[fileNode.Path] = fileNode.SubType;
m_ResourceNames[fileNode.Path] = fileNode.ResourceName;
this.m_PreservePaths[ fileNode.Path ] = fileNode.PreservePath;
this.m_Links[ fileNode.Path ] = fileNode.IsLink;
this.m_LinkPaths[ fileNode.Path ] = fileNode.LinkPath;
this.m_CopyToOutputs[ fileNode.Path ] = fileNode.CopyToOutput;
}
}
}
else if(dataNode is MatchNode)
{
foreach(string file in ((MatchNode)dataNode).Files)
{
MatchNode matchNode = (MatchNode)dataNode;
if (!m_Files.Contains(file))
{
m_Files.Add(file);
m_BuildActions[ file ] = matchNode.BuildAction == null ? GetBuildActionByFileName(file) : matchNode.BuildAction;
m_SubTypes[file] = matchNode.SubType == null ? GetSubTypeByFileName(file) : matchNode.SubType.Value;
m_ResourceNames[ file ] = matchNode.ResourceName;
this.m_PreservePaths[ file ] = matchNode.PreservePath;
this.m_Links[ file ] = matchNode.IsLink;
this.m_LinkPaths[ file ] = matchNode.LinkPath;
this.m_CopyToOutputs[ file ] = matchNode.CopyToOutput;
}
}
}
}
}
// TODO: Check in to why StringCollection's enumerator doesn't implement
// IEnumerator?
/// <summary>
///
/// </summary>
/// <returns></returns>
public StringEnumerator GetEnumerator()
{
return m_Files.GetEnumerator();
}
#endregion
}
}
| |
/*
* Created by SharpDevelop.
* User: Anthony.Mason
* Date: 5/7/2007
* Time: 10:35 AM
*
*/
using System;
using System.Collections.Generic;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Configuration;
using System.ComponentModel;
using System.Threading;
using System.Text;
using LibUSBLauncher;
using WebCam_Capture;
using LibHid;
namespace SharpLauncher
{
/// <summary>
/// Main Form of the application
/// </summary>
public partial class MainForm : BaseForm, IDisposable
{
#region Private Data
private LauncherManager _manager = new LauncherManager();
private WebCamCapture _camera = new WebCamCapture();
private Configuration _config = ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
private int _regWidth = 280;
private int _regHeight = 356;
private Thread _candidShotThread;
private System.Windows.Forms.Timer _timer = new System.Windows.Forms.Timer();
#endregion
#region Program Entry Point
[STAThread]
public static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//try
//{
Application.Run(new MainForm());
//}
//catch(Exception e)
//{
// MessageBox.Show("An exception has occurred, and the application must shut down. Please check " + Directory.GetCurrentDirectory() + Log.Filename + " for more information.", "Exception Has Occurred!", MessageBoxButtons.OK, MessageBoxIcon.Error);
// Log.Instance.Out(e);
//}
}
#endregion
#region Constructor
/// <summary>
/// Constructor. Put additional events here.
/// </summary>
public MainForm()
{
InitializeComponent();
this.CheckSettings();
this.Width = _regWidth;
this.Height = _regHeight;
this.btnDown.MouseUp += new MouseEventHandler(btn_Unclicked);
this.btnDownLeft.MouseUp += new MouseEventHandler(btn_Unclicked);
this.btnDownRight.MouseUp += new MouseEventHandler( btn_Unclicked);
this.btnLeft.MouseUp += new MouseEventHandler(btn_Unclicked);
this.btnRight.MouseUp += new MouseEventHandler(btn_Unclicked);
this.btnUpLeft.MouseUp += new MouseEventHandler(btn_Unclicked);
this.btnUp.MouseUp += new MouseEventHandler(btn_Unclicked);
this.btnUpRight.MouseUp += new MouseEventHandler(btn_Unclicked);
this.btnRight.MouseDown += new MouseEventHandler(BtnRightClick);
this.btnLeft.MouseDown += new MouseEventHandler(BtnLeftClick);
this.btnUp.MouseDown += new MouseEventHandler(BtnUpClick);
this.btnDown.MouseDown += new MouseEventHandler(BtnDownClick);
this.btnUpLeft.MouseDown += new MouseEventHandler(BtnUpLeftClick);
this.btnUpRight.MouseDown += new MouseEventHandler(BtnUpRightClick);
this.btnDownLeft.MouseDown += new MouseEventHandler(BtnDownLeftClick);
this.btnDownRight.MouseDown += new MouseEventHandler(BtnDownRightClick);
this.pictureBox1.VisibleChanged += new EventHandler(WebCamVisibilityChanged);
_camera.ImageCaptured += new WebCamCapture.WebCamEventHandler(this.WebCamCapture_ImageCaptured);
this.contextMenuStrip1.Opening += new CancelEventHandler(contextMenuStrip1_Opening);
UsbHidPort dreamCheeky = new UsbHidPort();
UsbHidPort rocketBaby = new UsbHidPort();
dreamCheeky.OnSpecifiedDeviceArrived += new EventHandler(DreamCheekyArrived);
dreamCheeky.OnSpecifiedDeviceRemoved += new EventHandler(DreamCheekyRemoved);
rocketBaby.OnSpecifiedDeviceArrived += new EventHandler(RocketBabyArrived);
rocketBaby.OnSpecifiedDeviceRemoved += new EventHandler(RocketBabyRemoved);
if(this._manager.Connect(dreamCheeky, rocketBaby))
{
//TODO: put logic if(settings[rocket_start] == "Y") then recalibrate launcher
this.updateLaunchersMenu();
}
else
{
this.AddText("No USB Launchers Found, check log");
}
this.chkFire.Checked = _config.AppSettings.Settings[Constants.Settings.FIRE_WHILE_MOVING].Value == "Y" ? true : false;
this.chkSlow.Checked = _config.AppSettings.Settings[Constants.Settings.SLOW].Value == "Y" ? true : false;
bool primeAfterFire = _config.AppSettings.Settings[Constants.Settings.PRIME_AIRTANK].Value == "Y" ? true : false;
foreach (USBLauncher l in _manager.Launchers)
{
if (l is DreamCheekyLauncher)
(l as DreamCheekyLauncher).PrimeAfterFire = primeAfterFire;
else if (l is RocketBabyLauncher)
(l as RocketBabyLauncher).PrimeAfterFire = primeAfterFire;
}
DirectoryInfo dInfo = new DirectoryInfo("images");
if(!dInfo.Exists)
dInfo.Create();
_timer.Interval = 5000;
_timer.Tick += new EventHandler(timer_Tick);
_timer.Start();
}
#endregion
#region Button Event Handlers
/// <summary>
/// Called when the Left arrow button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void BtnUpLeftClick(object sender, EventArgs e)
{
foreach(USBLauncher l in _manager.Launchers)
l.MoveUpLeft();
}
/// <summary>
/// Called when the Up arrow button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void BtnUpClick(object sender, EventArgs e)
{
foreach(USBLauncher l in _manager.Launchers)
l.MoveUp();
}
/// <summary>
/// Called when the Up-Right arrow button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void BtnUpRightClick(object sender, EventArgs e)
{
foreach(USBLauncher l in _manager.Launchers)
l.MoveUpRight();
}
/// <summary>
/// Called when the Left arrow button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void BtnLeftClick(object sender, EventArgs e)
{
foreach(USBLauncher l in _manager.Launchers)
l.MoveLeft();
}
/// <summary>
/// Called when the right arrow button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void BtnRightClick(object sender, EventArgs e)
{
foreach(USBLauncher l in _manager.Launchers)
l.MoveRight();
}
/// <summary>
/// Called when the Down-Left arrow button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void BtnDownLeftClick(object sender, EventArgs e)
{
foreach(USBLauncher l in _manager.Launchers)
l.MoveDownLeft();
}
void BtnDownClick(object sender, EventArgs e)
{
foreach(USBLauncher l in _manager.Launchers)
l.MoveDown();
}
/// <summary>
/// Called when the Down-Right arrow button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void BtnDownRightClick(object sender, EventArgs e)
{
foreach(USBLauncher l in _manager.Launchers)
l.MoveDownRight();
}
/// <summary>
/// Called when the Fire button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void BtnFireClick(object sender, EventArgs e)
{
foreach(USBLauncher l in _manager.Launchers)
l.Fire();
this.checkCandidShots();
}
/// <summary>
/// Called when the Prime button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void BtnPrimeClick(object sender, EventArgs e)
{
foreach(DreamCheekyLauncher r in _manager.Launchers)
r.Prime();
}
/// <summary>
/// Called when any movement buttons on the form are released, sends the kill command
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btn_Unclicked(object sender, EventArgs e)
{
foreach(USBLauncher l in _manager.Launchers)
l.Stop();
}
/// <summary>
/// Called when the stop button is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void BtnStopClick(object sender, EventArgs e)
{
foreach(USBLauncher l in _manager.Launchers)
l.Stop();
}
#endregion
#region Other GUI Event Handlers
/// <summary>
/// Called when the Slow checkbox is clicked or unclicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void ChkSlowCheckedChanged(object sender, EventArgs e)
{
bool visible = !this.chkSlow.Checked;
if(chkSlow.Checked)
{
reset();
chkFire.Checked = false;
foreach(USBLauncher l in _manager.Launchers)
{
l.Slow = true;
l.FireWhileMoving = false;
}
}
else
{
foreach(USBLauncher l in _manager.Launchers)
{
l.Slow = false;
}
}
this.btnDownLeft.Visible = visible;
this.btnDownRight.Visible = visible;
this.btnUpLeft.Visible = visible;
this.btnUpRight.Visible = visible;
_config.AppSettings.Settings[Constants.Settings.SLOW].Value = this.chkSlow.Checked ? "Y" : "N";
}
/// <summary>
/// Called when the "Attempt Fire While Moving" checkbox is clicked or unclicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void ChkFireCheckedChanged(object sender, EventArgs e)
{
bool visible = !this.chkFire.Checked;
if(chkFire.Checked)
{
reset();
chkSlow.Checked = false;
foreach(USBLauncher l in _manager.Launchers)
{
l.FireWhileMoving = true;
l.Slow = false;
}
}
else
{
foreach(USBLauncher l in _manager.Launchers)
l.FireWhileMoving = false;
}
this.btnUp.Visible = visible;
this.btnDown.Visible = visible;
this.btnDownLeft.Visible = visible;
_config.AppSettings.Settings[Constants.Settings.FIRE_WHILE_MOVING].Value = this.chkFire.Checked ? "Y" : "N";
}
/// <summary>
/// Called when View->Webcam is clicked(toggled).
/// It is also called anytime you minimize / restore,
/// since we close the webcam while minimized
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void WebCamVisibilityChanged(object sender, EventArgs e)
{
if(this.pictureBox1.Visible)
{
int width = Convert.ToInt32(_config.AppSettings.Settings[Constants.Settings.CAMERA_WIDTH].Value);
int height = Convert.ToInt32(_config.AppSettings.Settings[Constants.Settings.CAMERA_HEIGHT].Value);
this.pictureBox1.Width = width;
this.pictureBox1.Height = height;
_camera.CaptureWidth = width;
_camera.CaptureHeight = height;
this.Width = _regWidth + width + 45;
if(_regHeight > height + 30)
this.Height = _regHeight;
else
this.Height = height + 130;
_camera.TimeToCapture_milliseconds = Convert.ToInt32(_config.AppSettings.Settings[Constants.Settings.WEBCAM_REFRESH_RATE].Value);
_camera.Start(0);
this.snapPictureToolStripMenuItem.Enabled = true;
}
else
{
this.Width = _regWidth;
this.Height = _regHeight;
this.snapPictureToolStripMenuItem.Enabled = false;
_camera.Stop();
}
}
/// <summary>
/// Called every time the webcam gets a new image, which depends
/// on the refresh rate determined in the settings menu
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
private void WebCamCapture_ImageCaptured(object source, WebCam_Capture.WebcamEventArgs e)
{
// set the picturebox picture
this.pictureBox1.Image = e.WebCamImage;
}
/// <summary>
/// Called just before the form closes, we save the settings file
/// and attempt to dispose of objects
/// </summary>
/// <param name="e"></param>
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
this.pictureBox1.Visible = false;
_camera.Stop();
_manager.Disconnect();
this.toolStripStatusLabel1.Text = "Saving settings...";
Application.DoEvents();
_config.Save(System.Configuration.ConfigurationSaveMode.Modified);
_camera.Dispose();
_manager.Dispose();
//Log.Instance.Dispose();
base.OnClosing(e);
}
/// <summary>
/// Called the first time the form is opened and shown
/// </summary>
/// <param name="e"></param>
protected override void OnShown(EventArgs e)
{
if(this.webcamToolStripMenuItem.Checked
|| _config.AppSettings.Settings[Constants.Settings.WEBCAM_ON_START].Value == "Y")
{
this.pictureBox1.Visible = true;
this.webcamToolStripMenuItem.Checked = true;
}
else
{
this.pictureBox1.Visible = false;
this.WebCamVisibilityChanged(null,null);
this.webcamToolStripMenuItem.Checked = false;
this.Width = _regWidth;
this.Height = _regHeight;
}
}
/// <summary>
/// Called anytime the Window is resized, if minimized,
/// we turn off the camera
/// </summary>
/// <param name="e"></param>
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if(this.WindowState == FormWindowState.Minimized)
{
foreach(USBLauncher l in _manager.Launchers)
l.Pause();
this.pictureBox1.Visible = false;
this.Hide();
this.notifyIcon1.Visible = true;
}
}
/// <summary>
/// Called when you double click the icon in the system tray,
/// we restore the window to its previous state
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void NotifyIcon1MouseDoubleClick(object sender, MouseEventArgs e)
{
foreach(USBLauncher l in _manager.Launchers)
l.Continue();
this.Show();
this.OnShown(null);
this.WindowState = FormWindowState.Normal;
this.notifyIcon1.Visible = false;
}
/// <summary>
/// Called when the notifyicon is right clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void contextMenuStrip1_Opening(object sender, System.EventArgs e)
{
//if the camera isn't active, we disable the snap picture button
this.snapPictureToolStripMenuItem1.Enabled = this.webcamToolStripMenuItem.Checked;
}
/// <summary>
/// Called when notifyicon is right clicked -> Restore, we just manually call the same
/// as if it was double clicked to eliminate copy and paste code reuse :)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void RestoreToolStripMenuItemClick(object sender, EventArgs e)
{
this.NotifyIcon1MouseDoubleClick(null,null);
}
/// <summary>
/// Called when any item in the Launchers menu is checked or unchecked.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void launcherToolStripMenuItem_Checked(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
string name = item.Name;
int num = -1;
for(int i = 1; i<= _manager.Launchers.Count; i++)
{
if(name.EndsWith(i.ToString()))
{
num = i;
break;
}
}
if(num == -1)
return;
USBLauncher l = _manager.Launchers[num - 1]; //zero based, so so subtract one
l.Enabled = item.Checked;
}
#endregion
#region Menu Item Click Events
/// <summary>
/// Called when File->Exit is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void ExitToolStripMenuItemClick(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// Called when View->Webcam is clicked(toggled)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void WebcamToolStripMenuItemClick(object sender, EventArgs e)
{
if(this.webcamToolStripMenuItem.Checked)
{
_config.AppSettings.Settings[Constants.Settings.WEBCAM_ON_START].Value = "Y";
this.pictureBox1.Visible = true;
}
else
{
_config.AppSettings.Settings[Constants.Settings.WEBCAM_ON_START].Value = "N";
this.pictureBox1.Visible = false;
}
}
/// <summary>
/// Called when Help->About is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void AboutToolStripMenuItemClick(object sender, EventArgs e)
{
AboutForm frm = new AboutForm();
frm.ShowDialog(this);
}
/// <summary>
/// Called when Tools->Settings is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void SettingsToolStripMenuItemClick(object sender, EventArgs e)
{
SettingsForm frm = new SettingsForm(_config);
frm.ShowDialog(this);
if(frm.CameraSettingsChanged)
{
_camera.Stop();
this.pictureBox1.Visible = false;
this.pictureBox1.Visible = this.webcamToolStripMenuItem.Checked;
_camera.TimeToCapture_milliseconds = Convert.ToInt32(_config.AppSettings.Settings[Constants.Settings.WEBCAM_REFRESH_RATE].Value);
_camera.Start(0);
}
bool primeAfterFire = _config.AppSettings.Settings[Constants.Settings.PRIME_AIRTANK].Value == "Y" ? true : false;
foreach(DreamCheekyLauncher r in _manager.Launchers)
r.PrimeAfterFire = primeAfterFire;
}
/// <summary>
/// Called when Help->Donate is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void DonateToolStripMenuItemClick(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://www.antmason.com/wiki/index.php/AntMason:Site_support");
}
/// <summary>
/// Called when Help->Controls is called
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void ControlsToolStripMenuItemClick(object sender, EventArgs e)
{
ControlsForm frm = new ControlsForm();
frm.ShowDialog(this);
}
/// <summary>
/// Called when Tools->Snap Picture is called, or likewise when F10 is pressed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void snapPictureToolStripMenuItem_Click(object sender, EventArgs e)
{
this.toolStripStatusLabel1.Text = "Saving image...";
Application.DoEvents();
_camera.Stop();
DirectoryInfo dInfo = new DirectoryInfo("images");
if(!dInfo.Exists)
{
this.toolStripStatusLabel1.Text = "Could not save picture, " + dInfo.FullName + " does not exist";
_camera.Start(0);
return;
}
string filename = _config.AppSettings.Settings[Constants.Settings.IMAGE_NUMBER].Value + ".jpg";
this.pictureBox1.Image.Save("images/" + filename);
FileInfo fInfo = new FileInfo("images/" + filename);
if(fInfo.Exists)
{
this.toolStripStatusLabel1.Text = "Image " + filename + " saved successfully.";
int num = Convert.ToInt32(_config.AppSettings.Settings[Constants.Settings.IMAGE_NUMBER].Value);
num++;
_config.AppSettings.Settings[Constants.Settings.IMAGE_NUMBER].Value = num.ToString();
_config.Save();
}
else
this.toolStripStatusLabel1.Text = "Error: image not saved.";
_camera.Start(0);
}
/// <summary>
/// Called when exit is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void ExitToolStripMenuItem1Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// called when view-> log is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void LogToolStripMenuItemClick(object sender, EventArgs e)
{
ViewLogForm frm = new ViewLogForm();
frm.ShowDialog(this);
}
/// <summary>
/// Called when view->snapshots is called
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void SnapshotsToolStripMenuItemClick(object sender, EventArgs e)
{
ViewSnapshotsForm frm = new ViewSnapshotsForm();
frm.ShowDialog(this);
}
/// <summary>
/// Called when system tray icon Right Click -> Snap Picture
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void SnapPictureToolStripMenuItem1Click(object sender, EventArgs e)
{
_camera.Start(0); //the camera is stopped in minimized mode, we restart it
DirectoryInfo dInfo = new DirectoryInfo("images");
if(!dInfo.Exists)
dInfo.Create();
dInfo = new DirectoryInfo("images");
if(!dInfo.Exists)
{
MessageBox.Show("Error while saving: " + dInfo.FullName + " could not be found or created.","Error", MessageBoxButtons.OK,MessageBoxIcon.Error);
_camera.Stop();
return;
}
string filename = _config.AppSettings.Settings[Constants.Settings.IMAGE_NUMBER].Value + ".jpg";
this.pictureBox1.Image.Save("images/" + filename);
FileInfo fInfo = new FileInfo("images/" + filename);
if(fInfo.Exists)
{
this.toolStripStatusLabel1.Text = "Image " + filename + " saved successfully.";
int num = Convert.ToInt32(_config.AppSettings.Settings[Constants.Settings.IMAGE_NUMBER].Value);
num++;
_config.AppSettings.Settings[Constants.Settings.IMAGE_NUMBER].Value = num.ToString();
_config.Save();
}
else
MessageBox.Show("Due to an unexpected error, " + fInfo.Name + " could not be saved","Error", MessageBoxButtons.OK,MessageBoxIcon.Error);
_camera.Stop();
}
/// <summary>
/// Called when Tools -> Discover Commands
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void DiscoverCommandsToolStripMenuItemClick(object sender, EventArgs e)
{
DiscoveryForm frm = new DiscoveryForm(_manager);
frm.Show(this);
}
/// <summary>
/// Disconnects all launchers
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void DisconnectToolStripMenuItemClick(object sender, EventArgs e)
{
_manager.Disconnect();
_manager.Launchers.Clear();
this.updateLaunchersMenu();
}
/// <summary>
/// Disconnects and reconnects the launchers
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void ReconnectToolStripMenuItemClick(object sender, EventArgs e)
{
_manager.Disconnect();
_manager.Launchers.Clear();
//_manager.Connect();
this.updateLaunchersMenu();
}
#endregion
#region Keyboard Handling
/// <summary>
/// This is called when a key is released, and toggles
/// its respective boolean value for whether the key is currently
/// being held down or not
/// </summary>
/// <param name="e"></param>
protected override void OnKeyUp(KeyEventArgs e)
{
switch(e.KeyData)
{
case Keys.Left:
Constants.KeysDown.LEFT = false;
checkKeys();
break;
case Keys.Right:
Constants.KeysDown.RIGHT = false;
checkKeys();
break;
case Keys.Down:
Constants.KeysDown.DOWN = false;
checkKeys();
break;
case Keys.Up:
Constants.KeysDown.UP = false;
checkKeys();
break;
}
}
/// <summary>
/// This is called when a key is pressed down,
/// and we toggle an individual boolean value for each important
/// key. We handle it this way because it is the easiest way to handle
/// simultaneous key movements independently of one another
/// </summary>
/// <param name="msg"></param>
/// <param name="keyData"></param>
/// <returns></returns>
protected bool OnKeyDown(ref Message msg, Keys keyData)
{
switch(keyData)
{
case Keys.Left:
Constants.KeysDown.LEFT = true;
break;
case Keys.Right:
Constants.KeysDown.RIGHT = true;
break;
case Keys.Down:
Constants.KeysDown.DOWN = true;
break;
case Keys.Up:
Constants.KeysDown.UP = true;
break;
case Keys.Enter:
foreach(USBLauncher l in _manager.Launchers)
l.Fire();
this.checkCandidShots();
break;
case Keys.P:
foreach(DreamCheekyLauncher r in _manager.Launchers)
r.Prime();
break;
}
this.checkKeys();
return true;
}
/// <summary>
/// When a key is pressed or released, this is called to recheck what
/// is currently being held down, and sets a command that should be
/// called that depends on what is held down, then calls that command.
/// </summary>
void checkKeys()
{
bool left, right, up, down;
left = Constants.KeysDown.LEFT;
right = Constants.KeysDown.RIGHT;
up = Constants.KeysDown.UP;
down = Constants.KeysDown.DOWN;
if(left)
{
if(up)
{
foreach(USBLauncher l in _manager.Launchers) l.MoveUpLeft();
return;
}
else if(down)
{
foreach(USBLauncher l in _manager.Launchers) l.MoveDownLeft();
return;
}
else
{
foreach(USBLauncher l in _manager.Launchers) l.MoveLeft();
return;
}
}
else if(right)
{
if(up)
{
foreach(USBLauncher l in _manager.Launchers) l.MoveUpRight();
return;
}
else if(down)
{
foreach(USBLauncher l in _manager.Launchers) l.MoveDownRight();
return;
}
else
{
foreach(USBLauncher l in _manager.Launchers) l.MoveRight();
return;
}
}
else if(up)
{
foreach(USBLauncher l in _manager.Launchers) l.MoveUp();
return;
}
else if(down)
{
foreach(USBLauncher l in _manager.Launchers) l.MoveDown();
return;
}
if(!left && !right && !up && !down)
foreach(USBLauncher l in _manager.Launchers)
l.Stop();
}
/// <summary>
/// This is where all key commands start for this particular form,
/// if it isn't handled here, then KeyUp or KeyDown functions
/// handle the key.
/// </summary>
/// <param name="msg"></param>
/// <param name="keyData"></param>
/// <returns></returns>
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if(keyData == Keys.Tab)
{
return base.ProcessCmdKey(ref msg, keyData);
}
else if(keyData == Keys.F10)
{
if(this.snapPictureToolStripMenuItem.Enabled)
this.snapPictureToolStripMenuItem_Click(this, null);
return true;
}
else
{
return OnKeyDown(ref msg, keyData);
}
}
#endregion
#region Properties
/// <summary>
/// Allows the other forms to access the configuration settings for the application
/// quickly and easily
/// </summary>
public Configuration AppSettings
{
get { return _config; }
}
#endregion
#region Utility Functions
/// <summary>
/// Resets the visibility of the controls buttons to all visible
/// </summary>
private void reset()
{
this.btnUp.Visible = true;
this.btnRight.Visible = true;
this.btnLeft.Visible = true;
this.btnDown.Visible = true;
this.btnDownLeft.Visible = true;
this.btnDownRight.Visible = true;
this.btnUpLeft.Visible = true;
this.btnUpRight.Visible = true;
}
/// <summary>
/// Called when the application starts, this checks to see if the setting
/// file exists, and if the individual settings have been intialized to their
/// appropriate initial value, and if not, creates them.
/// If Clear is true, it clears the setting back to default anyway
/// </summary>
public void CheckSettings()
{
if(_config.AppSettings.Settings[Constants.Settings.PRIME_AIRTANK] == null)
_config.AppSettings.Settings.Add(Constants.Settings.PRIME_AIRTANK,Constants.Defaults.PRIME_AIRTANK);
if(_config.AppSettings.Settings[Constants.Settings.RESET_LAUNCHER_ON_START] == null)
_config.AppSettings.Settings.Add(Constants.Settings.RESET_LAUNCHER_ON_START,Constants.Defaults.RESET_LAUNCHER_ON_START);
if(_config.AppSettings.Settings[Constants.Settings.WEBCAM_ON_START] == null)
_config.AppSettings.Settings.Add(Constants.Settings.WEBCAM_ON_START,Constants.Defaults.WEBCAM_ON_START);
if(_config.AppSettings.Settings[Constants.Settings.WEBCAM_REFRESH_RATE] == null)
_config.AppSettings.Settings.Add(Constants.Settings.WEBCAM_REFRESH_RATE,Constants.Defaults.WEBCAM_REFRESH_RATE);
if(_config.AppSettings.Settings[Constants.Settings.IMAGE_NUMBER] == null)
_config.AppSettings.Settings.Add(Constants.Settings.IMAGE_NUMBER,Constants.Defaults.IMAGE_NUMBER);
if(_config.AppSettings.Settings[Constants.Settings.CAMERA_HEIGHT] == null)
_config.AppSettings.Settings.Add(Constants.Settings.CAMERA_HEIGHT,Constants.Defaults.CAMERA_HEIGHT);
if(_config.AppSettings.Settings[Constants.Settings.CAMERA_WIDTH] == null)
_config.AppSettings.Settings.Add(Constants.Settings.CAMERA_WIDTH,Constants.Defaults.CAMERA_WIDTH);
if(_config.AppSettings.Settings[Constants.Settings.SLOW] == null)
_config.AppSettings.Settings.Add(Constants.Settings.SLOW,Constants.Defaults.SLOW);
if(_config.AppSettings.Settings[Constants.Settings.FIRE_WHILE_MOVING] == null)
_config.AppSettings.Settings.Add(Constants.Settings.FIRE_WHILE_MOVING,Constants.Defaults.FIRE_WHILE_MOVING);
if(_config.AppSettings.Settings[Constants.Settings.CANDID_SHOTS] == null)
_config.AppSettings.Settings.Add(Constants.Settings.CANDID_SHOTS,Constants.Defaults.CANDID_SHOTS);
if(_config.AppSettings.Settings[Constants.Settings.CANDID_SHOTS_TIMING] == null)
_config.AppSettings.Settings.Add(Constants.Settings.CANDID_SHOTS_TIMING,Constants.Defaults.CANDID_SHOTS_TIMING);
}
/// <summary>
/// This iterates over all drop down items in the Launchers menu,
/// and adds an entry for each usb launcher currently connected.
/// </summary>
private void updateLaunchersMenu()
{
int count = 1;
ToolStripItem item1 = this.launchersToolStripMenuItem.DropDownItems[0];
ToolStripItem item2 = this.launchersToolStripMenuItem.DropDownItems[1];
ToolStripItem item3 = this.launchersToolStripMenuItem.DropDownItems[2];
this.launchersToolStripMenuItem.DropDownItems.Clear();
this.launchersToolStripMenuItem.DropDownItems.Add(item1);
this.launchersToolStripMenuItem.DropDownItems.Add(item2);
this.launchersToolStripMenuItem.DropDownItems.Add(item3);
foreach(USBLauncher l in _manager.Launchers)
{
if (l is DreamCheekyLauncher)
{
ToolStripMenuItem item = new ToolStripMenuItem("Dream Cheeky Launcher " + count, null, null, "dreamCheekyLauncherToolStripMenuItem" + count);
item.CheckOnClick = true;
item.Checked = true;
item.CheckedChanged += new EventHandler(launcherToolStripMenuItem_Checked);
this.launchersToolStripMenuItem.DropDownItems.Add(item);
count++;
}
else if (l is RocketBabyLauncher)
{
ToolStripMenuItem item = new ToolStripMenuItem("Rocket Baby Launcher " + count, null, null, "rocketBabyLauncherToolStripMenuItem" + count);
item.CheckOnClick = true;
item.Checked = true;
item.CheckedChanged += new EventHandler(launcherToolStripMenuItem_Checked);
this.launchersToolStripMenuItem.DropDownItems.Add(item);
count++;
}
}
}
private bool checkCandidShots()
{
if(this.pictureBox1.Image == null || this.webcamToolStripMenuItem.Checked == false)
return false;
if(_candidShotThread != null && _candidShotThread.ThreadState == ThreadState.Running)
return false;
DirectoryInfo dInfo = new DirectoryInfo("images");
if(!dInfo.Exists)
return false;
_candidShotThread = new Thread(new ThreadStart(candidShotHelper));
//_candidShotThread.Priority = ThreadPriority.Lowest;
_candidShotThread.Start();
return true;
}
private void candidShotHelper()
{
int times = Convert.ToInt32(_config.AppSettings.Settings[Constants.Settings.CANDID_SHOTS].Value);
int spacing = Convert.ToInt32(_config.AppSettings.Settings[Constants.Settings.CANDID_SHOTS_TIMING].Value);
List<Image> images = new List<Image>();
for(int i = 0; i < times; i++)
{
images.Add(this.pictureBox1.Image);
Thread.Sleep(spacing);
}
if(images.Count == 0)
return;
int count = Convert.ToInt32(_config.AppSettings.Settings[Constants.Settings.IMAGE_NUMBER].Value);
//we need to wait at least 5 seconds so that we don't interfer with the firing or priming timing
this.AddText("Waiting 5 seconds for firing to finish.");
Application.DoEvents();
Thread.Sleep(5000);
foreach(Image img in images)
{
StringBuilder filename = new StringBuilder("images/");
filename.Append(count.ToString());
filename.Append(".jpg");
img.Save(filename.ToString());
count++;
}
_config.AppSettings.Settings[Constants.Settings.IMAGE_NUMBER].Value = count.ToString();
_config.Save(System.Configuration.ConfigurationSaveMode.Modified);
this.AddText(images.Count.ToString() + " candid shots taken.");
}
private void timer_Tick(object sender, System.EventArgs e)
{
//if(_manager.Launchers.Count < 1 || _manager.Launchers[0].FiringStatus == USBLauncher.Status.DoneFiring)
// return;
//if(_manager.Launchers[0].FiringStatus == USBLauncher.Status.DonePriming)
// this.toolStripStatusLabel2.Text = "Primed";
}
#endregion
[System.ComponentModel.EditorBrowsableAttribute()]
protected override void WndProc(ref Message m)
{
_manager.PassMessages(ref m);
base.WndProc(ref m);
}
[System.ComponentModel.EditorBrowsableAttribute()]
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
_manager.PassHandle(Handle);
}
private void DreamCheekyArrived(object sender,System.EventArgs e)
{
this.AddText("Dream Cheeky Connected");
}
private void DreamCheekyRemoved(object sender, System.EventArgs e)
{
this.AddText("Dream Cheeky Removed");
}
private void RocketBabyArrived(object sender, System.EventArgs e)
{
this.AddText("Rocket Baby Connected");
}
private void RocketBabyRemoved(object sender, System.EventArgs e)
{
this.AddText("Rocket Baby Removed");
}
private void AddText(string text)
{
this.txtLog.Text = this.txtLog.Text + text + "\r\n\r\n";
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the GuardiaRegistrosPractica class.
/// </summary>
[Serializable]
public partial class GuardiaRegistrosPracticaCollection : ActiveList<GuardiaRegistrosPractica, GuardiaRegistrosPracticaCollection>
{
public GuardiaRegistrosPracticaCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>GuardiaRegistrosPracticaCollection</returns>
public GuardiaRegistrosPracticaCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
GuardiaRegistrosPractica o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Guardia_Registros_Practicas table.
/// </summary>
[Serializable]
public partial class GuardiaRegistrosPractica : ActiveRecord<GuardiaRegistrosPractica>, IActiveRecord
{
#region .ctors and Default Settings
public GuardiaRegistrosPractica()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public GuardiaRegistrosPractica(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public GuardiaRegistrosPractica(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public GuardiaRegistrosPractica(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Guardia_Registros_Practicas", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "id";
colvarId.DataType = DbType.Int32;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = true;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = true;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
colvarId.DefaultSetting = @"";
colvarId.ForeignKeyTableName = "";
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarIdRegistroGuardia = new TableSchema.TableColumn(schema);
colvarIdRegistroGuardia.ColumnName = "idRegistroGuardia";
colvarIdRegistroGuardia.DataType = DbType.Int32;
colvarIdRegistroGuardia.MaxLength = 0;
colvarIdRegistroGuardia.AutoIncrement = false;
colvarIdRegistroGuardia.IsNullable = false;
colvarIdRegistroGuardia.IsPrimaryKey = false;
colvarIdRegistroGuardia.IsForeignKey = false;
colvarIdRegistroGuardia.IsReadOnly = false;
colvarIdRegistroGuardia.DefaultSetting = @"";
colvarIdRegistroGuardia.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdRegistroGuardia);
TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema);
colvarIdEfector.ColumnName = "idEfector";
colvarIdEfector.DataType = DbType.Int32;
colvarIdEfector.MaxLength = 0;
colvarIdEfector.AutoIncrement = false;
colvarIdEfector.IsNullable = true;
colvarIdEfector.IsPrimaryKey = false;
colvarIdEfector.IsForeignKey = false;
colvarIdEfector.IsReadOnly = false;
colvarIdEfector.DefaultSetting = @"";
colvarIdEfector.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEfector);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "fecha";
colvarFecha.DataType = DbType.DateTime;
colvarFecha.MaxLength = 0;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = false;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
colvarFecha.DefaultSetting = @"";
colvarFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarIdTipoPractica = new TableSchema.TableColumn(schema);
colvarIdTipoPractica.ColumnName = "idTipoPractica";
colvarIdTipoPractica.DataType = DbType.Int32;
colvarIdTipoPractica.MaxLength = 0;
colvarIdTipoPractica.AutoIncrement = false;
colvarIdTipoPractica.IsNullable = false;
colvarIdTipoPractica.IsPrimaryKey = false;
colvarIdTipoPractica.IsForeignKey = false;
colvarIdTipoPractica.IsReadOnly = false;
colvarIdTipoPractica.DefaultSetting = @"";
colvarIdTipoPractica.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdTipoPractica);
TableSchema.TableColumn colvarIdPrioridad = new TableSchema.TableColumn(schema);
colvarIdPrioridad.ColumnName = "idPrioridad";
colvarIdPrioridad.DataType = DbType.Int32;
colvarIdPrioridad.MaxLength = 0;
colvarIdPrioridad.AutoIncrement = false;
colvarIdPrioridad.IsNullable = false;
colvarIdPrioridad.IsPrimaryKey = false;
colvarIdPrioridad.IsForeignKey = false;
colvarIdPrioridad.IsReadOnly = false;
colvarIdPrioridad.DefaultSetting = @"";
colvarIdPrioridad.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPrioridad);
TableSchema.TableColumn colvarIdEstado = new TableSchema.TableColumn(schema);
colvarIdEstado.ColumnName = "idEstado";
colvarIdEstado.DataType = DbType.Int32;
colvarIdEstado.MaxLength = 0;
colvarIdEstado.AutoIncrement = false;
colvarIdEstado.IsNullable = false;
colvarIdEstado.IsPrimaryKey = false;
colvarIdEstado.IsForeignKey = false;
colvarIdEstado.IsReadOnly = false;
colvarIdEstado.DefaultSetting = @"";
colvarIdEstado.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEstado);
TableSchema.TableColumn colvarObservaciones = new TableSchema.TableColumn(schema);
colvarObservaciones.ColumnName = "observaciones";
colvarObservaciones.DataType = DbType.AnsiString;
colvarObservaciones.MaxLength = -1;
colvarObservaciones.AutoIncrement = false;
colvarObservaciones.IsNullable = true;
colvarObservaciones.IsPrimaryKey = false;
colvarObservaciones.IsForeignKey = false;
colvarObservaciones.IsReadOnly = false;
colvarObservaciones.DefaultSetting = @"";
colvarObservaciones.ForeignKeyTableName = "";
schema.Columns.Add(colvarObservaciones);
TableSchema.TableColumn colvarUrl = new TableSchema.TableColumn(schema);
colvarUrl.ColumnName = "url";
colvarUrl.DataType = DbType.AnsiString;
colvarUrl.MaxLength = -1;
colvarUrl.AutoIncrement = false;
colvarUrl.IsNullable = true;
colvarUrl.IsPrimaryKey = false;
colvarUrl.IsForeignKey = false;
colvarUrl.IsReadOnly = false;
colvarUrl.DefaultSetting = @"";
colvarUrl.ForeignKeyTableName = "";
schema.Columns.Add(colvarUrl);
TableSchema.TableColumn colvarAuditUser = new TableSchema.TableColumn(schema);
colvarAuditUser.ColumnName = "auditUser";
colvarAuditUser.DataType = DbType.Int32;
colvarAuditUser.MaxLength = 0;
colvarAuditUser.AutoIncrement = false;
colvarAuditUser.IsNullable = true;
colvarAuditUser.IsPrimaryKey = false;
colvarAuditUser.IsForeignKey = false;
colvarAuditUser.IsReadOnly = false;
colvarAuditUser.DefaultSetting = @"";
colvarAuditUser.ForeignKeyTableName = "";
schema.Columns.Add(colvarAuditUser);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Guardia_Registros_Practicas",schema);
}
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public int Id
{
get { return GetColumnValue<int>(Columns.Id); }
set { SetColumnValue(Columns.Id, value); }
}
[XmlAttribute("IdRegistroGuardia")]
[Bindable(true)]
public int IdRegistroGuardia
{
get { return GetColumnValue<int>(Columns.IdRegistroGuardia); }
set { SetColumnValue(Columns.IdRegistroGuardia, value); }
}
[XmlAttribute("IdEfector")]
[Bindable(true)]
public int? IdEfector
{
get { return GetColumnValue<int?>(Columns.IdEfector); }
set { SetColumnValue(Columns.IdEfector, value); }
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public DateTime Fecha
{
get { return GetColumnValue<DateTime>(Columns.Fecha); }
set { SetColumnValue(Columns.Fecha, value); }
}
[XmlAttribute("IdTipoPractica")]
[Bindable(true)]
public int IdTipoPractica
{
get { return GetColumnValue<int>(Columns.IdTipoPractica); }
set { SetColumnValue(Columns.IdTipoPractica, value); }
}
[XmlAttribute("IdPrioridad")]
[Bindable(true)]
public int IdPrioridad
{
get { return GetColumnValue<int>(Columns.IdPrioridad); }
set { SetColumnValue(Columns.IdPrioridad, value); }
}
[XmlAttribute("IdEstado")]
[Bindable(true)]
public int IdEstado
{
get { return GetColumnValue<int>(Columns.IdEstado); }
set { SetColumnValue(Columns.IdEstado, value); }
}
[XmlAttribute("Observaciones")]
[Bindable(true)]
public string Observaciones
{
get { return GetColumnValue<string>(Columns.Observaciones); }
set { SetColumnValue(Columns.Observaciones, value); }
}
[XmlAttribute("Url")]
[Bindable(true)]
public string Url
{
get { return GetColumnValue<string>(Columns.Url); }
set { SetColumnValue(Columns.Url, value); }
}
[XmlAttribute("AuditUser")]
[Bindable(true)]
public int? AuditUser
{
get { return GetColumnValue<int?>(Columns.AuditUser); }
set { SetColumnValue(Columns.AuditUser, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdRegistroGuardia,int? varIdEfector,DateTime varFecha,int varIdTipoPractica,int varIdPrioridad,int varIdEstado,string varObservaciones,string varUrl,int? varAuditUser)
{
GuardiaRegistrosPractica item = new GuardiaRegistrosPractica();
item.IdRegistroGuardia = varIdRegistroGuardia;
item.IdEfector = varIdEfector;
item.Fecha = varFecha;
item.IdTipoPractica = varIdTipoPractica;
item.IdPrioridad = varIdPrioridad;
item.IdEstado = varIdEstado;
item.Observaciones = varObservaciones;
item.Url = varUrl;
item.AuditUser = varAuditUser;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varId,int varIdRegistroGuardia,int? varIdEfector,DateTime varFecha,int varIdTipoPractica,int varIdPrioridad,int varIdEstado,string varObservaciones,string varUrl,int? varAuditUser)
{
GuardiaRegistrosPractica item = new GuardiaRegistrosPractica();
item.Id = varId;
item.IdRegistroGuardia = varIdRegistroGuardia;
item.IdEfector = varIdEfector;
item.Fecha = varFecha;
item.IdTipoPractica = varIdTipoPractica;
item.IdPrioridad = varIdPrioridad;
item.IdEstado = varIdEstado;
item.Observaciones = varObservaciones;
item.Url = varUrl;
item.AuditUser = varAuditUser;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdRegistroGuardiaColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdEfectorColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn FechaColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn IdTipoPracticaColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn IdPrioridadColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn IdEstadoColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn ObservacionesColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn UrlColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn AuditUserColumn
{
get { return Schema.Columns[9]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"id";
public static string IdRegistroGuardia = @"idRegistroGuardia";
public static string IdEfector = @"idEfector";
public static string Fecha = @"fecha";
public static string IdTipoPractica = @"idTipoPractica";
public static string IdPrioridad = @"idPrioridad";
public static string IdEstado = @"idEstado";
public static string Observaciones = @"observaciones";
public static string Url = @"url";
public static string AuditUser = @"auditUser";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias PDB;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.DiaSymReader;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
using PDB::Roslyn.Test.MetadataUtilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class Scope
{
internal readonly int StartOffset;
internal readonly int EndOffset;
internal readonly ImmutableArray<string> Locals;
internal Scope(int startOffset, int endOffset, ImmutableArray<string> locals, bool isEndInclusive)
{
this.StartOffset = startOffset;
this.EndOffset = endOffset + (isEndInclusive ? 1 : 0);
this.Locals = locals;
}
internal int Length
{
get { return this.EndOffset - this.StartOffset + 1; }
}
internal bool Contains(int offset)
{
return (offset >= this.StartOffset) && (offset < this.EndOffset);
}
}
internal static class ExpressionCompilerTestHelpers
{
internal static CompileResult CompileAssignment(
this EvaluationContextBase context,
string target,
string expr,
out string error,
CompilationTestData testData = null,
DiagnosticFormatter formatter = null)
{
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileAssignment(
target,
expr,
ImmutableArray<Alias>.Empty,
formatter ?? DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
// This is a crude way to test the language, but it's convenient to share this test helper.
var isCSharp = context.GetType().Namespace.IndexOf("csharp", StringComparison.OrdinalIgnoreCase) >= 0;
var expectedFlags = error != null
? DkmClrCompilationResultFlags.None
: isCSharp
? DkmClrCompilationResultFlags.PotentialSideEffect
: DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult;
Assert.Equal(expectedFlags, resultProperties.Flags);
Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category);
Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType);
Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType);
Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags);
return result;
}
internal static CompileResult CompileAssignment(
this EvaluationContextBase context,
string target,
string expr,
ImmutableArray<Alias> aliases,
DiagnosticFormatter formatter,
out ResultProperties resultProperties,
out string error,
out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities,
CultureInfo preferredUICulture,
CompilationTestData testData)
{
var diagnostics = DiagnosticBag.GetInstance();
var result = context.CompileAssignment(target, expr, aliases, diagnostics, out resultProperties, testData);
if (diagnostics.HasAnyErrors())
{
bool useReferencedModulesOnly;
error = context.GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out useReferencedModulesOnly, out missingAssemblyIdentities);
}
else
{
error = null;
missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty;
}
diagnostics.Free();
return result;
}
internal static ReadOnlyCollection<byte> CompileGetLocals(
this EvaluationContextBase context,
ArrayBuilder<LocalAndMethod> locals,
bool argumentsOnly,
out string typeName,
CompilationTestData testData,
DiagnosticDescription[] expectedDiagnostics = null)
{
var diagnostics = DiagnosticBag.GetInstance();
var result = context.CompileGetLocals(
locals,
argumentsOnly,
ImmutableArray<Alias>.Empty,
diagnostics,
out typeName,
testData);
diagnostics.Verify(expectedDiagnostics ?? DiagnosticDescription.None);
diagnostics.Free();
return result;
}
internal static CompileResult CompileExpression(
this EvaluationContextBase context,
string expr,
out string error,
CompilationTestData testData = null,
DiagnosticFormatter formatter = null)
{
ResultProperties resultProperties;
return CompileExpression(context, expr, out resultProperties, out error, testData, formatter);
}
internal static CompileResult CompileExpression(
this EvaluationContextBase context,
string expr,
out ResultProperties resultProperties,
out string error,
CompilationTestData testData = null,
DiagnosticFormatter formatter = null)
{
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
expr,
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray<Alias>.Empty,
formatter ?? DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
return result;
}
static internal CompileResult CompileExpression(
this EvaluationContextBase evaluationContext,
string expr,
DkmEvaluationFlags compilationFlags,
ImmutableArray<Alias> aliases,
out string error,
CompilationTestData testData = null,
DiagnosticFormatter formatter = null)
{
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = evaluationContext.CompileExpression(
expr,
compilationFlags,
aliases,
formatter ?? DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
return result;
}
/// <summary>
/// Compile C# expression and emit assembly with evaluation method.
/// </summary>
/// <returns>
/// Result containing generated assembly, type and method names, and any format specifiers.
/// </returns>
static internal CompileResult CompileExpression(
this EvaluationContextBase evaluationContext,
string expr,
DkmEvaluationFlags compilationFlags,
ImmutableArray<Alias> aliases,
DiagnosticFormatter formatter,
out ResultProperties resultProperties,
out string error,
out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities,
CultureInfo preferredUICulture,
CompilationTestData testData)
{
var diagnostics = DiagnosticBag.GetInstance();
var result = evaluationContext.CompileExpression(expr, compilationFlags, aliases, diagnostics, out resultProperties, testData);
if (diagnostics.HasAnyErrors())
{
bool useReferencedModulesOnly;
error = evaluationContext.GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out useReferencedModulesOnly, out missingAssemblyIdentities);
}
else
{
error = null;
missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty;
}
diagnostics.Free();
return result;
}
internal static CompileResult CompileExpressionWithRetry(
ImmutableArray<MetadataBlock> metadataBlocks,
EvaluationContextBase context,
ExpressionCompiler.CompileDelegate<CompileResult> compile,
DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
out string errorMessage)
{
return ExpressionCompiler.CompileWithRetry(
metadataBlocks,
DiagnosticFormatter.Instance,
(blocks, useReferencedModulesOnly) => context,
compile,
getMetaDataBytesPtr,
out errorMessage);
}
internal static CompileResult CompileExpressionWithRetry(
ImmutableArray<MetadataBlock> metadataBlocks,
string expr,
ExpressionCompiler.CreateContextDelegate createContext,
DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr,
out string errorMessage,
out CompilationTestData testData)
{
var r = ExpressionCompiler.CompileWithRetry(
metadataBlocks,
DiagnosticFormatter.Instance,
createContext,
(context, diagnostics) =>
{
var td = new CompilationTestData();
ResultProperties resultProperties;
var compileResult = context.CompileExpression(
expr,
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray<Alias>.Empty,
diagnostics,
out resultProperties,
td);
return new CompileExpressionResult(compileResult, td);
},
getMetaDataBytesPtr,
out errorMessage);
testData = r.TestData;
return r.CompileResult;
}
private struct CompileExpressionResult
{
internal readonly CompileResult CompileResult;
internal readonly CompilationTestData TestData;
internal CompileExpressionResult(CompileResult compileResult, CompilationTestData testData)
{
this.CompileResult = compileResult;
this.TestData = testData;
}
}
internal static TypeDefinition GetTypeDef(this MetadataReader reader, string typeName)
{
return reader.TypeDefinitions.Select(reader.GetTypeDefinition).First(t => reader.StringComparer.Equals(t.Name, typeName));
}
internal static MethodDefinition GetMethodDef(this MetadataReader reader, TypeDefinition typeDef, string methodName)
{
return typeDef.GetMethods().Select(reader.GetMethodDefinition).First(m => reader.StringComparer.Equals(m.Name, methodName));
}
internal static MethodDefinitionHandle GetMethodDefHandle(this MetadataReader reader, TypeDefinition typeDef, string methodName)
{
return typeDef.GetMethods().First(h => reader.StringComparer.Equals(reader.GetMethodDefinition(h).Name, methodName));
}
internal static void CheckTypeParameters(this MetadataReader reader, GenericParameterHandleCollection genericParameters, params string[] expectedNames)
{
var actualNames = genericParameters.Select(reader.GetGenericParameter).Select(tp => reader.GetString(tp.Name)).ToArray();
Assert.True(expectedNames.SequenceEqual(actualNames));
}
internal static AssemblyName GetAssemblyName(this byte[] exeBytes)
{
using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes)))
{
var metadataReader = reader.GetMetadataReader();
var def = metadataReader.GetAssemblyDefinition();
var name = metadataReader.GetString(def.Name);
return new AssemblyName() { Name = name, Version = def.Version };
}
}
internal static Guid GetModuleVersionId(this byte[] exeBytes)
{
using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes)))
{
return reader.GetMetadataReader().GetModuleVersionId();
}
}
internal static ImmutableArray<string> GetLocalNames(this ISymUnmanagedReader symReader, int methodToken, int methodVersion = 1)
{
var method = symReader.GetMethodByVersion(methodToken, methodVersion);
if (method == null)
{
return ImmutableArray<string>.Empty;
}
var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
method.GetAllScopes(scopes);
var names = ArrayBuilder<string>.GetInstance();
foreach (var scope in scopes)
{
var locals = scope.GetLocals();
foreach (var local in locals)
{
var name = local.GetName();
int slot;
local.GetAddressField1(out slot);
while (names.Count <= slot)
{
names.Add(null);
}
names[slot] = name;
}
}
scopes.Free();
return names.ToImmutableAndFree();
}
internal static void VerifyIL(
this ImmutableArray<byte> assembly,
string qualifiedName,
string expectedIL,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
var parts = qualifiedName.Split('.');
if (parts.Length != 2)
{
throw new NotImplementedException();
}
using (var module = new PEModule(new PEReader(assembly), metadataOpt: IntPtr.Zero, metadataSizeOpt: 0))
{
var reader = module.MetadataReader;
var typeDef = reader.GetTypeDef(parts[0]);
var methodName = parts[1];
var methodHandle = reader.GetMethodDefHandle(typeDef, methodName);
var methodBody = module.GetMethodBodyOrThrow(methodHandle);
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
var writer = new StringWriter(pooled.Builder);
var visualizer = new MetadataVisualizer(reader, writer);
visualizer.VisualizeMethodBody(methodBody, methodHandle, emitHeader: false);
var actualIL = pooled.ToStringAndFree();
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine);
}
}
internal static bool EmitAndGetReferences(
this Compilation compilation,
out byte[] exeBytes,
out byte[] pdbBytes,
out ImmutableArray<MetadataReference> references)
{
using (var pdbStream = new MemoryStream())
{
using (var exeStream = new MemoryStream())
{
var result = compilation.Emit(
peStream: exeStream,
pdbStream: pdbStream,
xmlDocumentationStream: null,
win32Resources: null,
manifestResources: null,
options: EmitOptions.Default,
testData: null,
getHostDiagnostics: null,
cancellationToken: default(CancellationToken));
if (!result.Success)
{
result.Diagnostics.Verify();
exeBytes = null;
pdbBytes = null;
references = default(ImmutableArray<MetadataReference>);
return false;
}
exeBytes = exeStream.ToArray();
pdbBytes = pdbStream.ToArray();
}
}
// Determine the set of references that were actually used
// and ignore any references that were dropped in emit.
HashSet<string> referenceNames;
using (var metadata = ModuleMetadata.CreateFromImage(exeBytes))
{
var reader = metadata.MetadataReader;
referenceNames = new HashSet<string>(reader.AssemblyReferences.Select(h => GetAssemblyReferenceName(reader, h)));
}
references = ImmutableArray.CreateRange(compilation.References.Where(r => IsReferenced(r, referenceNames)));
return true;
}
internal static ImmutableArray<Scope> GetScopes(this ISymUnmanagedReader symReader, int methodToken, int methodVersion, bool isEndInclusive)
{
var method = symReader.GetMethodByVersion(methodToken, methodVersion);
if (method == null)
{
return ImmutableArray<Scope>.Empty;
}
var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
method.GetAllScopes(scopes);
var result = scopes.SelectAsArray(s => new Scope(s.GetStartOffset(), s.GetEndOffset(), s.GetLocals().SelectAsArray(l => l.GetName()), isEndInclusive));
scopes.Free();
return result;
}
internal static Scope GetInnermostScope(this ImmutableArray<Scope> scopes, int offset)
{
Scope result = null;
foreach (var scope in scopes)
{
if (scope.Contains(offset))
{
if ((result == null) || (result.Length > scope.Length))
{
result = scope;
}
}
}
return result;
}
private static string GetAssemblyReferenceName(MetadataReader reader, AssemblyReferenceHandle handle)
{
var reference = reader.GetAssemblyReference(handle);
return reader.GetString(reference.Name);
}
private static bool IsReferenced(MetadataReference reference, HashSet<string> referenceNames)
{
var assemblyMetadata = ((PortableExecutableReference)reference).GetMetadata() as AssemblyMetadata;
if (assemblyMetadata == null)
{
// Netmodule. Assume it is referenced.
return true;
}
var name = assemblyMetadata.GetAssembly().Identity.Name;
return referenceNames.Contains(name);
}
/// <summary>
/// Verify the set of module metadata blocks
/// contains all blocks referenced by the set.
/// </summary>
internal static void VerifyAllModules(this ImmutableArray<ModuleInstance> modules)
{
var blocks = modules.SelectAsArray(m => m.MetadataBlock).SelectAsArray(b => ModuleMetadata.CreateFromMetadata(b.Pointer, b.Size));
var names = new HashSet<string>(blocks.Select(b => b.Name));
foreach (var block in blocks)
{
foreach (var name in block.GetModuleNames())
{
Assert.True(names.Contains(name));
}
}
}
internal static ModuleMetadata GetModuleMetadata(this MetadataReference reference)
{
var metadata = ((MetadataImageReference)reference).GetMetadata();
var assemblyMetadata = metadata as AssemblyMetadata;
Assert.True((assemblyMetadata == null) || (assemblyMetadata.GetModules().Length == 1));
return (assemblyMetadata == null) ? (ModuleMetadata)metadata : assemblyMetadata.GetModules()[0];
}
internal static ModuleInstance ToModuleInstance(
this MetadataReference reference,
byte[] fullImage,
object symReader,
bool includeLocalSignatures = true)
{
var moduleMetadata = reference.GetModuleMetadata();
var moduleId = moduleMetadata.Module.GetModuleVersionIdOrThrow();
// The Expression Compiler expects metadata only, no headers or IL.
var metadataBytes = moduleMetadata.Module.PEReaderOpt.GetMetadata().GetContent().ToArray();
return new ModuleInstance(
reference,
moduleMetadata,
moduleId,
fullImage,
metadataBytes,
symReader,
includeLocalSignatures && (fullImage != null));
}
internal static AssemblyIdentity GetAssemblyIdentity(this MetadataReference reference)
{
var moduleMetadata = reference.GetModuleMetadata();
var reader = moduleMetadata.MetadataReader;
return reader.ReadAssemblyIdentityOrThrow();
}
internal static Guid GetModuleVersionId(this MetadataReference reference)
{
var moduleMetadata = reference.GetModuleMetadata();
var reader = moduleMetadata.MetadataReader;
return reader.GetModuleVersionIdOrThrow();
}
internal static void VerifyLocal<TMethodSymbol>(
this CompilationTestData testData,
string typeName,
LocalAndMethod localAndMethod,
string expectedMethodName,
string expectedLocalName,
string expectedLocalDisplayName,
DkmClrCompilationResultFlags expectedFlags,
Action<TMethodSymbol> verifyTypeParameters,
string expectedILOpt,
bool expectedGeneric,
string expectedValueSourcePath,
int expectedValueSourceLine)
where TMethodSymbol : IMethodSymbol
{
Assert.Equal(expectedLocalName, localAndMethod.LocalName);
Assert.Equal(expectedLocalDisplayName, localAndMethod.LocalDisplayName);
Assert.True(expectedMethodName.StartsWith(localAndMethod.MethodName, StringComparison.Ordinal), expectedMethodName + " does not start with " + localAndMethod.MethodName); // Expected name may include type arguments and parameters.
Assert.Equal(expectedFlags, localAndMethod.Flags);
var methodData = testData.GetMethodData(typeName + "." + expectedMethodName);
verifyTypeParameters((TMethodSymbol)methodData.Method);
if (expectedILOpt != null)
{
string actualIL = methodData.GetMethodIL();
AssertEx.AssertEqualToleratingWhitespaceDifferences(
expectedILOpt,
actualIL,
escapeQuotes: true,
expectedValueSourcePath: expectedValueSourcePath,
expectedValueSourceLine: expectedValueSourceLine);
}
Assert.Equal(((Cci.IMethodDefinition)methodData.Method).CallingConvention, expectedGeneric ? Cci.CallingConvention.Generic : Cci.CallingConvention.Default);
}
internal static ISymUnmanagedReader ConstructSymReaderWithImports(byte[] exeBytes, string methodName, params string[] importStrings)
{
using (var peReader = new PEReader(ImmutableArray.Create(exeBytes)))
{
var metadataReader = peReader.GetMetadataReader();
var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, methodName));
var methodToken = metadataReader.GetToken(methodHandle);
return new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes>
{
{ methodToken, new MethodDebugInfoBytes.Builder(new [] { importStrings }).Build() },
}.ToImmutableDictionary());
}
}
internal static readonly MetadataReference IntrinsicAssemblyReference = GetIntrinsicAssemblyReference();
internal static ImmutableArray<MetadataReference> AddIntrinsicAssembly(this ImmutableArray<MetadataReference> references)
{
var builder = ArrayBuilder<MetadataReference>.GetInstance();
builder.AddRange(references);
builder.Add(IntrinsicAssemblyReference);
return builder.ToImmutableAndFree();
}
private static MetadataReference GetIntrinsicAssemblyReference()
{
var source =
@".assembly extern mscorlib { }
.class public Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods
{
.method public static object GetObjectAtAddress(uint64 address)
{
ldnull
throw
}
.method public static class [mscorlib]System.Exception GetException()
{
ldnull
throw
}
.method public static class [mscorlib]System.Exception GetStowedException()
{
ldnull
throw
}
.method public static object GetReturnValue(int32 index)
{
ldnull
throw
}
.method public static void CreateVariable(class [mscorlib]System.Type 'type', string name, valuetype [mscorlib]System.Guid customTypeInfoPayloadTypeId, uint8[] customTypeInfoPayload)
{
ldnull
throw
}
.method public static object GetObjectByAlias(string name)
{
ldnull
throw
}
.method public static !!T& GetVariableAddress<T>(string name)
{
ldnull
throw
}
}";
return CommonTestBase.CompileIL(source);
}
/// <summary>
/// Return MetadataReferences to the .winmd assemblies
/// for the given namespaces.
/// </summary>
internal static ImmutableArray<MetadataReference> GetRuntimeWinMds(params string[] namespaces)
{
var paths = new HashSet<string>();
foreach (var @namespace in namespaces)
{
foreach (var path in WindowsRuntimeMetadata.ResolveNamespace(@namespace, null))
{
paths.Add(path);
}
}
return ImmutableArray.CreateRange(paths.Select(GetAssembly));
}
private const string Version1_3CLRString = "WindowsRuntime 1.3;CLR v4.0.30319";
private const string Version1_3String = "WindowsRuntime 1.3";
private const string Version1_4String = "WindowsRuntime 1.4";
private static readonly int s_versionStringLength = Version1_3CLRString.Length;
private static readonly byte[] s_version1_3CLRBytes = ToByteArray(Version1_3CLRString, s_versionStringLength);
private static readonly byte[] s_version1_3Bytes = ToByteArray(Version1_3String, s_versionStringLength);
private static readonly byte[] s_version1_4Bytes = ToByteArray(Version1_4String, s_versionStringLength);
private static byte[] ToByteArray(string str, int length)
{
var bytes = new byte[length];
for (int i = 0; i < str.Length; i++)
{
bytes[i] = (byte)str[i];
}
return bytes;
}
internal static byte[] ToVersion1_3(byte[] bytes)
{
return ToVersion(bytes, s_version1_3CLRBytes, s_version1_3Bytes);
}
internal static byte[] ToVersion1_4(byte[] bytes)
{
return ToVersion(bytes, s_version1_3CLRBytes, s_version1_4Bytes);
}
private static byte[] ToVersion(byte[] bytes, byte[] from, byte[] to)
{
int n = bytes.Length;
var copy = new byte[n];
Array.Copy(bytes, copy, n);
int index = IndexOf(copy, from);
Array.Copy(to, 0, copy, index, to.Length);
return copy;
}
private static int IndexOf(byte[] a, byte[] b)
{
int m = b.Length;
int n = a.Length - m;
for (int x = 0; x < n; x++)
{
var matches = true;
for (int y = 0; y < m; y++)
{
if (a[x + y] != b[y])
{
matches = false;
break;
}
}
if (matches)
{
return x;
}
}
return -1;
}
private static MetadataReference GetAssembly(string path)
{
var bytes = File.ReadAllBytes(path);
var metadata = ModuleMetadata.CreateFromImage(bytes);
return metadata.GetReference(filePath: path);
}
internal static int GetOffset(int methodToken, ISymUnmanagedReader symReader, int atLineNumber = -1)
{
int ilOffset;
if (symReader == null)
{
ilOffset = 0;
}
else
{
var symMethod = symReader.GetMethod(methodToken);
if (symMethod == null)
{
ilOffset = 0;
}
else
{
var sequencePoints = symMethod.GetSequencePoints();
ilOffset = atLineNumber < 0
? sequencePoints.Where(sp => sp.StartLine != SequencePointList.HiddenSequencePointLine).Select(sp => sp.Offset).FirstOrDefault()
: sequencePoints.First(sp => sp.StartLine == atLineNumber).Offset;
}
}
Assert.InRange(ilOffset, 0, int.MaxValue);
return ilOffset;
}
internal static string GetMethodOrTypeSignatureParts(string signature, out string[] parameterTypeNames)
{
var parameterListStart = signature.IndexOf('(');
if (parameterListStart < 0)
{
parameterTypeNames = null;
return signature;
}
var parameters = signature.Substring(parameterListStart + 1, signature.Length - parameterListStart - 2);
var methodName = signature.Substring(0, parameterListStart);
parameterTypeNames = (parameters.Length == 0) ?
new string[0] :
parameters.Split(',');
return methodName;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.