context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/language/v1beta1/language_service.proto
// Original file comments:
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace Google.Cloud.Language.V1Beta1 {
/// <summary>
/// Provides text analysis operations such as sentiment analysis and entity
/// recognition.
/// </summary>
public static class LanguageService
{
static readonly string __ServiceName = "google.cloud.language.v1beta1.LanguageService";
static readonly Marshaller<global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentRequest> __Marshaller_AnalyzeSentimentRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentResponse> __Marshaller_AnalyzeSentimentResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesRequest> __Marshaller_AnalyzeEntitiesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesResponse> __Marshaller_AnalyzeEntitiesResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxRequest> __Marshaller_AnalyzeSyntaxRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxResponse> __Marshaller_AnalyzeSyntaxResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1Beta1.AnnotateTextRequest> __Marshaller_AnnotateTextRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1Beta1.AnnotateTextRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1Beta1.AnnotateTextResponse> __Marshaller_AnnotateTextResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1Beta1.AnnotateTextResponse.Parser.ParseFrom);
static readonly Method<global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentRequest, global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentResponse> __Method_AnalyzeSentiment = new Method<global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentRequest, global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentResponse>(
MethodType.Unary,
__ServiceName,
"AnalyzeSentiment",
__Marshaller_AnalyzeSentimentRequest,
__Marshaller_AnalyzeSentimentResponse);
static readonly Method<global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesRequest, global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesResponse> __Method_AnalyzeEntities = new Method<global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesRequest, global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesResponse>(
MethodType.Unary,
__ServiceName,
"AnalyzeEntities",
__Marshaller_AnalyzeEntitiesRequest,
__Marshaller_AnalyzeEntitiesResponse);
static readonly Method<global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxRequest, global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxResponse> __Method_AnalyzeSyntax = new Method<global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxRequest, global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxResponse>(
MethodType.Unary,
__ServiceName,
"AnalyzeSyntax",
__Marshaller_AnalyzeSyntaxRequest,
__Marshaller_AnalyzeSyntaxResponse);
static readonly Method<global::Google.Cloud.Language.V1Beta1.AnnotateTextRequest, global::Google.Cloud.Language.V1Beta1.AnnotateTextResponse> __Method_AnnotateText = new Method<global::Google.Cloud.Language.V1Beta1.AnnotateTextRequest, global::Google.Cloud.Language.V1Beta1.AnnotateTextResponse>(
MethodType.Unary,
__ServiceName,
"AnnotateText",
__Marshaller_AnnotateTextRequest,
__Marshaller_AnnotateTextResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.Language.V1Beta1.LanguageServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of LanguageService</summary>
public abstract class LanguageServiceBase
{
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentResponse> AnalyzeSentiment(global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesResponse> AnalyzeEntities(global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxResponse> AnalyzeSyntax(global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1Beta1.AnnotateTextResponse> AnnotateText(global::Google.Cloud.Language.V1Beta1.AnnotateTextRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for LanguageService</summary>
public class LanguageServiceClient : ClientBase<LanguageServiceClient>
{
/// <summary>Creates a new client for LanguageService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public LanguageServiceClient(Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for LanguageService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public LanguageServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected LanguageServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected LanguageServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
public virtual global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentResponse AnalyzeSentiment(global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeSentiment(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
public virtual global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentResponse AnalyzeSentiment(global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnalyzeSentiment, null, options, request);
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentResponse> AnalyzeSentimentAsync(global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeSentimentAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentResponse> AnalyzeSentimentAsync(global::Google.Cloud.Language.V1Beta1.AnalyzeSentimentRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnalyzeSentiment, null, options, request);
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
public virtual global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesResponse AnalyzeEntities(global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeEntities(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
public virtual global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesResponse AnalyzeEntities(global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnalyzeEntities, null, options, request);
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeEntitiesAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(global::Google.Cloud.Language.V1Beta1.AnalyzeEntitiesRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnalyzeEntities, null, options, request);
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
public virtual global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxResponse AnalyzeSyntax(global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeSyntax(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
public virtual global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxResponse AnalyzeSyntax(global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnalyzeSyntax, null, options, request);
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeSyntaxAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(global::Google.Cloud.Language.V1Beta1.AnalyzeSyntaxRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnalyzeSyntax, null, options, request);
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
public virtual global::Google.Cloud.Language.V1Beta1.AnnotateTextResponse AnnotateText(global::Google.Cloud.Language.V1Beta1.AnnotateTextRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnnotateText(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
public virtual global::Google.Cloud.Language.V1Beta1.AnnotateTextResponse AnnotateText(global::Google.Cloud.Language.V1Beta1.AnnotateTextRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnnotateText, null, options, request);
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1Beta1.AnnotateTextResponse> AnnotateTextAsync(global::Google.Cloud.Language.V1Beta1.AnnotateTextRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnnotateTextAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1Beta1.AnnotateTextResponse> AnnotateTextAsync(global::Google.Cloud.Language.V1Beta1.AnnotateTextRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnnotateText, null, options, request);
}
protected override LanguageServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new LanguageServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(LanguageServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_AnalyzeSentiment, serviceImpl.AnalyzeSentiment)
.AddMethod(__Method_AnalyzeEntities, serviceImpl.AnalyzeEntities)
.AddMethod(__Method_AnalyzeSyntax, serviceImpl.AnalyzeSyntax)
.AddMethod(__Method_AnnotateText, serviceImpl.AnnotateText).Build();
}
}
}
#endregion
| |
using System;
using System.Collections.Generic;
namespace ArgData.Entities
{
/// <summary>
/// Represents a small section of a track.
/// </summary>
public class TrackSection
{
/// <summary>
/// Initializes a new instance of a TrackSection.
/// </summary>
public TrackSection()
{
Commands = new List<TrackSectionCommand>();
}
/// <summary>
/// Gets or sets the length of the section. 1 unit is 16 feet (approx 4.87 meters).
/// </summary>
public byte Length { get; set; }
/// <summary>
/// Gets the list of TrackSectionCommands.
/// </summary>
public List<TrackSectionCommand> Commands { get; }
/// <summary>
/// Gets or sets the curvature of the track. Positive numbers means a right turn, negative numbers means a left turn. Smaller numbers indicate a tighter turn.
/// </summary>
public short Curvature { get; set; }
/// <summary>
/// Gets or sets the height change that occurs in the section.
/// </summary>
public short Height { get; set; }
/// <summary>
/// Gets or sets the width of the left verge.
/// </summary>
public byte LeftVergeWidth { get; set; }
/// <summary>
/// Gets or sets the width of the right verge.
/// </summary>
public byte RightVergeWidth { get; set; }
private TrackSectionFlags InternalFlags { get; set; }
internal short Flags
{
get
{
return (short)InternalFlags;
}
set
{
InternalFlags = (TrackSectionFlags)Enum.Parse(typeof(TrackSectionFlags), value.ToString());
}
}
/// <summary>
/// Get or sets whether the PitLaneEntrance flag should be set for the section.
/// </summary>
public bool PitLaneEntrance
{
get { return InternalFlags.HasFlag(TrackSectionFlags.PitLaneEntrance); }
set
{
SetFlag(value, TrackSectionFlags.PitLaneEntrance);
}
}
/// <summary>
/// Get or sets whether the PitLaneExit flag should be set for the section.
/// </summary>
public bool PitLaneExit
{
get { return InternalFlags.HasFlag(TrackSectionFlags.PitLaneExit); }
set
{
SetFlag(value, TrackSectionFlags.PitLaneExit);
}
}
/// <summary>
/// Gets or sets the height of the kerb in the section, if there is one set with the HasLeftKerb or HasRightKerb flags.
/// </summary>
public KerbHeight KerbHeight
{
get
{
return InternalFlags.HasFlag(TrackSectionFlags.KerbHeight)
? KerbHeight.Low
: KerbHeight.High;
}
set
{
SetFlag(value == KerbHeight.Low, TrackSectionFlags.KerbHeight);
}
}
/// <summary>
/// Gets or sets whether there is a kerb on the left side of the track in the section.
/// </summary>
public bool HasLeftKerb
{
get { return InternalFlags.HasFlag(TrackSectionFlags.LeftKerb); }
set
{
SetFlag(value, TrackSectionFlags.LeftKerb);
}
}
/// <summary>
/// Gets or sets whether there is a kerb on the right side of the track in the section.
/// </summary>
public bool HasRightKerb
{
get { return InternalFlags.HasFlag(TrackSectionFlags.RightKerb); }
set
{
SetFlag(value, TrackSectionFlags.RightKerb);
}
}
/// <summary>
/// Gets or sets whether 300/200/100 signs should appear before the section.
/// </summary>
public bool RoadSigns
{
get { return InternalFlags.HasFlag(TrackSectionFlags.RoadSigns); }
set
{
SetFlag(value, TrackSectionFlags.RoadSigns);
}
}
/// <summary>
/// Gets or sets whether an arrow sign should appear before the section.
/// </summary>
public bool RoadSignArrow
{
get { return InternalFlags.HasFlag(TrackSectionFlags.RoadSignArrow); }
set
{
SetFlag(value, TrackSectionFlags.RoadSignArrow);
}
}
/// <summary>
/// Gets or sets whether an arrow and 100 sign should appear before the section.
/// </summary>
public bool RoadSignArrow100
{
get { return InternalFlags.HasFlag(TrackSectionFlags.RoadSignArrow100); }
set
{
SetFlag(value, TrackSectionFlags.RoadSignArrow100);
}
}
/// <summary>
/// Gets or sets whether the right fence should be bridged from the starting point of
/// the current section to the starting point of the next non-bridged section.
/// </summary>
public bool BridgedRightFence
{
get { return InternalFlags.HasFlag(TrackSectionFlags.BridgedRightFence); }
set
{
SetFlag(value, TrackSectionFlags.BridgedRightFence);
}
}
/// <summary>
/// Gets or sets whether the left fence should be bridged from the starting point of
/// the current section to the starting point of the next non-bridged section.
/// </summary>
public bool BridgedLeftFence
{
get { return InternalFlags.HasFlag(TrackSectionFlags.BridgedLeftFence); }
set
{
SetFlag(value, TrackSectionFlags.BridgedLeftFence);
}
}
/// <summary>
/// Gets or sets whether the right wall of the section should be removed/invisible.
/// </summary>
public bool RemoveRightWall
{
get { return InternalFlags.HasFlag(TrackSectionFlags.RightWallRemove); }
set
{
SetFlag(value, TrackSectionFlags.RightWallRemove);
}
}
/// <summary>
/// Gets or sets whether the right wall of the section should be removed/invisible.
/// </summary>
public bool RemoveLeftWall
{
get { return InternalFlags.HasFlag(TrackSectionFlags.LeftWallRemove); }
set
{
SetFlag(value, TrackSectionFlags.LeftWallRemove);
}
}
/// <summary>
/// Gets or sets the Unknown1 flag (0x100). Not used in any default track, probably has no use.
/// </summary>
public bool Unknown1
{
get { return InternalFlags.HasFlag(TrackSectionFlags.Unknown1); }
set
{
SetFlag(value, TrackSectionFlags.Unknown1);
}
}
/// <summary>
/// Gets or sets the Unknown2 flag (0x200). Not used in any default track, probably has no use.
/// </summary>
public bool Unknown2
{
get { return InternalFlags.HasFlag(TrackSectionFlags.Unknown2); }
set
{
SetFlag(value, TrackSectionFlags.Unknown2);
}
}
/// <summary>
/// Gets or sets the Unknown3 flag (0x4000).
/// </summary>
public bool Unknown3
{
get { return InternalFlags.HasFlag(TrackSectionFlags.Unknown3); }
set
{
SetFlag(value, TrackSectionFlags.Unknown3);
}
}
/// <summary>
/// Gets or sets the Unknown4 flag (0x8000). Not used in any default track, probably has no use.
/// </summary>
public bool Unknown4
{
get { return InternalFlags.HasFlag(TrackSectionFlags.Unknown4); }
set
{
SetFlag(value, TrackSectionFlags.Unknown4);
}
}
private void SetFlag(bool value, TrackSectionFlags flag)
{
if (value)
{
InternalFlags |= flag;
}
else
{
InternalFlags &= ~flag;
}
}
[Flags]
private enum TrackSectionFlags
{
PitLaneEntrance = 0x1,
PitLaneExit = 0x2,
KerbHeight = 0x4,
RoadSigns = 0x8,
BridgedRightFence = 0x10,
BridgedLeftFence = 0x20,
RoadSignArrow = 0x40,
RoadSignArrow100 = 0x80,
Unknown1 = 0x100,
Unknown2 = 0x200,
RightKerb = 0x400,
LeftKerb = 0x800,
RightWallRemove = 0x1000,
LeftWallRemove = 0x2000,
Unknown3 = 0x4000,
Unknown4 = 0x8000
}
}
/// <summary>
/// Defines the type of kerb that exists in the track section.
/// </summary>
public enum KerbHeight
{
/// <summary>
/// Low kerb, can be driven over.
/// </summary>
Low,
/// <summary>
/// High kerb, upsets the car when driven over.
/// </summary>
High
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Globalization;
using System.Linq;
namespace Avalonia
{
/// <summary>
/// Defines a rectangle.
/// </summary>
public struct Rect
{
/// <summary>
/// An empty rectangle.
/// </summary>
public static readonly Rect Empty = default(Rect);
/// <summary>
/// The X position.
/// </summary>
private readonly double _x;
/// <summary>
/// The Y position.
/// </summary>
private readonly double _y;
/// <summary>
/// The width.
/// </summary>
private readonly double _width;
/// <summary>
/// The height.
/// </summary>
private readonly double _height;
/// <summary>
/// Initializes a new instance of the <see cref="Rect"/> structure.
/// </summary>
/// <param name="x">The X position.</param>
/// <param name="y">The Y position.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public Rect(double x, double y, double width, double height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
/// <summary>
/// Initializes a new instance of the <see cref="Rect"/> structure.
/// </summary>
/// <param name="size">The size of the rectangle.</param>
public Rect(Size size)
{
_x = 0;
_y = 0;
_width = size.Width;
_height = size.Height;
}
/// <summary>
/// Initializes a new instance of the <see cref="Rect"/> structure.
/// </summary>
/// <param name="position">The position of the rectangle.</param>
/// <param name="size">The size of the rectangle.</param>
public Rect(Point position, Size size)
{
_x = position.X;
_y = position.Y;
_width = size.Width;
_height = size.Height;
}
/// <summary>
/// Initializes a new instance of the <see cref="Rect"/> structure.
/// </summary>
/// <param name="topLeft">The top left position of the rectangle.</param>
/// <param name="bottomRight">The bottom right position of the rectangle.</param>
public Rect(Point topLeft, Point bottomRight)
{
_x = topLeft.X;
_y = topLeft.Y;
_width = bottomRight.X - topLeft.X;
_height = bottomRight.Y - topLeft.Y;
}
/// <summary>
/// Gets the X position.
/// </summary>
public double X => _x;
/// <summary>
/// Gets the Y position.
/// </summary>
public double Y => _y;
/// <summary>
/// Gets the width.
/// </summary>
public double Width => _width;
/// <summary>
/// Gets the height.
/// </summary>
public double Height => _height;
/// <summary>
/// Gets the position of the rectangle.
/// </summary>
public Point Position => new Point(_x, _y);
/// <summary>
/// Gets the size of the rectangle.
/// </summary>
public Size Size => new Size(_width, _height);
/// <summary>
/// Gets the right position of the rectangle.
/// </summary>
public double Right => _x + _width;
/// <summary>
/// Gets the bottom position of the rectangle.
/// </summary>
public double Bottom => _y + _height;
/// <summary>
/// Gets the top left point of the rectangle.
/// </summary>
public Point TopLeft => new Point(_x, _y);
/// <summary>
/// Gets the top right point of the rectangle.
/// </summary>
public Point TopRight => new Point(Right, _y);
/// <summary>
/// Gets the bottom left point of the rectangle.
/// </summary>
public Point BottomLeft => new Point(_x, Bottom);
/// <summary>
/// Gets the bottom right point of the rectangle.
/// </summary>
public Point BottomRight => new Point(Right, Bottom);
/// <summary>
/// Gets the center point of the rectangle.
/// </summary>
public Point Center => new Point(_x + (_width / 2), _y + (_height / 2));
/// <summary>
/// Gets a value that indicates whether the rectangle is empty.
/// </summary>
public bool IsEmpty => _width == 0 && _height == 0;
/// <summary>
/// Checks for equality between two <see cref="Rect"/>s.
/// </summary>
/// <param name="left">The first rect.</param>
/// <param name="right">The second rect.</param>
/// <returns>True if the rects are equal; otherwise false.</returns>
public static bool operator ==(Rect left, Rect right)
{
return left.Position == right.Position && left.Size == right.Size;
}
/// <summary>
/// Checks for unequality between two <see cref="Rect"/>s.
/// </summary>
/// <param name="left">The first rect.</param>
/// <param name="right">The second rect.</param>
/// <returns>True if the rects are unequal; otherwise false.</returns>
public static bool operator !=(Rect left, Rect right)
{
return !(left == right);
}
/// <summary>
/// Multiplies a rectangle by a scaling vector.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="scale">The vector scale.</param>
/// <returns>The scaled rectangle.</returns>
public static Rect operator *(Rect rect, Vector scale)
{
return new Rect(
rect.X * scale.X,
rect.Y * scale.Y,
rect.Width * scale.X,
rect.Height * scale.Y);
}
/// <summary>
/// Divides a rectangle by a vector.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="scale">The vector scale.</param>
/// <returns>The scaled rectangle.</returns>
public static Rect operator /(Rect rect, Vector scale)
{
return new Rect(
rect.X / scale.X,
rect.Y / scale.Y,
rect.Width / scale.X,
rect.Height / scale.Y);
}
/// <summary>
/// Determines whether a point in in the bounds of the rectangle.
/// </summary>
/// <param name="p">The point.</param>
/// <returns>true if the point is in the bounds of the rectangle; otherwise false.</returns>
public bool Contains(Point p)
{
return p.X >= _x && p.X <= _x + _width &&
p.Y >= _y && p.Y <= _y + _height;
}
/// <summary>
/// Determines whether the rectangle fully contains another rectangle.
/// </summary>
/// <param name="r">The rectangle.</param>
/// <returns>true if the rectangle is fully contained; otherwise false.</returns>
public bool Contains(Rect r)
{
return Contains(r.TopLeft) && Contains(r.BottomRight);
}
/// <summary>
/// Centers another rectangle in this rectangle.
/// </summary>
/// <param name="rect">The rectangle to center.</param>
/// <returns>The centered rectangle.</returns>
public Rect CenterRect(Rect rect)
{
return new Rect(
_x + ((_width - rect._width) / 2),
_y + ((_height - rect._height) / 2),
rect._width,
rect._height);
}
/// <summary>
/// Inflates the rectangle.
/// </summary>
/// <param name="thickness">The thickness.</param>
/// <returns>The inflated rectangle.</returns>
public Rect Inflate(double thickness)
{
return Inflate(new Thickness(thickness));
}
/// <summary>
/// Inflates the rectangle.
/// </summary>
/// <param name="thickness">The thickness.</param>
/// <returns>The inflated rectangle.</returns>
public Rect Inflate(Thickness thickness)
{
return new Rect(
new Point(_x - thickness.Left, _y - thickness.Top),
Size.Inflate(thickness));
}
/// <summary>
/// Deflates the rectangle.
/// </summary>
/// <param name="thickness">The thickness.</param>
/// <returns>The deflated rectangle.</returns>
/// <remarks>The deflated rectangle size cannot be less than 0.</remarks>
public Rect Deflate(double thickness)
{
return Deflate(new Thickness(thickness / 2));
}
/// <summary>
/// Deflates the rectangle by a <see cref="Thickness"/>.
/// </summary>
/// <param name="thickness">The thickness.</param>
/// <returns>The deflated rectangle.</returns>
/// <remarks>The deflated rectangle size cannot be less than 0.</remarks>
public Rect Deflate(Thickness thickness)
{
return new Rect(
new Point(_x + thickness.Left, _y + thickness.Top),
Size.Deflate(thickness));
}
/// <summary>
/// Returns a boolean indicating whether the given object is equal to this rectangle.
/// </summary>
/// <param name="obj">The object to compare against.</param>
/// <returns>True if the object is equal to this rectangle; false otherwise.</returns>
public override bool Equals(object obj)
{
if (obj is Rect)
{
var other = (Rect)obj;
return Position == other.Position && Size == other.Size;
}
return false;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = (hash * 23) + X.GetHashCode();
hash = (hash * 23) + Y.GetHashCode();
hash = (hash * 23) + Width.GetHashCode();
hash = (hash * 23) + Height.GetHashCode();
return hash;
}
}
/// <summary>
/// Gets the intersection of two rectangles.
/// </summary>
/// <param name="rect">The other rectangle.</param>
/// <returns>The intersection.</returns>
public Rect Intersect(Rect rect)
{
var newLeft = (rect.X > X) ? rect.X : X;
var newTop = (rect.Y > Y) ? rect.Y : Y;
var newRight = (rect.Right < Right) ? rect.Right : Right;
var newBottom = (rect.Bottom < Bottom) ? rect.Bottom : Bottom;
if ((newRight > newLeft) && (newBottom > newTop))
{
return new Rect(newLeft, newTop, newRight - newLeft, newBottom - newTop);
}
else
{
return Empty;
}
}
/// <summary>
/// Determines whether a rectangle intersects with this rectangle.
/// </summary>
/// <param name="rect">The other rectangle.</param>
/// <returns>
/// True if the specified rectangle intersects with this one; otherwise false.
/// </returns>
public bool Intersects(Rect rect)
{
return (rect.X < Right) && (X < rect.Right) && (rect.Y < Bottom) && (Y < rect.Bottom);
}
/// <summary>
/// Returns the axis-aligned bounding box of a transformed rectangle.
/// </summary>
/// <param name="matrix">The transform.</param>
/// <returns>The bounding box</returns>
public Rect TransformToAABB(Matrix matrix)
{
var points = new[]
{
TopLeft.Transform(matrix),
TopRight.Transform(matrix),
BottomRight.Transform(matrix),
BottomLeft.Transform(matrix),
};
var left = double.MaxValue;
var right = double.MinValue;
var top = double.MaxValue;
var bottom = double.MinValue;
foreach (var p in points)
{
if (p.X < left) left = p.X;
if (p.X > right) right = p.X;
if (p.Y < top) top = p.Y;
if (p.Y > bottom) bottom = p.Y;
}
return new Rect(new Point(left, top), new Point(right, bottom));
}
/// <summary>
/// Translates the rectangle by an offset.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns>The translated rectangle.</returns>
public Rect Translate(Vector offset)
{
return new Rect(Position + offset, Size);
}
/// <summary>
/// Gets the union of two rectangles.
/// </summary>
/// <param name="rect">The other rectangle.</param>
/// <returns>The union.</returns>
public Rect Union(Rect rect)
{
if (IsEmpty)
{
return rect;
}
else if (rect.IsEmpty)
{
return this;
}
else
{
var x1 = Math.Min(this.X, rect.X);
var x2 = Math.Max(this.Right, rect.Right);
var y1 = Math.Min(this.Y, rect.Y);
var y2 = Math.Max(this.Bottom, rect.Bottom);
return new Rect(new Point(x1, y1), new Point(x2, y2));
}
}
/// <summary>
/// Returns a new <see cref="Rect"/> with the specified X position.
/// </summary>
/// <param name="x">The x position.</param>
/// <returns>The new <see cref="Rect"/>.</returns>
public Rect WithX(double x)
{
return new Rect(x, _y, _width, _height);
}
/// <summary>
/// Returns a new <see cref="Rect"/> with the specified Y position.
/// </summary>
/// <param name="y">The y position.</param>
/// <returns>The new <see cref="Rect"/>.</returns>
public Rect WithY(double y)
{
return new Rect(_x, y, _width, _height);
}
/// <summary>
/// Returns a new <see cref="Rect"/> with the specified width.
/// </summary>
/// <param name="width">The width.</param>
/// <returns>The new <see cref="Rect"/>.</returns>
public Rect WithWidth(double width)
{
return new Rect(_x, _y, width, _height);
}
/// <summary>
/// Returns a new <see cref="Rect"/> with the specified height.
/// </summary>
/// <param name="height">The height.</param>
/// <returns>The new <see cref="Rect"/>.</returns>
public Rect WithHeight(double height)
{
return new Rect(_x, _y, _width, height);
}
/// <summary>
/// Returns the string representation of the rectangle.
/// </summary>
/// <returns>The string representation of the rectangle.</returns>
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"{0}, {1}, {2}, {3}",
_x,
_y,
_width,
_height);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Services.Connectors
{
public class UserAccountServicesConnector : IUserAccountService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
public UserAccountServicesConnector()
{
}
public UserAccountServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public UserAccountServicesConnector(IConfigSource source)
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig assetConfig = source.Configs["UserAccountService"];
if (assetConfig == null)
{
m_log.Error("[ACCOUNT CONNECTOR]: UserAccountService missing from OpenSim.ini");
throw new Exception("User account connector init error");
}
string serviceURI = assetConfig.GetString("UserAccountServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[ACCOUNT CONNECTOR]: No Server URI named in section UserAccountService");
throw new Exception("User account connector init error");
}
m_ServerURI = serviceURI;
}
public virtual UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "getaccount";
sendData["ScopeID"] = scopeID;
sendData["FirstName"] = firstName.ToString();
sendData["LastName"] = lastName.ToString();
return SendAndGetReply(sendData);
}
public virtual UserAccount GetUserAccount(UUID scopeID, string email)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "getaccount";
sendData["ScopeID"] = scopeID;
sendData["Email"] = email;
return SendAndGetReply(sendData);
}
public virtual UserAccount GetUserAccount(UUID scopeID, UUID userID)
{
//m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccount {0}", userID);
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "getaccount";
sendData["ScopeID"] = scopeID;
sendData["UserID"] = userID.ToString();
return SendAndGetReply(sendData);
}
public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "getaccounts";
sendData["ScopeID"] = scopeID.ToString();
sendData["query"] = query;
string reply = string.Empty;
string reqString = ServerUtils.BuildQueryString(sendData);
// m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/accounts",
reqString);
if (reply == null || (reply != null && reply == string.Empty))
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received null or empty reply");
return null;
}
}
catch (Exception e)
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting accounts server: {0}", e.Message);
}
List<UserAccount> accounts = new List<UserAccount>();
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
if (replyData.ContainsKey("result") && replyData.ContainsKey("result").ToString() == "null")
{
return accounts;
}
Dictionary<string, object>.ValueCollection accountList = replyData.Values;
//m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count);
foreach (object acc in accountList)
{
if (acc is Dictionary<string, object>)
{
UserAccount pinfo = new UserAccount((Dictionary<string, object>)acc);
accounts.Add(pinfo);
}
else
m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received invalid response type {0}",
acc.GetType());
}
}
else
m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccounts received null response");
return accounts;
}
public virtual bool StoreUserAccount(UserAccount data)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "setaccount";
Dictionary<string, object> structData = data.ToKeyValuePairs();
foreach (KeyValuePair<string,object> kvp in structData)
sendData[kvp.Key] = kvp.Value.ToString();
return SendAndGetBoolReply(sendData);
}
private UserAccount SendAndGetReply(Dictionary<string, object> sendData)
{
string reply = string.Empty;
string reqString = ServerUtils.BuildQueryString(sendData);
// m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/accounts",
reqString);
if (reply == null || (reply != null && reply == string.Empty))
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccount received null or empty reply");
return null;
}
}
catch (Exception e)
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user account server: {0}", e.Message);
}
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
UserAccount account = null;
if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
{
account = new UserAccount((Dictionary<string, object>)replyData["result"]);
}
}
return account;
}
private bool SendAndGetBoolReply(Dictionary<string, object> sendData)
{
string reqString = ServerUtils.BuildQueryString(sendData);
// m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/accounts",
reqString);
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData.ContainsKey("result"))
{
if (replyData["result"].ToString().ToLower() == "success")
return true;
else
return false;
}
else
m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Set or Create UserAccount reply data does not contain result field");
}
else
m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Set or Create UserAccount received empty reply");
}
catch (Exception e)
{
m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Exception when contacting user account server: {0}", e.Message);
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.DirectoryServices.Protocols
{
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Principal;
public enum ExtendedDNFlag
{
HexString = 0,
StandardString = 1
}
[Flags]
public enum SecurityMasks
{
None = 0,
Owner = 1,
Group = 2,
Dacl = 4,
Sacl = 8
}
[Flags]
public enum DirectorySynchronizationOptions : long
{
None = 0,
ObjectSecurity = 0x1,
ParentsFirst = 0x0800,
PublicDataOnly = 0x2000,
IncrementalValues = 0x80000000
}
public enum SearchOption
{
DomainScope = 1,
PhantomRoot = 2
}
internal class UtilityHandle
{
private static ConnectionHandle s_handle = new ConnectionHandle();
public static ConnectionHandle GetHandle()
{
return s_handle;
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class SortKey
{
private string _name = null;
private string _rule = null;
private bool _order = false;
public SortKey()
{
}
public SortKey(string attributeName, string matchingRule, bool reverseOrder)
{
AttributeName = attributeName;
_rule = matchingRule;
_order = reverseOrder;
}
public string AttributeName
{
get
{
return _name;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
_name = value;
}
}
public string MatchingRule
{
get
{
return _rule;
}
set
{
_rule = value;
}
}
public bool ReverseOrder
{
get
{
return _order;
}
set
{
_order = value;
}
}
}
public class DirectoryControl
{
// control value
internal byte[] directoryControlValue = null;
// oid of the control
private string _directoryControlType = "";
// criticality of the control
private bool _directoryControlCriticality = true;
// whether it is a server side control or not
private bool _directoryControlServerSide = true;
public DirectoryControl(string type, byte[] value, bool isCritical, bool serverSide)
{
_directoryControlType = type;
if (type == null)
throw new ArgumentNullException("type");
if (value != null)
{
directoryControlValue = new byte[value.Length];
for (int i = 0; i < value.Length; i++)
directoryControlValue[i] = value[i];
}
_directoryControlCriticality = isCritical;
_directoryControlServerSide = serverSide;
}
public virtual byte[] GetValue()
{
if (directoryControlValue == null)
return new byte[0];
else
{
byte[] tempValue = new byte[directoryControlValue.Length];
for (int i = 0; i < directoryControlValue.Length; i++)
tempValue[i] = directoryControlValue[i];
return tempValue;
}
}
public string Type
{
get
{
return _directoryControlType;
}
}
public bool IsCritical
{
get
{
return _directoryControlCriticality;
}
set
{
_directoryControlCriticality = value;
}
}
public bool ServerSide
{
get
{
return _directoryControlServerSide;
}
set
{
_directoryControlServerSide = value;
}
}
internal static void TransformControls(DirectoryControl[] controls)
{
for (int i = 0; i < controls.Length; i++)
{
Debug.Assert(controls[i] != null);
byte[] value = controls[i].GetValue();
// if it is a page control
if (controls[i].Type == "1.2.840.113556.1.4.319")
{
object[] result = BerConverter.Decode("{iO}", value);
Debug.Assert((result != null) && (result.Length == 2));
int size = (int)result[0];
byte[] cookie = (byte[])result[1];
// user expects cookie with length 0 as paged search is done.
if (cookie == null)
cookie = new byte[0];
PageResultResponseControl pageControl = new PageResultResponseControl(size, cookie, controls[i].IsCritical, controls[i].GetValue());
controls[i] = pageControl;
}
else if (controls[i].Type == "1.2.840.113556.1.4.1504")
{
// asq control
object[] o = null;
o = BerConverter.Decode("{e}", value);
Debug.Assert((o != null) && (o.Length == 1));
int result = (int)o[0];
AsqResponseControl asq = new AsqResponseControl(result, controls[i].IsCritical, controls[i].GetValue());
controls[i] = asq;
}
else if (controls[i].Type == "1.2.840.113556.1.4.841")
{
//dirsync control
object[] o = BerConverter.Decode("{iiO}", value);
Debug.Assert(o != null && o.Length == 3);
int moreData = (int)o[0];
int count = (int)o[1];
byte[] dirsyncCookie = (byte[])o[2];
DirSyncResponseControl dirsync = new DirSyncResponseControl(dirsyncCookie, (moreData == 0 ? false : true), count, controls[i].IsCritical, controls[i].GetValue());
controls[i] = dirsync;
}
else if (controls[i].Type == "1.2.840.113556.1.4.474")
{
object[] o = null;
int result = 0;
string attribute = null;
bool decodeSucceeded;
//sort control
o = BerConverter.TryDecode("{ea}", value, out decodeSucceeded);
// decode might fail as AD for example never returns attribute name, we don't want to unnecessarily throw and catch exception
if (decodeSucceeded)
{
Debug.Assert(o != null && o.Length == 2);
result = (int)o[0];
attribute = (string)o[1];
}
else
{
// decoding might fail as attribute is optional
o = BerConverter.Decode("{e}", value);
Debug.Assert(o != null && o.Length == 1);
result = (int)o[0];
}
SortResponseControl sort = new SortResponseControl((ResultCode)result, attribute, controls[i].IsCritical, controls[i].GetValue());
controls[i] = sort;
}
else if (controls[i].Type == "2.16.840.1.113730.3.4.10")
{
int position;
int count;
int result;
byte[] context = null;
object[] o = null;
bool decodeSucceeded = false;
o = BerConverter.TryDecode("{iieO}", value, out decodeSucceeded);
if (decodeSucceeded)
{
Debug.Assert(o != null && o.Length == 4);
position = (int)o[0];
count = (int)o[1];
result = (int)o[2];
context = (byte[])o[3];
}
else
{
o = BerConverter.Decode("{iie}", value);
Debug.Assert(o != null && o.Length == 3);
position = (int)o[0];
count = (int)o[1];
result = (int)o[2];
}
VlvResponseControl vlv = new VlvResponseControl(position, count, context, (ResultCode)result, controls[i].IsCritical, controls[i].GetValue());
controls[i] = vlv;
}
}
}
}
public class AsqRequestControl : DirectoryControl
{
private string _name;
public AsqRequestControl() : base("1.2.840.113556.1.4.1504", null, true, true)
{
}
public AsqRequestControl(string attributeName) : this()
{
_name = attributeName;
}
public string AttributeName
{
get
{
return _name;
}
set
{
_name = value;
}
}
public override byte[] GetValue()
{
this.directoryControlValue = BerConverter.Encode("{s}", new object[] { _name });
return base.GetValue();
}
}
public class AsqResponseControl : DirectoryControl
{
private ResultCode _result;
internal AsqResponseControl(int result, bool criticality, byte[] controlValue) : base("1.2.840.113556.1.4.1504", controlValue, criticality, true)
{
_result = (ResultCode)result;
}
public ResultCode Result
{
get
{
return _result;
}
}
}
public class CrossDomainMoveControl : DirectoryControl
{
private string _dcName = null;
public CrossDomainMoveControl() : base("1.2.840.113556.1.4.521", null, true, true)
{
}
public CrossDomainMoveControl(string targetDomainController) : this()
{
_dcName = targetDomainController;
}
public string TargetDomainController
{
get
{
return _dcName;
}
set
{
_dcName = value;
}
}
public override byte[] GetValue()
{
if (_dcName != null)
{
UTF8Encoding encoder = new UTF8Encoding();
byte[] bytes = encoder.GetBytes(_dcName);
// allocate large enough space for the '\0' character
this.directoryControlValue = new byte[bytes.Length + 2];
for (int i = 0; i < bytes.Length; i++)
this.directoryControlValue[i] = bytes[i];
}
return base.GetValue();
}
}
public class DomainScopeControl : DirectoryControl
{
public DomainScopeControl() : base("1.2.840.113556.1.4.1339", null, true, true)
{
}
}
public class ExtendedDNControl : DirectoryControl
{
private ExtendedDNFlag _format = ExtendedDNFlag.HexString;
public ExtendedDNControl() : base("1.2.840.113556.1.4.529", null, true, true)
{
}
public ExtendedDNControl(ExtendedDNFlag flag) : this()
{
Flag = flag;
}
public ExtendedDNFlag Flag
{
get
{
return _format;
}
set
{
if (value < ExtendedDNFlag.HexString || value > ExtendedDNFlag.StandardString)
throw new InvalidEnumArgumentException("value", (int)value, typeof(ExtendedDNFlag));
_format = value;
}
}
public override byte[] GetValue()
{
this.directoryControlValue = BerConverter.Encode("{i}", new object[] { (int)_format });
return base.GetValue();
}
}
public class LazyCommitControl : DirectoryControl
{
public LazyCommitControl() : base("1.2.840.113556.1.4.619", null, true, true) { }
}
public class DirectoryNotificationControl : DirectoryControl
{
public DirectoryNotificationControl() : base("1.2.840.113556.1.4.528", null, true, true) { }
}
public class PermissiveModifyControl : DirectoryControl
{
public PermissiveModifyControl() : base("1.2.840.113556.1.4.1413", null, true, true) { }
}
public class SecurityDescriptorFlagControl : DirectoryControl
{
private SecurityMasks _flag = SecurityMasks.None;
public SecurityDescriptorFlagControl() : base("1.2.840.113556.1.4.801", null, true, true) { }
public SecurityDescriptorFlagControl(SecurityMasks masks) : this()
{
SecurityMasks = masks;
}
public SecurityMasks SecurityMasks
{
get
{
return _flag;
}
set
{
// we don't do validation to the dirsync flag here as underneath API does not check for it and we don't want to put
// unnecessary limitation on it.
_flag = value;
}
}
public override byte[] GetValue()
{
this.directoryControlValue = BerConverter.Encode("{i}", new object[] { (int)_flag });
return base.GetValue();
}
}
public class SearchOptionsControl : DirectoryControl
{
private SearchOption _flag = SearchOption.DomainScope;
public SearchOptionsControl() : base("1.2.840.113556.1.4.1340", null, true, true) { }
public SearchOptionsControl(SearchOption flags) : this()
{
SearchOption = flags;
}
public SearchOption SearchOption
{
get
{
return _flag;
}
set
{
if (value < SearchOption.DomainScope || value > SearchOption.PhantomRoot)
throw new InvalidEnumArgumentException("value", (int)value, typeof(SearchOption));
_flag = value;
}
}
public override byte[] GetValue()
{
this.directoryControlValue = BerConverter.Encode("{i}", new object[] { (int)_flag });
return base.GetValue();
}
}
public class ShowDeletedControl : DirectoryControl
{
public ShowDeletedControl() : base("1.2.840.113556.1.4.417", null, true, true) { }
}
public class TreeDeleteControl : DirectoryControl
{
public TreeDeleteControl() : base("1.2.840.113556.1.4.805", null, true, true) { }
}
public class VerifyNameControl : DirectoryControl
{
private string _name = null;
private int _flag = 0;
public VerifyNameControl() : base("1.2.840.113556.1.4.1338", null, true, true) { }
public VerifyNameControl(string serverName) : this()
{
if (serverName == null)
throw new ArgumentNullException("serverName");
_name = serverName;
}
public VerifyNameControl(string serverName, int flag) : this(serverName)
{
_flag = flag;
}
public string ServerName
{
get
{
return _name;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
_name = value;
}
}
public int Flag
{
get
{
return _flag;
}
set
{
_flag = value;
}
}
public override byte[] GetValue()
{
byte[] tmpValue = null;
if (ServerName != null)
{
UnicodeEncoding unicode = new UnicodeEncoding();
tmpValue = unicode.GetBytes(ServerName);
}
this.directoryControlValue = BerConverter.Encode("{io}", new object[] { _flag, tmpValue });
return base.GetValue();
}
}
public class DirSyncRequestControl : DirectoryControl
{
private byte[] _dirsyncCookie = null;
private DirectorySynchronizationOptions _flag = DirectorySynchronizationOptions.None;
private int _count = 1048576;
public DirSyncRequestControl() : base("1.2.840.113556.1.4.841", null, true, true) { }
public DirSyncRequestControl(byte[] cookie) : this()
{
_dirsyncCookie = cookie;
}
public DirSyncRequestControl(byte[] cookie, DirectorySynchronizationOptions option) : this(cookie)
{
Option = option;
}
public DirSyncRequestControl(byte[] cookie, DirectorySynchronizationOptions option, int attributeCount) : this(cookie, option)
{
AttributeCount = attributeCount;
}
public byte[] Cookie
{
get
{
if (_dirsyncCookie == null)
return new byte[0];
else
{
byte[] tempCookie = new byte[_dirsyncCookie.Length];
for (int i = 0; i < tempCookie.Length; i++)
tempCookie[i] = _dirsyncCookie[i];
return tempCookie;
}
}
set
{
_dirsyncCookie = value;
}
}
public DirectorySynchronizationOptions Option
{
get
{
return _flag;
}
set
{
// we don't do validation to the dirsync flag here as underneath API does not check for it and we don't want to put
// unnecessary limitation on it.
_flag = value;
}
}
public int AttributeCount
{
get
{
return _count;
}
set
{
if (value < 0)
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.ValidValue), "value");
_count = value;
}
}
public override byte[] GetValue()
{
object[] o = new object[] { (int)_flag, _count, _dirsyncCookie };
this.directoryControlValue = BerConverter.Encode("{iio}", o);
return base.GetValue();
}
}
public class DirSyncResponseControl : DirectoryControl
{
private byte[] _dirsyncCookie = null;
private bool _moreResult = false;
private int _size = 0;
internal DirSyncResponseControl(byte[] cookie, bool moreData, int resultSize, bool criticality, byte[] controlValue) : base("1.2.840.113556.1.4.841", controlValue, criticality, true)
{
_dirsyncCookie = cookie;
_moreResult = moreData;
_size = resultSize;
}
public byte[] Cookie
{
get
{
if (_dirsyncCookie == null)
return new byte[0];
else
{
byte[] tempCookie = new byte[_dirsyncCookie.Length];
for (int i = 0; i < tempCookie.Length; i++)
tempCookie[i] = _dirsyncCookie[i];
return tempCookie;
}
}
}
public bool MoreData
{
get
{
return _moreResult;
}
}
public int ResultSize
{
get
{
return _size;
}
}
}
public class PageResultRequestControl : DirectoryControl
{
private int _size = 512;
private byte[] _pageCookie = null;
public PageResultRequestControl() : base("1.2.840.113556.1.4.319", null, true, true) { }
public PageResultRequestControl(int pageSize) : this()
{
PageSize = pageSize;
}
public PageResultRequestControl(byte[] cookie) : this()
{
_pageCookie = cookie;
}
public int PageSize
{
get
{
return _size;
}
set
{
if (value < 0)
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.ValidValue), "value");
_size = value;
}
}
public byte[] Cookie
{
get
{
if (_pageCookie == null)
return new byte[0];
byte[] tempCookie = new byte[_pageCookie.Length];
for (int i = 0; i < _pageCookie.Length; i++)
tempCookie[i] = _pageCookie[i];
return tempCookie;
}
set
{
_pageCookie = value;
}
}
public override byte[] GetValue()
{
object[] o = new object[] { _size, _pageCookie };
this.directoryControlValue = BerConverter.Encode("{io}", o);
return base.GetValue();
}
}
public class PageResultResponseControl : DirectoryControl
{
private byte[] _pageCookie = null;
private int _count = 0;
internal PageResultResponseControl(int count, byte[] cookie, bool criticality, byte[] controlValue) : base("1.2.840.113556.1.4.319", controlValue, criticality, true)
{
_count = count;
_pageCookie = cookie;
}
public byte[] Cookie
{
get
{
if (_pageCookie == null)
return new byte[0];
else
{
byte[] tempCookie = new byte[_pageCookie.Length];
for (int i = 0; i < _pageCookie.Length; i++)
{
tempCookie[i] = _pageCookie[i];
}
return tempCookie;
}
}
}
public int TotalCount
{
get
{
return _count;
}
}
}
public class SortRequestControl : DirectoryControl
{
private SortKey[] _keys = new SortKey[0];
public SortRequestControl(params SortKey[] sortKeys) : base("1.2.840.113556.1.4.473", null, true, true)
{
if (sortKeys == null)
throw new ArgumentNullException("sortKeys");
for (int i = 0; i < sortKeys.Length; i++)
{
if (sortKeys[i] == null)
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NullValueArray), "sortKeys");
}
_keys = new SortKey[sortKeys.Length];
for (int i = 0; i < sortKeys.Length; i++)
{
_keys[i] = new SortKey(sortKeys[i].AttributeName, sortKeys[i].MatchingRule, sortKeys[i].ReverseOrder);
}
}
public SortRequestControl(string attributeName, bool reverseOrder) : this(attributeName, null, reverseOrder)
{
}
public SortRequestControl(string attributeName, string matchingRule, bool reverseOrder) : base("1.2.840.113556.1.4.473", null, true, true)
{
SortKey key = new SortKey(attributeName, matchingRule, reverseOrder);
_keys = new SortKey[1];
_keys[0] = key;
}
public SortKey[] SortKeys
{
get
{
if (_keys == null)
return new SortKey[0];
else
{
SortKey[] tempKeys = new SortKey[_keys.Length];
for (int i = 0; i < _keys.Length; i++)
{
tempKeys[i] = new SortKey(_keys[i].AttributeName, _keys[i].MatchingRule, _keys[i].ReverseOrder);
}
return tempKeys;
}
}
set
{
if (value == null)
throw new ArgumentNullException("value");
for (int i = 0; i < value.Length; i++)
{
if (value[i] == null)
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NullValueArray), "value");
}
_keys = new SortKey[value.Length];
for (int i = 0; i < value.Length; i++)
{
_keys[i] = new SortKey(value[i].AttributeName, value[i].MatchingRule, value[i].ReverseOrder);
}
}
}
public override byte[] GetValue()
{
IntPtr control = (IntPtr)0;
int structSize = Marshal.SizeOf(typeof(SortKey));
int keyCount = _keys.Length;
IntPtr memHandle = Utility.AllocHGlobalIntPtrArray(keyCount + 1);
try
{
IntPtr tempPtr = (IntPtr)0;
IntPtr sortPtr = (IntPtr)0;
int i = 0;
for (i = 0; i < keyCount; i++)
{
sortPtr = Marshal.AllocHGlobal(structSize);
Marshal.StructureToPtr(_keys[i], sortPtr, false);
tempPtr = (IntPtr)((long)memHandle + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, sortPtr);
}
tempPtr = (IntPtr)((long)memHandle + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, (IntPtr)0);
bool critical = IsCritical;
int error = Wldap32.ldap_create_sort_control(UtilityHandle.GetHandle(), memHandle, critical ? (byte)1 : (byte)0, ref control);
if (error != 0)
{
if (Utility.IsLdapError((LdapError)error))
{
string errorMessage = LdapErrorMappings.MapResultCode(error);
throw new LdapException(error, errorMessage);
}
else
throw new LdapException(error);
}
LdapControl managedControl = new LdapControl();
Marshal.PtrToStructure(control, managedControl);
berval value = managedControl.ldctl_value;
// reinitialize the value
directoryControlValue = null;
if (value != null)
{
directoryControlValue = new byte[value.bv_len];
Marshal.Copy(value.bv_val, directoryControlValue, 0, value.bv_len);
}
}
finally
{
if (control != (IntPtr)0)
Wldap32.ldap_control_free(control);
if (memHandle != (IntPtr)0)
{
//release the memory from the heap
for (int i = 0; i < keyCount; i++)
{
IntPtr tempPtr = Marshal.ReadIntPtr(memHandle, IntPtr.Size * i);
if (tempPtr != (IntPtr)0)
{
// free the marshalled name
IntPtr ptr = Marshal.ReadIntPtr(tempPtr);
if (ptr != (IntPtr)0)
Marshal.FreeHGlobal(ptr);
// free the marshalled rule
ptr = Marshal.ReadIntPtr(tempPtr, IntPtr.Size);
if (ptr != (IntPtr)0)
Marshal.FreeHGlobal(ptr);
Marshal.FreeHGlobal(tempPtr);
}
}
Marshal.FreeHGlobal(memHandle);
}
}
return base.GetValue();
}
}
public class SortResponseControl : DirectoryControl
{
private ResultCode _result;
private string _name;
internal SortResponseControl(ResultCode result, string attributeName, bool critical, byte[] value) : base("1.2.840.113556.1.4.474", value, critical, true)
{
_result = result;
_name = attributeName;
}
public ResultCode Result
{
get
{
return _result;
}
}
public string AttributeName
{
get
{
return _name;
}
}
}
public class VlvRequestControl : DirectoryControl
{
private int _before = 0;
private int _after = 0;
private int _offset = 0;
private int _estimateCount = 0;
private byte[] _target = null;
private byte[] _context = null;
public VlvRequestControl() : base("2.16.840.1.113730.3.4.9", null, true, true) { }
public VlvRequestControl(int beforeCount, int afterCount, int offset) : this()
{
BeforeCount = beforeCount;
AfterCount = afterCount;
Offset = offset;
}
public VlvRequestControl(int beforeCount, int afterCount, string target) : this()
{
BeforeCount = beforeCount;
AfterCount = afterCount;
if (target != null)
{
UTF8Encoding encoder = new UTF8Encoding();
byte[] bytes = encoder.GetBytes(target);
_target = bytes;
}
}
public VlvRequestControl(int beforeCount, int afterCount, byte[] target) : this()
{
BeforeCount = beforeCount;
AfterCount = afterCount;
Target = target;
}
public int BeforeCount
{
get
{
return _before;
}
set
{
if (value < 0)
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.ValidValue), "value");
_before = value;
}
}
public int AfterCount
{
get
{
return _after;
}
set
{
if (value < 0)
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.ValidValue), "value");
_after = value;
}
}
public int Offset
{
get
{
return _offset;
}
set
{
if (value < 0)
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.ValidValue), "value");
_offset = value;
}
}
public int EstimateCount
{
get
{
return _estimateCount;
}
set
{
if (value < 0)
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.ValidValue), "value");
_estimateCount = value;
}
}
public byte[] Target
{
get
{
if (_target == null)
return new byte[0];
else
{
byte[] tempContext = new byte[_target.Length];
for (int i = 0; i < tempContext.Length; i++)
{
tempContext[i] = _target[i];
}
return tempContext;
}
}
set
{
_target = value;
}
}
public byte[] ContextId
{
get
{
if (_context == null)
return new byte[0];
else
{
byte[] tempContext = new byte[_context.Length];
for (int i = 0; i < tempContext.Length; i++)
{
tempContext[i] = _context[i];
}
return tempContext;
}
}
set
{
_context = value;
}
}
public override byte[] GetValue()
{
StringBuilder seq = new StringBuilder(10);
ArrayList objList = new ArrayList();
// first encode the before and the after count.
seq.Append("{ii");
objList.Add(BeforeCount);
objList.Add(AfterCount);
// encode Target if it is not null
if (Target.Length != 0)
{
seq.Append("t");
objList.Add(0x80 | 0x1);
seq.Append("o");
objList.Add(Target);
}
else
{
seq.Append("t{");
objList.Add(0xa0);
seq.Append("ii");
objList.Add(Offset);
objList.Add(EstimateCount);
seq.Append("}");
}
// encode the contextID if present
if (ContextId.Length != 0)
{
seq.Append("o");
objList.Add(ContextId);
}
seq.Append("}");
object[] values = new object[objList.Count];
for (int i = 0; i < objList.Count; i++)
{
values[i] = objList[i];
}
directoryControlValue = BerConverter.Encode(seq.ToString(), values);
return base.GetValue();
}
}
public class VlvResponseControl : DirectoryControl
{
private int _position = 0;
private int _count = 0;
private byte[] _context = null;
private ResultCode _result;
internal VlvResponseControl(int targetPosition, int count, byte[] context, ResultCode result, bool criticality, byte[] value) : base("2.16.840.1.113730.3.4.10", value, criticality, true)
{
_position = targetPosition;
_count = count;
_context = context;
_result = result;
}
public int TargetPosition
{
get
{
return _position;
}
}
public int ContentCount
{
get
{
return _count;
}
}
public byte[] ContextId
{
get
{
if (_context == null)
return new byte[0];
else
{
byte[] tempContext = new byte[_context.Length];
for (int i = 0; i < tempContext.Length; i++)
{
tempContext[i] = _context[i];
}
return tempContext;
}
}
}
public ResultCode Result
{
get
{
return _result;
}
}
}
public class QuotaControl : DirectoryControl
{
private byte[] _sid = null;
public QuotaControl() : base("1.2.840.113556.1.4.1852", null, true, true) { }
public QuotaControl(SecurityIdentifier querySid) : this()
{
QuerySid = querySid;
}
public SecurityIdentifier QuerySid
{
get
{
if (_sid == null)
return null;
else
{
return new SecurityIdentifier(_sid, 0);
}
}
set
{
if (value == null)
_sid = null;
else
{
_sid = new byte[value.BinaryLength];
value.GetBinaryForm(_sid, 0);
}
}
}
public override byte[] GetValue()
{
this.directoryControlValue = BerConverter.Encode("{o}", new object[] { _sid });
return base.GetValue();
}
}
public class DirectoryControlCollection : CollectionBase
{
public DirectoryControlCollection()
{
}
public DirectoryControl this[int index]
{
get
{
return (DirectoryControl)List[index];
}
set
{
if (value == null)
throw new ArgumentNullException("value");
List[index] = value;
}
}
public int Add(DirectoryControl control)
{
if (control == null)
throw new ArgumentNullException("control");
return List.Add(control);
}
public void AddRange(DirectoryControl[] controls)
{
if (controls == null)
throw new ArgumentNullException("controls");
foreach (DirectoryControl c in controls)
{
if (c == null)
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.ContainNullControl), "controls");
}
}
InnerList.AddRange(controls);
}
public void AddRange(DirectoryControlCollection controlCollection)
{
if (controlCollection == null)
{
throw new ArgumentNullException("controlCollection");
}
int currentCount = controlCollection.Count;
for (int i = 0; i < currentCount; i = ((i) + (1)))
{
this.Add(controlCollection[i]);
}
}
public bool Contains(DirectoryControl value)
{
return List.Contains(value);
}
public void CopyTo(DirectoryControl[] array, int index)
{
List.CopyTo(array, index);
}
public int IndexOf(DirectoryControl value)
{
return List.IndexOf(value);
}
public void Insert(int index, DirectoryControl value)
{
if (value == null)
throw new ArgumentNullException("value");
List.Insert(index, value);
}
public void Remove(DirectoryControl value)
{
List.Remove(value);
}
protected override void OnValidate(Object value)
{
if (value == null) throw new ArgumentNullException("value");
if (!(value is DirectoryControl))
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidValueType, "DirectoryControl"), "value");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Xml.Linq;
namespace WixSharp.Controls
{
/// <summary>
/// Defines the association between an MSI dialog control and the <see cref="T:WixSharp.PublishingInfo" />.
/// </summary>
public class PublishingInfo : WixEntity
{
/// <summary>
/// Gets or sets the dialog Id.
/// </summary>
/// <value>
/// The dialog Id.
/// </value>
public string Dialog { get; set; }
/// <summary>
/// Gets or sets the control Id.
/// </summary>
/// <value>
/// The control Id.
/// </value>
public string Control { get; set; }
/// <summary>
/// The actions associated with the dialog control.
/// </summary>
public List<DialogAction> Actions = new List<DialogAction>();
}
/// <summary>
/// Defines <see cref="T:WixSharp.DialogAction"/> for showing MSI dialog.
/// </summary>
public class ShowDialog : DialogAction
{
/// <summary>
/// Initializes a new instance of the <see cref="ShowDialog"/> class.
/// </summary>
/// <param name="dialogName">Name of the dialog.</param>
/// <param name="condition">The condition.</param>
public ShowDialog(string dialogName, string condition = "1")
{
this.Name = ControlAction.NewDialog;
this.Condition = condition;
this.Value = dialogName;
}
/// <summary>
/// Initializes a new instance of the <see cref="ShowDialog"/> class.
/// </summary>
/// <param name="dialogName">Name of the dialog.</param>
/// <param name="condition">The condition.</param>
public ShowDialog(string dialogName, Condition condition)
{
this.Name = ControlAction.NewDialog;
this.Condition = condition.ToString();
this.Value = dialogName;
}
}
/// <summary>
/// Defines <see cref="T:WixSharp.DialogAction"/> for creating a child of a modal dialog box while keeping the present dialog box running.
/// </summary>
public class SpawnDialog : DialogAction
{
/// <summary>
/// Initializes a new instance of the <see cref="SpawnDialog"/> class.
/// </summary>
/// <param name="dialogName">Name of the dialog.</param>
/// <param name="condition">The condition.</param>
public SpawnDialog(string dialogName, string condition = "1")
{
this.Name = ControlAction.SpawnDialog;
this.Condition = condition;
this.Value = dialogName;
}
/// <summary>
/// Initializes a new instance of the <see cref="SpawnDialog"/> class.
/// </summary>
/// <param name="dialogName">Name of the dialog.</param>
/// <param name="condition">The condition.</param>
public SpawnDialog(string dialogName, Condition condition)
{
this.Name = ControlAction.SpawnDialog;
this.Condition = condition.ToString();
this.Value = dialogName;
}
}
/// <summary>
/// Defines <see cref="T:WixSharp.DialogAction"/> for executing MSI CustomAction ("DoAction").
/// </summary>
public class ExecuteCustomAction : DialogAction
{
/// <summary>
/// Initializes a new instance of the <see cref="ExecuteCustomAction"/> class.
/// </summary>
/// <param name="actionName">Name of the action.</param>
/// <param name="condition">The condition.</param>
public ExecuteCustomAction(string actionName, string condition = "1")
{
this.Name = "DoAction";
this.Condition = condition;
this.Value = actionName;
}
/// <summary>
/// Initializes a new instance of the <see cref="ExecuteCustomAction"/> class.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="condition">The condition.</param>
public ExecuteCustomAction(Action action, string condition = "1")
{
this.Name = "DoAction";
this.Condition = condition;
this.Value = action.Id;
}
}
/// <summary>
/// Defines "SetTargetPath" <see cref="T:WixSharp.DialogAction"/>.
/// </summary>
public class SetTargetPath : DialogAction
{
/// <summary>
/// Initializes a new instance of the <see cref="SetTargetPath"/> class.
/// </summary>
/// <param name="propertyValue">The property value. Default value is "[WIXUI_INSTALLDIR]".</param>
/// <param name="condition">The condition.</param>
public SetTargetPath(string propertyValue = "[WIXUI_INSTALLDIR]", string condition = "1")
{
this.Name = ControlAction.SetTargetPath.ToString();
this.Value = propertyValue;
this.Condition = condition;
}
}
/// <summary>
/// Defines <see cref="T:WixSharp.DialogAction"/> for setting property.
/// </summary>
public class SetProperty : DialogAction
{
/// <summary>
/// Initializes a new instance of the <see cref="SetProperty"/> class.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="propertyValue">The property value.</param>
/// <param name="condition">The condition.</param>
public SetProperty(string propertyName, string propertyValue, string condition = "1")
{
this.Property = propertyName;
this.Value = propertyValue;
this.Condition = condition;
}
}
/// <summary>
/// Defines custom UI control "Close Dialog" action.
/// </summary>
public class CloseDialog : DialogAction
{
/// <summary>
/// Initializes a new instance of the <see cref="T:WixSharp.CloseDialog"/> class.
/// </summary>
/// <param name="returnValue">The return value.</param>
/// <param name="condition">The condition.</param>
public CloseDialog(string returnValue = "Return", string condition = "1")
{
this.Value = returnValue;
this.Name = ControlAction.EndDialog.ToString();
this.Condition = condition;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:WixSharp.CloseDialog"/> class.
/// </summary>
/// <param name="returnValue">The return value.</param>
/// <param name="condition">The condition.</param>
public CloseDialog(string returnValue, Condition condition)
{
this.Value = returnValue;
this.Name = ControlAction.EndDialog.ToString();
this.Condition = condition.ToString();
}
}
/// <summary>
/// Defines custom UI control generic action.
/// </summary>
public class DialogAction : WixEntity
{
#pragma warning disable 1591
new public string Name;
public string Property;
public string Value;
public string Condition = "1";
public int? Order;
#pragma warning restore 1591
}
/// <summary>
/// Simple class that defines custom UI (WiX <c>UI</c> element). This is a specialized version of <see cref="T:WixSharp.CustomUI" /> class
/// designed to allow simple customization of the dialogs sequence without the introduction of any custom dialogs.
/// <example>The following is an example demonstrates how to skip <c>License Agreement</c> dialog,
/// which is otherwise displayed between <c>Welcome</c> and <c>InstallDir</c> dialogs.
/// <code>
/// project.CustomUI = new DialogSequence()
/// .On(Dialogs.WelcomeDlg, Buttons.Next, new ShowDialog(Dialogs.InstallDirDlg))
/// .On(Dialogs.InstallDirDlg, Buttons.Back, new ShowDialog(Dialogs.WelcomeDlg));
/// </code></example>
/// </summary>
public class DialogSequence : CustomUI
{
/// <summary>
/// Initializes a new instance of the <see cref="DialogSequence"/> class.
/// </summary>
public DialogSequence()
{
TextStyles.Clear();
DialogRefs.Clear();
Properties.Clear();
}
/// <summary>
/// Defines the WiX Dialog UI control Action (event handler).
/// <para>Note that all handlers will have <c>Order</c> field automatically assigned '5'
/// to ensure the overriding the default WiX event handlers</para>
/// </summary>
/// <param name="dialog">The dialog.</param>
/// <param name="control">The control.</param>
/// <param name="handlers">The handlers.</param>
/// <returns></returns>
public new DialogSequence On(string dialog, string control, params DialogAction[] handlers)
{
handlers.Where(h => !h.Order.HasValue)
.ForEach(h => h.Order = DefaultOrder);
base.On(dialog, control, handlers);
return this;
}
/// <summary>
/// The default value of the Order of the DialogAction. It is automatically assigned of handler doesn't have it set.
/// </summary>
static public int DefaultOrder = 5; //something high enough to have the highest priority at runtime
}
/// <summary>
/// Defines custom UI (WiX <c>UI</c> element). This class is to be used to define the customization of the standard MSI UI.
/// The usual scenario of the customization is the injection of the custom <see cref="T:WixSharp.Dialog"/>
/// into the sequence of the standard dialogs. This can be accomplished by defining the custom dialog as
/// <see cref="T:WixSharp.WixForm"/>. Such a <see cref="T:WixSharp.WixForm"/> can be edited with the Visual Studio form designer.
/// <para>
/// When <see cref="T:WixSharp.WixForm"/> is complete it can be converted into <see cref="T:WixSharp.Dialog"/>
/// with the <see cref="T:WixSharp.Dialog.ToWDialog"/>() call. And at compile time Wix# compiler converts
/// <see cref="T:WixSharp.Dialog"/> into the final WiX <c>UI</c> element XML definition.
/// </para>
/// <para>
/// While it is possible to construct <see cref="T:WixSharp.CustomUI"/> instance manually it is preferred to use
/// Factory methods of <see cref="T:WixSharp.CustomUIBuilder"/> (e.g. BuildPostLicenseDialogUI) for this.
/// </para>
/// <code>
/// project.UI = WUI.WixUI_Common;
/// project.CustomUI = CustomUIBuilder.BuildPostLicenseDialogUI(productActivationDialog,
/// onNextActions: new DialogAction[]{
/// new ExecueteCustomAction ("ValidateLicenceKey"),
/// new ShowDialog(Dialogs.InstallDirDlg, "SERIALNUMBER_VALIDATED = \"TRUE\"")});
/// </code>
/// </summary>
public class CustomUI : WixEntity
{
/// <summary>
/// The collection of PropertyId vs. PropertyValue pairs to be defined as the <c>Property</c> WiX elements inside of the <c>UI</c> element.
/// </summary>
public Dictionary<string, string> Properties = new Dictionary<string, string>()
{
{"DefaultUIFont", "WixUI_Font_Normal"},
{"WIXUI_INSTALLDIR", "INSTALLDIR"},
{"PIDTemplate", "####-####-####-####"},
{"ARPNOMODIFY", "1"}
};
/// <summary>
/// The collection of StyleId vs. Font pairs to be defined as the <c>TextStyle</c> WiX elements inside of the <c>UI</c> element.
/// </summary>
public Dictionary<string, Font> TextStyles = new Dictionary<string, Font>()
{
{"WixUI_Font_Normal", new Font("Tahoma", 8)},
{"WixUI_Font_Bigger", new Font("Tahoma", 12)},
{"WixUI_Font_Title", new Font("Tahoma", 9, FontStyle.Bold)}
};
/// <summary>
/// The collection of dialog IDs to be defined as the <c>DialogRef</c> WiX elements inside of the <c>UI</c> element.
/// By default it contains references to all MSI predefined dialogs.
/// </summary>
public List<string> DialogRefs = new List<string>(CommonDialogs.AllValues());
/// <summary>
/// The collection of <see cref="T:WixSharp.Dialog"/>s to be defined as the custom <c>Dialog</c> WiX elements inside of the <c>UI</c> element.
/// </summary>
public List<Dialog> CustomDialogs = new List<Dialog>();
/// <summary>
/// Defines UI sequence via collection of <see cref="T:WixSharp.PublishingInfo"/> items containing association between Dialog controls and MSI Dialog actions.
/// </summary>
public List<PublishingInfo> UISequence = new List<PublishingInfo>();
/// <summary>
/// Defines the WiX Dialog UI control Action (event handler).
/// <code>
/// customUI.On(Dialogs.WelcomeDlg, Buttons.Next, new ShowDialog(Dialogs.LicenseAgreementDlg));
/// </code>
/// </summary>
/// <param name="dialog">The dialog.</param>
/// <param name="control">The control.</param>
/// <param name="handlers">The handlers.</param>
/// <returns></returns>
public CustomUI On(string dialog, string control, params DialogAction[] handlers)
{
var actionInfo = UISequence.Where(x => x.Dialog == dialog && x.Control == control)
.Select(x => x)
.FirstOrDefault();
if (actionInfo == null)
{
UISequence.Add(actionInfo = new PublishingInfo
{
Dialog = dialog,
Control = control
});
}
actionInfo.Actions.AddRange(handlers);
return this;
}
/// <summary>
/// Defines the <see cref="T:WixSharp.Dialog" /> UI control Action (event handler).
/// <code>
/// customUI.On(activationDialog, Buttons.Cancel, new CloseDialog("Exit"));
/// </code>
/// </summary>
/// <param name="dialog">The dialog.</param>
/// <param name="control">The control.</param>
/// <param name="handlers">The handlers.</param>
/// <returns></returns>
public CustomUI On(Dialog dialog, string control, params DialogAction[] handlers)
{
return On(dialog.Id, control, handlers);
}
/// <summary>
/// Converts the <see cref="T:WixSharp.CustomUI"/> instance into WiX <see cref="T:System.Xml.Linq.XElement"/>.
/// </summary>
/// <returns><see cref="T:System.Xml.Linq.XElement"/> instance.</returns>
public virtual XElement ToXElement()
{
var ui = new XElement("UI")
.AddAttributes(this.Attributes);
foreach (string key in TextStyles.Keys)
{
var font = TextStyles[key];
var style = ui.AddElement(new XElement("TextStyle",
new XAttribute("Id", key),
// font.FontFamily.Name may be substituted by OS with the compatible font name
// font.OriginalFontName on the other hand warranties no substitution
new XAttribute("FaceName", font.OriginalFontName),
new XAttribute("Size", font.Size),
new XAttribute("Bold", font.Bold.ToYesNo()),
new XAttribute("Italic", font.Italic.ToYesNo()),
new XAttribute("Strike", font.Strikeout.ToYesNo()),
new XAttribute("Underline", font.Underline.ToYesNo())));
}
foreach (string key in Properties.Keys)
ui.Add(new XElement("Property",
new XAttribute("Id", key),
new XAttribute("Value", Properties[key])));
foreach (string dialogId in DialogRefs)
ui.Add(new XElement("DialogRef",
new XAttribute("Id", dialogId)));
foreach (PublishingInfo info in this.UISequence)
{
int index = 0;
foreach (DialogAction action in info.Actions)
{
index++;
var element = ui.AddElement(new XElement("Publish",
new XAttribute("Dialog", info.Dialog),
new XAttribute("Control", info.Control),
action.Condition));
Action<string, string> AddAttribute = (name, value) =>
{
if (!value.IsEmpty())
element.Add(new XAttribute(name, value));
};
AddAttribute("Event", action.Name);
AddAttribute("Value", action.Value);
AddAttribute("Property", action.Property);
if (action.Order.HasValue)
{
element.Add(new XAttribute("Order", action.Order.Value));
}
else if (info.Actions.Count > 1)
{
element.Add(new XAttribute("Order", index));
}
}
}
foreach (Dialog dialog in this.CustomDialogs)
{
ui.Add(dialog.ToXElement());
}
return ui;
}
}
/// <summary>
/// Class defining all <c>Publish</c> declarations associated with the <c>WixUI_Common</c> dialogs. This class is used as a starting point for
/// UI customization with injection of CLR Dialog (WinForms).
/// </summary>
public class CommomDialogsUI : CustomUI
{
/// <summary>
/// Initializes a new instance of the <see cref="CommomDialogsUI"/> class.
/// </summary>
public CommomDialogsUI()
{
On(NativeDialogs.WelcomeDlg, Buttons.Next, new ShowDialog(NativeDialogs.LicenseAgreementDlg));
On(NativeDialogs.LicenseAgreementDlg, Buttons.Back, new ShowDialog(NativeDialogs.WelcomeDlg));
On(NativeDialogs.LicenseAgreementDlg, Buttons.Next, new ShowDialog(NativeDialogs.InstallDirDlg));
On(NativeDialogs.InstallDirDlg, Buttons.Back, new ShowDialog(NativeDialogs.LicenseAgreementDlg));
On(NativeDialogs.InstallDirDlg, Buttons.Next, new SetTargetPath(),
new ShowDialog(NativeDialogs.CustomizeDlg));
On(NativeDialogs.InstallDirDlg, Buttons.ChangeFolder,
new SetProperty("_BrowseProperty", "[WIXUI_INSTALLDIR]"),
new SpawnDialog(CommonDialogs.BrowseDlg));
On(NativeDialogs.CustomizeDlg, Buttons.Back, new ShowDialog(NativeDialogs.InstallDirDlg));
On(NativeDialogs.CustomizeDlg, Buttons.Next, new ShowDialog(NativeDialogs.VerifyReadyDlg));
On(NativeDialogs.VerifyReadyDlg, Buttons.Back, new ShowDialog(NativeDialogs.InstallDirDlg, Condition.NOT_Installed),
new ShowDialog(NativeDialogs.MaintenanceTypeDlg, Condition.Installed));
On(NativeDialogs.MaintenanceWelcomeDlg, Buttons.Next, new ShowDialog(NativeDialogs.MaintenanceTypeDlg));
On(NativeDialogs.MaintenanceTypeDlg, Buttons.Back, new ShowDialog(NativeDialogs.MaintenanceWelcomeDlg));
On(NativeDialogs.MaintenanceTypeDlg, Buttons.Repair, new ShowDialog(NativeDialogs.VerifyReadyDlg));
On(NativeDialogs.MaintenanceTypeDlg, Buttons.Remove, new ShowDialog(NativeDialogs.VerifyReadyDlg));
On(NativeDialogs.ExitDialog, Buttons.Finish, new CloseDialog() { Order = 9999 });
}
}
/// <summary>
/// Defines values (names) for the WiX custom UI predefined dialog types.
/// </summary>
public class CommonDialogs
{
#pragma warning disable 1591
public const string BrowseDlg = "BrowseDlg";
public const string DiskCostDlg = "DiskCostDlg";
public const string ErrorDlg = "ErrorDlg";
public const string FatalError = "FatalError";
public const string FilesInUse = "FilesInUse";
public const string MsiRMFilesInUse = "MsiRMFilesInUse";
public const string PrepareDlg = "PrepareDlg";
public const string ProgressDlg = "ProgressDlg";
public const string ResumeDlg = "ResumeDlg";
public const string UserExit = "UserExit";
#pragma warning restore 1591
/// <summary>
/// Returns all WiX custom UI predefined dialog types.
/// </summary>
/// <returns>Array of dialog types.</returns>
static public string[] AllValues()
{
return Utils.AllConstStringValues<CommonDialogs>();
}
}
/// <summary>
/// Defines values (names) for the standard WiX dialogs.
/// </summary>
public class NativeDialogs
{
#pragma warning disable 1591
public const string WelcomeDlg = "WelcomeDlg";
public const string LicenseAgreementDlg = "LicenseAgreementDlg";
public const string InstallDirDlg = "InstallDirDlg";
/// <summary>
/// The customize features dialog
/// </summary>
public const string CustomizeDlg = "CustomizeDlg";
public const string VerifyReadyDlg = "VerifyReadyDlg";
public const string MaintenanceWelcomeDlg = "MaintenanceWelcomeDlg";
public const string MaintenanceTypeDlg = "MaintenanceTypeDlg";
public const string ExitDialog = "ExitDialog";
public const string DiskCostDlg = "DiskCostDlg";
#pragma warning restore 1591
}
/// <summary>
/// Predefined values for the <c>Control</c> actions.
/// </summary>
public class ControlActionData
{
#pragma warning disable 1591
public string Event;
public string Property;
public string Value;
public string Condition;
#pragma warning restore 1591
}
/// <summary>
/// Predefined WiX custom UI control (element) action types.
/// </summary>
public class ControlAction
{
#pragma warning disable 1591
public const string EndDialog = "EndDialog";
public const string NewDialog = "NewDialog";
public const string DoAction = "DoAction";
public const string SetTargetPath = "SetTargetPath";
public const string SpawnDialog = "SpawnDialog";
#pragma warning restore 1591
}
/// <summary>
/// Predefined values for the <c>EndDialog</c> action.
/// </summary>
public class EndDialogValue
{
#pragma warning disable 1591
public const string Exit = "Exit";
public const string Retry = "Retry";
public const string Ignore = "Ignore";
public const string Return = "Return";
#pragma warning restore 1591
}
/// <summary>
/// Defines values (names) for the WiX custom UI predefined buttons.
/// </summary>
public class Buttons
{
#pragma warning disable 1591
public const string Next = "Next";
public const string Back = "Back";
public const string Cancel = "Cancel";
public const string Finish = "Finish";
public const string ChangeFolder = "ChangeFolder";
public const string Repair = "RepairButton";
public const string Remove = "RemoveButton";
#pragma warning restore 1591
}
/// <summary>
/// The Factory class for building <see cref="T:WixSharp.CustomUI"/>.
/// <para>
/// While it is possible to construct instance manually it is preferred to use
/// Factory methods of <see cref="T:WixSharp.CustomUIBuilder"/> for this.
/// </para>
/// <code>
/// project.UI = WUI.WixUI_Common;
/// project.CustomUI = CustomUIBuilder.BuildPostLicenseDialogUI(productActivationDialog,
/// onNextActions: new DialogAction[]{
/// new ExecueteCustomAction ("ValidateLicenceKey"),
/// new ShowDialog(Dialogs.InstallDirDlg, "SERIALNUMBER_VALIDATED = \"TRUE\"")});
/// </code>
/// </summary>
public class CustomUIBuilder
{
/// <summary>
/// Builds <see cref="T:WixSharp.CustomUI"/> instance and injects <see cref="T:WixSharp.Dialog"/> into the standard UI sequence
/// just after <c>LicenceDialog</c> step.
/// </summary>
/// <param name="customDialog">The <see cref="T:WixSharp.Dialog"/> dialog to be injected.</param>
/// <param name="onNextActions">The on next actions.</param>
/// <param name="onBackActions">The on back actions.</param>
/// <param name="onCancelActions">The on cancel actions.</param>
/// <returns><see cref="T:WixSharp.CustomUI"/> instance.</returns>
public static CustomUI BuildPostLicenseDialogUI(Dialog customDialog,
DialogAction[] onNextActions = null,
DialogAction[] onBackActions = null,
DialogAction[] onCancelActions = null)
{
var customUI = new CustomUI();
customUI.CustomDialogs.Add(customDialog);
customUI.On(NativeDialogs.ExitDialog, Buttons.Finish, new CloseDialog() { Order = 9999 });
customUI.On(NativeDialogs.WelcomeDlg, Buttons.Next, new ShowDialog(NativeDialogs.LicenseAgreementDlg));
customUI.On(NativeDialogs.LicenseAgreementDlg, Buttons.Back, new ShowDialog(NativeDialogs.WelcomeDlg));
customUI.On(NativeDialogs.LicenseAgreementDlg, Buttons.Next, new ShowDialog(customDialog, "LicenseAccepted = \"1\""));
customUI.On(customDialog, Buttons.Back, onBackActions ?? new DialogAction[] { new ShowDialog(NativeDialogs.LicenseAgreementDlg) });
customUI.On(customDialog, Buttons.Next, onNextActions ?? new DialogAction[] { new ShowDialog(NativeDialogs.InstallDirDlg) });
customUI.On(customDialog, Buttons.Cancel, onCancelActions ?? new DialogAction[] { new CloseDialog("Exit") });
customUI.On(NativeDialogs.InstallDirDlg, Buttons.Back, new ShowDialog(customDialog));
customUI.On(NativeDialogs.InstallDirDlg, Buttons.Next, new SetTargetPath(),
new ShowDialog(NativeDialogs.VerifyReadyDlg));
customUI.On(NativeDialogs.InstallDirDlg, Buttons.ChangeFolder,
new SetProperty("_BrowseProperty", "[WIXUI_INSTALLDIR]"),
new ShowDialog(CommonDialogs.BrowseDlg));
customUI.On(NativeDialogs.VerifyReadyDlg, Buttons.Back, new ShowDialog(NativeDialogs.InstallDirDlg, Condition.NOT_Installed),
new ShowDialog(NativeDialogs.MaintenanceTypeDlg, Condition.Installed));
customUI.On(NativeDialogs.MaintenanceWelcomeDlg, Buttons.Next, new ShowDialog(NativeDialogs.MaintenanceTypeDlg));
customUI.On(NativeDialogs.MaintenanceTypeDlg, Buttons.Back, new ShowDialog(NativeDialogs.MaintenanceWelcomeDlg));
customUI.On(NativeDialogs.MaintenanceTypeDlg, Buttons.Repair, new ShowDialog(NativeDialogs.VerifyReadyDlg));
customUI.On(NativeDialogs.MaintenanceTypeDlg, Buttons.Remove, new ShowDialog(NativeDialogs.VerifyReadyDlg));
return customUI;
}
//public static CustomUI InjectClrDialogBetween(string showAction, string prevDialog, string nextDialog)
//{
// var customUI = new CommomDialogsUI();
// //disconnect prev and next dialogs
// customUI.UISequence.RemoveAll(x => (x.Dialog == prevDialog && x.Control == Buttons.Next) ||
// (x.Dialog == nextDialog && x.Control == Buttons.Back));
// //create new dialogs connection with showAction in between
// customUI.On(prevDialog, Buttons.Next, new ExecuteCustomAction(showAction));
// customUI.On(prevDialog, Buttons.Next, new ShowDialog(nextDialog, Condition.ClrDialog_NextPressed));
// customUI.On(prevDialog, Buttons.Next, new CloseDialog("Exit", Condition.ClrDialog_CancelPressed) { Order = 2 });
// customUI.On(nextDialog, Buttons.Back, new ExecuteCustomAction(showAction));
// customUI.On(nextDialog, Buttons.Back, new ShowDialog(prevDialog, Condition.ClrDialog_BackPressed));
// return customUI;
//}
//public static CustomUI InjectClrDialogBetween1(string showAction, string prevDialox, string nextDialog)
//{
// var customUI = new CustomUI();
// customUI.TextStyles.Clear();
// customUI.DialogRefs.Clear();
// customUI.Properties.Clear();
// customUI.On(prevDialox, Buttons.Next, new ExecueteCustomAction(showAction));
// customUI.On(prevDialox, Buttons.Next, new ShowDialog(nextDialog, "Custom_UI_Command = \"next\""));
// customUI.On(prevDialox, Buttons.Next, new CloseDialog("Exit", "Custom_UI_Command = \"abort\"") { Order = 2 });
// customUI.On(nextDialog, Buttons.Back, new ExecueteCustomAction(showAction));
// customUI.On(nextDialog, Buttons.Back, new ShowDialog(prevDialox, "Custom_UI_Command = \"back\""));
// return customUI;
//}
}
}
| |
// 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 ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ApplicationGatewaysOperations operations.
/// </summary>
public partial interface IApplicationGatewaysOperations
{
/// <summary>
/// Deletes the specified application gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </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 applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified application gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </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<ApplicationGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates the specified application gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update application gateway
/// 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<ApplicationGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all application gateways 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<ApplicationGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the application gateways 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<ApplicationGateway>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Starts the specified application gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </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> StartWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Stops the specified application gateway in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </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> StopWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the backend health of the specified application gateway in a
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='expand'>
/// Expands BackendAddressPool and BackendHttpSettings referenced in
/// backend health.
/// </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<ApplicationGatewayBackendHealth>> BackendHealthWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified application gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </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 applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates the specified application gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update application gateway
/// 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<ApplicationGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Starts the specified application gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </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> BeginStartWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Stops the specified application gateway in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </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> BeginStopWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the backend health of the specified application gateway in a
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='expand'>
/// Expands BackendAddressPool and BackendHttpSettings referenced in
/// backend health.
/// </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<ApplicationGatewayBackendHealth>> BeginBackendHealthWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all application gateways 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<ApplicationGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the application gateways 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<ApplicationGateway>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Net;
using Orleans.Runtime;
namespace Orleans.Serialization
{
/// <summary>
/// Type is a low level representation of grain reference keys to enable
/// space-efficient serialization of grain references.
/// </summary>
/// <remarks>
/// This type is not intended for general use. It's a highly specialized type
/// for serializing and deserializing grain references, and as such is not
/// generally something you should pass around in your application.
/// </remarks>
public readonly struct GrainReferenceKeyInfo
{
/// <summary>
/// Observer id. Only applicable if <see cref="HasObserverId"/> is true.
/// </summary>
/// <remarks>In most cases, is Guid.Empty.</remarks>
public Guid ObserverId { get; }
/// <summary>
/// Target silo. Only applicable if <see cref="HasTargetSilo"/> is true.
/// </summary>
/// <remarks>In most cases, is <c>(null, 0)</c>.</remarks>
public (IPEndPoint endpoint, int generation) TargetSilo { get; }
/// <summary>
/// Generic argument. Only applicable if <see cref="HasGenericArgument"/> is true.
/// </summary>
/// <remarks>In most cases, is <c>null</c>.</remarks>
public string GenericArgument { get; }
/// <summary>
/// Grain key. For more specialized views, see <c>KeyAs*</c> methods and <c>KeyFrom*</c>.
/// </summary>
public (ulong, ulong, ulong, string) Key { get; }
/// <summary>
/// Whether or not key info has observer id.
/// </summary>
public bool HasObserverId => ObserverId != Guid.Empty;
/// <summary>
/// Whether or not key info has silo endpoint.
/// </summary>
public bool HasTargetSilo => TargetSilo.endpoint != null;
/// <summary>
/// Whether or not key info has generic argument.
/// </summary>
public bool HasGenericArgument => GenericArgument != null;
/// <summary>
/// Whether or not key info has a long key.
/// </summary>
public bool IsLongKey => Key.Item1 == 0;
/// <summary>
/// Whether or not key info has key extension.
/// </summary>
public bool HasKeyExt
{
get
{
var category = UniqueKey.GetCategory(Key.Item3);
return category == UniqueKey.Category.KeyExtGrain
|| category == UniqueKey.Category.GeoClient; // geo clients use the KeyExt string to specify the cluster id
}
}
public (Guid key, ulong typeCode) KeyAsGuid()
{
if (HasKeyExt)
{
throw new InvalidOperationException("Key has string extension");
}
return (ToGuid(Key), Key.Item3);
}
public static (ulong, ulong, ulong, string) KeyFromGuid(Guid key, ulong typeCode)
{
var (n0, n1) = FromGuid(key);
return (n0, n1, typeCode, null);
}
public (Guid key, string ext, ulong typeCode) KeyAsGuidWithExt()
{
return (ToGuid(Key), Key.Item4, Key.Item3);
}
public static (ulong, ulong, ulong, string) KeyFromGuidWithExt(Guid key, string ext, ulong typeCode)
{
var (n0, n1) = FromGuid(key);
return (n0, n1, typeCode, ext);
}
public (long key, ulong typeCode) KeyAsLong()
{
if (HasKeyExt)
{
throw new InvalidOperationException("Key has string extension");
}
if (!IsLongKey)
{
throw new InvalidOperationException("Key is not a long key");
}
return (unchecked((long)Key.Item2), Key.Item3);
}
public static (ulong, ulong, ulong, string) KeyFromLong(long key, ulong typeCode)
{
var n1 = unchecked((ulong)key);
return (0, n1, typeCode, null);
}
public (long key, string ext, ulong typeCode) KeyAsLongWithExt()
{
if (!IsLongKey)
{
throw new InvalidOperationException("Key is not a long key");
}
return (unchecked((long)Key.Item2), Key.Item4, Key.Item3);
}
public static (ulong, ulong, ulong, string) KeyFromLongWithExt(long key, string ext, ulong typeCode)
{
var n1 = unchecked((ulong)key);
return (0, n1, typeCode, ext);
}
public (string key, ulong typeCode) KeyAsString()
{
if (Key.Item1 != 0 || Key.Item2 != 0)
{
throw new InvalidOperationException("Key is not a string key");
}
if (!HasKeyExt)
{
throw new InvalidOperationException("Key has no string extension");
}
return (Key.Item4, Key.Item3);
}
public static (ulong, ulong, ulong, string) KeyFromString(string key, ulong typeCode)
{
return KeyFromLongWithExt(0L, key, typeCode);
}
public GrainReferenceKeyInfo((ulong, ulong, ulong, string) key)
{
Key = key;
ObserverId = Guid.Empty;
TargetSilo = (null, 0);
GenericArgument = null;
}
public GrainReferenceKeyInfo((ulong, ulong, ulong, string) key, Guid observerId)
{
Key = key;
ObserverId = observerId;
TargetSilo = (null, 0);
GenericArgument = null;
}
public GrainReferenceKeyInfo((ulong, ulong, ulong, string) key, (IPEndPoint endpoint, int generation) targetSilo)
{
Key = key;
ObserverId = Guid.Empty;
TargetSilo = targetSilo;
GenericArgument = null;
}
public GrainReferenceKeyInfo((ulong, ulong, ulong, string) key, string genericArgument)
{
Key = key;
ObserverId = Guid.Empty;
TargetSilo = (null, 0);
GenericArgument = genericArgument;
}
private static Guid ToGuid((ulong n0, ulong n1, ulong, string) key) =>
new Guid(
(uint)(key.n0 & 0xffffffff),
(ushort)(key.n0 >> 32),
(ushort)(key.n0 >> 48),
(byte)key.n1,
(byte)(key.n1 >> 8),
(byte)(key.n1 >> 16),
(byte)(key.n1 >> 24),
(byte)(key.n1 >> 32),
(byte)(key.n1 >> 40),
(byte)(key.n1 >> 48),
(byte)(key.n1 >> 56));
private static (ulong, ulong) FromGuid(Guid guid)
{
var guidBytes = guid.ToByteArray();
var n0 = BitConverter.ToUInt64(guidBytes, 0);
var n1 = BitConverter.ToUInt64(guidBytes, 8);
return (n0, n1);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
using System.Diagnostics;
namespace System.Collections.Immutable.Tests
{
public abstract class ImmutableListTestBase : SimpleElementImmutablesTestBase
{
protected static readonly Func<IList, object, object> IndexOfFunc = (l, v) => l.IndexOf(v);
protected static readonly Func<IList, object, object> ContainsFunc = (l, v) => l.Contains(v);
protected static readonly Func<IList, object, object> RemoveFunc = (l, v) => { l.Remove(v); return l.Count; };
internal abstract IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list);
[Fact]
public void CopyToEmptyTest()
{
var array = new int[0];
this.GetListQuery(ImmutableList<int>.Empty).CopyTo(array);
this.GetListQuery(ImmutableList<int>.Empty).CopyTo(array, 0);
this.GetListQuery(ImmutableList<int>.Empty).CopyTo(0, array, 0, 0);
((ICollection)this.GetListQuery(ImmutableList<int>.Empty)).CopyTo(array, 0);
}
[Fact]
public void CopyToTest()
{
var listQuery = this.GetListQuery(ImmutableList.Create(1, 2));
var list = (IEnumerable<int>)listQuery;
var array = new int[2];
listQuery.CopyTo(array);
Assert.Equal(list, array);
array = new int[2];
listQuery.CopyTo(array, 0);
Assert.Equal(list, array);
array = new int[2];
listQuery.CopyTo(0, array, 0, listQuery.Count);
Assert.Equal(list, array);
array = new int[1]; // shorter than source length
listQuery.CopyTo(0, array, 0, array.Length);
Assert.Equal(list.Take(array.Length), array);
array = new int[3];
listQuery.CopyTo(1, array, 2, 1);
Assert.Equal(new[] { 0, 0, 2 }, array);
array = new int[2];
((ICollection)listQuery).CopyTo(array, 0);
Assert.Equal(list, array);
}
[Fact]
public void ForEachTest()
{
this.GetListQuery(ImmutableList<int>.Empty).ForEach(n => { throw new ShouldNotBeInvokedException(); });
var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 3));
var hitTest = new bool[list.Max() + 1];
this.GetListQuery(list).ForEach(i =>
{
Assert.False(hitTest[i]);
hitTest[i] = true;
});
for (int i = 0; i < hitTest.Length; i++)
{
Assert.Equal(list.Contains(i), hitTest[i]);
Assert.Equal(((IList)list).Contains(i), hitTest[i]);
}
}
[Fact]
public void ExistsTest()
{
Assert.False(this.GetListQuery(ImmutableList<int>.Empty).Exists(n => true));
var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 5));
Assert.True(this.GetListQuery(list).Exists(n => n == 3));
Assert.False(this.GetListQuery(list).Exists(n => n == 8));
}
[Fact]
public void FindAllTest()
{
Assert.True(this.GetListQuery(ImmutableList<int>.Empty).FindAll(n => true).IsEmpty);
var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 });
var actual = this.GetListQuery(list).FindAll(n => n % 2 == 1);
var expected = list.ToList().FindAll(n => n % 2 == 1);
Assert.Equal<int>(expected, actual.ToList());
}
[Fact]
public void FindTest()
{
Assert.Equal(0, this.GetListQuery(ImmutableList<int>.Empty).Find(n => true));
var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 });
Assert.Equal(3, this.GetListQuery(list).Find(n => (n % 2) == 1));
}
[Fact]
public void FindLastTest()
{
Assert.Equal(0, this.GetListQuery(ImmutableList<int>.Empty).FindLast(n => { throw new ShouldNotBeInvokedException(); }));
var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 });
Assert.Equal(5, this.GetListQuery(list).FindLast(n => (n % 2) == 1));
}
[Fact]
public void FindIndexTest()
{
Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(n => true));
Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(0, n => true));
Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(0, 0, n => true));
// Create a list with contents: 100,101,102,103,104,100,101,102,103,104
var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5)));
var bclList = list.ToList();
Assert.Equal(-1, this.GetListQuery(list).FindIndex(n => n == 6));
for (int idx = 0; idx < list.Count; idx++)
{
for (int count = 0; count <= list.Count - idx; count++)
{
foreach (int c in list)
{
int predicateInvocationCount = 0;
Predicate<int> match = n =>
{
predicateInvocationCount++;
return n == c;
};
int expected = bclList.FindIndex(idx, count, match);
int expectedInvocationCount = predicateInvocationCount;
predicateInvocationCount = 0;
int actual = this.GetListQuery(list).FindIndex(idx, count, match);
int actualInvocationCount = predicateInvocationCount;
Assert.Equal(expected, actual);
Assert.Equal(expectedInvocationCount, actualInvocationCount);
if (count == list.Count)
{
// Also test the FindIndex overload that takes no count parameter.
predicateInvocationCount = 0;
actual = this.GetListQuery(list).FindIndex(idx, match);
Assert.Equal(expected, actual);
Assert.Equal(expectedInvocationCount, actualInvocationCount);
if (idx == 0)
{
// Also test the FindIndex overload that takes no index parameter.
predicateInvocationCount = 0;
actual = this.GetListQuery(list).FindIndex(match);
Assert.Equal(expected, actual);
Assert.Equal(expectedInvocationCount, actualInvocationCount);
}
}
}
}
}
}
[Fact]
public void FindLastIndexTest()
{
Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(n => true));
Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(0, n => true));
Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(0, 0, n => true));
// Create a list with contents: 100,101,102,103,104,100,101,102,103,104
var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5)));
var bclList = list.ToList();
Assert.Equal(-1, this.GetListQuery(list).FindLastIndex(n => n == 6));
for (int idx = 0; idx < list.Count; idx++)
{
for (int count = 0; count <= idx + 1; count++)
{
foreach (int c in list)
{
int predicateInvocationCount = 0;
Predicate<int> match = n =>
{
predicateInvocationCount++;
return n == c;
};
int expected = bclList.FindLastIndex(idx, count, match);
int expectedInvocationCount = predicateInvocationCount;
predicateInvocationCount = 0;
int actual = this.GetListQuery(list).FindLastIndex(idx, count, match);
int actualInvocationCount = predicateInvocationCount;
Assert.Equal(expected, actual);
Assert.Equal(expectedInvocationCount, actualInvocationCount);
if (count == list.Count)
{
// Also test the FindIndex overload that takes no count parameter.
predicateInvocationCount = 0;
actual = this.GetListQuery(list).FindLastIndex(idx, match);
Assert.Equal(expected, actual);
Assert.Equal(expectedInvocationCount, actualInvocationCount);
if (idx == list.Count - 1)
{
// Also test the FindIndex overload that takes no index parameter.
predicateInvocationCount = 0;
actual = this.GetListQuery(list).FindLastIndex(match);
Assert.Equal(expected, actual);
Assert.Equal(expectedInvocationCount, actualInvocationCount);
}
}
}
}
}
}
[Fact]
public void IList_IndexOf_NullArgument()
{
this.AssertIListBaseline(IndexOfFunc, 1, null);
this.AssertIListBaseline(IndexOfFunc, "item", null);
this.AssertIListBaseline(IndexOfFunc, new int?(1), null);
this.AssertIListBaseline(IndexOfFunc, new int?(), null);
}
[Fact]
public void IList_IndexOf_ArgTypeMismatch()
{
this.AssertIListBaseline(IndexOfFunc, "first item", new object());
this.AssertIListBaseline(IndexOfFunc, 1, 1.0);
this.AssertIListBaseline(IndexOfFunc, new int?(1), 1);
this.AssertIListBaseline(IndexOfFunc, new int?(1), new int?(1));
this.AssertIListBaseline(IndexOfFunc, new int?(1), string.Empty);
}
[Fact]
public void IList_IndexOf_EqualsOverride()
{
this.AssertIListBaseline(IndexOfFunc, new ProgrammaticEquals(v => v is string), "foo");
this.AssertIListBaseline(IndexOfFunc, new ProgrammaticEquals(v => v is string), 3);
}
[Fact]
public void IList_Contains_NullArgument()
{
this.AssertIListBaseline(ContainsFunc, 1, null);
this.AssertIListBaseline(ContainsFunc, "item", null);
this.AssertIListBaseline(ContainsFunc, new int?(1), null);
this.AssertIListBaseline(ContainsFunc, new int?(), null);
}
[Fact]
public void IList_Contains_ArgTypeMismatch()
{
this.AssertIListBaseline(ContainsFunc, "first item", new object());
this.AssertIListBaseline(ContainsFunc, 1, 1.0);
this.AssertIListBaseline(ContainsFunc, new int?(1), 1);
this.AssertIListBaseline(ContainsFunc, new int?(1), new int?(1));
this.AssertIListBaseline(ContainsFunc, new int?(1), string.Empty);
}
[Fact]
public void IList_Contains_EqualsOverride()
{
this.AssertIListBaseline(ContainsFunc, new ProgrammaticEquals(v => v is string), "foo");
this.AssertIListBaseline(ContainsFunc, new ProgrammaticEquals(v => v is string), 3);
}
[Fact]
public void ConvertAllTest()
{
Assert.True(this.GetListQuery(ImmutableList<int>.Empty).ConvertAll<float>(n => n).IsEmpty);
var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10));
Func<int, double> converter = n => 2.0 * n;
var expected = list.ToList().Select(converter).ToList();
var actual = this.GetListQuery(list).ConvertAll(converter);
Assert.Equal<double>(expected.ToList(), actual.ToList());
}
[Fact]
public void GetRangeTest()
{
Assert.True(this.GetListQuery(ImmutableList<int>.Empty).GetRange(0, 0).IsEmpty);
var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10));
var bclList = list.ToList();
for (int index = 0; index < list.Count; index++)
{
for (int count = 0; count < list.Count - index; count++)
{
var expected = bclList.GetRange(index, count);
var actual = this.GetListQuery(list).GetRange(index, count);
Assert.Equal<int>(expected.ToList(), actual.ToList());
}
}
}
[Fact]
public void TrueForAllTest()
{
Assert.True(this.GetListQuery(ImmutableList<int>.Empty).TrueForAll(n => false));
var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10));
this.TrueForAllTestHelper(list, n => n % 2 == 0);
this.TrueForAllTestHelper(list, n => n % 2 == 1);
this.TrueForAllTestHelper(list, n => true);
}
[Fact]
public void RemoveAllTest()
{
var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10));
this.RemoveAllTestHelper(list, n => false);
this.RemoveAllTestHelper(list, n => true);
this.RemoveAllTestHelper(list, n => n < 7);
this.RemoveAllTestHelper(list, n => n > 7);
this.RemoveAllTestHelper(list, n => n == 7);
}
[Fact]
public void ReverseTest()
{
var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10));
for (int i = 0; i < list.Count; i++)
{
for (int j = 0; j < list.Count - i; j++)
{
this.ReverseTestHelper(list, i, j);
}
}
}
[Fact]
public void Sort_NullComparison_Throws()
{
Assert.Throws<ArgumentNullException>(() => this.SortTestHelper(ImmutableList<int>.Empty, (Comparison<int>)null));
}
[Fact]
public void SortTest()
{
var scenarios = new[] {
ImmutableList<int>.Empty,
ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 50)),
ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 50).Reverse()),
};
foreach (var scenario in scenarios)
{
var expected = scenario.ToList();
expected.Sort();
var actual = this.SortTestHelper(scenario);
Assert.Equal<int>(expected, actual);
expected = scenario.ToList();
Comparison<int> comparison = (x, y) => x > y ? 1 : (x < y ? -1 : 0);
expected.Sort(comparison);
actual = this.SortTestHelper(scenario, comparison);
Assert.Equal<int>(expected, actual);
expected = scenario.ToList();
IComparer<int> comparer = null;
expected.Sort(comparer);
actual = this.SortTestHelper(scenario, comparer);
Assert.Equal<int>(expected, actual);
expected = scenario.ToList();
comparer = Comparer<int>.Create(comparison);
expected.Sort(comparer);
actual = this.SortTestHelper(scenario, comparer);
Assert.Equal<int>(expected, actual);
for (int i = 0; i < scenario.Count; i++)
{
for (int j = 0; j < scenario.Count - i; j++)
{
expected = scenario.ToList();
comparer = null;
expected.Sort(i, j, comparer);
actual = this.SortTestHelper(scenario, i, j, comparer);
Assert.Equal<int>(expected, actual);
}
}
}
}
[Fact]
public void BinarySearch()
{
var basis = new List<int>(Enumerable.Range(1, 50).Select(n => n * 2));
var query = this.GetListQuery(basis.ToImmutableList());
for (int value = basis.First() - 1; value <= basis.Last() + 1; value++)
{
int expected = basis.BinarySearch(value);
int actual = query.BinarySearch(value);
if (expected != actual) Debugger.Break();
Assert.Equal(expected, actual);
for (int index = 0; index < basis.Count - 1; index++)
{
for (int count = 0; count <= basis.Count - index; count++)
{
expected = basis.BinarySearch(index, count, value, null);
actual = query.BinarySearch(index, count, value, null);
if (expected != actual) Debugger.Break();
Assert.Equal(expected, actual);
}
}
}
}
[Fact]
public void BinarySearchPartialSortedList()
{
var reverseSorted = ImmutableArray.CreateRange(Enumerable.Range(1, 150).Select(n => n * 2).Reverse());
this.BinarySearchPartialSortedListHelper(reverseSorted, 0, 50);
this.BinarySearchPartialSortedListHelper(reverseSorted, 50, 50);
this.BinarySearchPartialSortedListHelper(reverseSorted, 100, 50);
}
private void BinarySearchPartialSortedListHelper(ImmutableArray<int> inputData, int sortedIndex, int sortedLength)
{
Requires.Range(sortedIndex >= 0, "sortedIndex");
Requires.Range(sortedLength > 0, "sortedLength");
inputData = inputData.Sort(sortedIndex, sortedLength, Comparer<int>.Default);
int min = inputData[sortedIndex];
int max = inputData[sortedIndex + sortedLength - 1];
var basis = new List<int>(inputData);
var query = this.GetListQuery(inputData.ToImmutableList());
for (int value = min - 1; value <= max + 1; value++)
{
for (int index = sortedIndex; index < sortedIndex + sortedLength; index++) // make sure the index we pass in is always within the sorted range in the list.
{
for (int count = 0; count <= sortedLength - index; count++)
{
int expected = basis.BinarySearch(index, count, value, null);
int actual = query.BinarySearch(index, count, value, null);
if (expected != actual) Debugger.Break();
Assert.Equal(expected, actual);
}
}
}
}
[Fact]
public void SyncRoot()
{
var collection = (ICollection)this.GetEnumerableOf<int>();
Assert.NotNull(collection.SyncRoot);
Assert.Same(collection.SyncRoot, collection.SyncRoot);
}
[Fact]
public void GetEnumeratorTest()
{
var enumerable = this.GetEnumerableOf(1);
Assert.Equal(new[] { 1 }, enumerable.ToList()); // exercises the enumerator
IEnumerable enumerableNonGeneric = enumerable;
Assert.Equal(new[] { 1 }, enumerableNonGeneric.Cast<int>().ToList()); // exercises the enumerator
}
protected abstract void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test);
protected abstract void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count);
protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list);
protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison);
protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer);
protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer);
protected void AssertIListBaselineBothDirections<T1, T2>(Func<IList, object, object> operation, T1 item, T2 other)
{
this.AssertIListBaseline(operation, item, other);
this.AssertIListBaseline(operation, other, item);
}
/// <summary>
/// Asserts that the <see cref="ImmutableList{T}"/> or <see cref="ImmutableList{T}.Builder"/>'s
/// implementation of <see cref="IList"/> behave the same way <see cref="List{T}"/> does.
/// </summary>
/// <typeparam name="T">The type of the element for one collection to test with.</typeparam>
/// <param name="operation">
/// The <see cref="IList"/> operation to perform.
/// The function is provided with the <see cref="IList"/> implementation to test
/// and the item to use as the argument to the operation.
/// The function should return some equatable value by which to compare the effects
/// of the operation across <see cref="IList"/> implementations.
/// </param>
/// <param name="item">The item to add to the collection.</param>
/// <param name="other">The item to pass to the <paramref name="operation"/> function as the second parameter.</param>
protected void AssertIListBaseline<T>(Func<IList, object, object> operation, T item, object other)
{
IList bclList = new List<T> { item };
IList testedList = (IList)this.GetListQuery(ImmutableList.Create(item));
object expected = operation(bclList, other);
object actual = operation(testedList, other);
Assert.Equal(expected, actual);
}
private void TrueForAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test)
{
var bclList = list.ToList();
var expected = bclList.TrueForAll(test);
var actual = this.GetListQuery(list).TrueForAll(test);
Assert.Equal(expected, actual);
}
protected class ProgrammaticEquals
{
private readonly Func<object, bool> equalsCallback;
internal ProgrammaticEquals(Func<object, bool> equalsCallback)
{
this.equalsCallback = equalsCallback;
}
public override bool Equals(object obj)
{
return this.equalsCallback(obj);
}
public override int GetHashCode()
{
throw new NotImplementedException();
}
}
}
}
| |
#region Copyright & License
// This is a modified copy of a file in the Apache Log4Net project.
// The primary change was to the namespace.
// The remainder of this comment is taken verbatim from the original Apache file.
//
// Copyright 2001-2005 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.IO;
namespace TracerX {
/// <summary>
/// This static class maps object types to <see cref="IObjectRenderer"/>s that render objects of each registered
/// type as strings for logging.
/// </summary>
/// <remarks>
/// <para>
/// Maintains a mapping between types that require special
/// rendering and the <see cref="IObjectRenderer"/> that
/// is used to render them. Users should implement IObjectRenderer as required
/// for types where ToString() is insufficient and add the IObjectRenderer objects
/// to the RendererMap.
/// </para>
/// <para>
/// The <see cref="FindAndRender(object)"/> method is called by TracerX to render an
/// <c>object</c> using the appropriate renderers defined in this map.
/// </para>
/// </remarks>
public static class RendererMap {
#region Member Variables
private static System.Collections.Hashtable m_map;
private static System.Collections.Hashtable m_cache = new System.Collections.Hashtable();
private static IObjectRenderer s_defaultRenderer = new DefaultRenderer();
#endregion
#region Constructors
static RendererMap() {
m_map = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
Put(typeof(System.Exception), new ExceptionRenderer());
}
#endregion
/// <summary>
/// Render <paramref name="obj"/> using the appropriate renderer.
/// </summary>
/// <param name="obj">the object to render to a string</param>
/// <returns>the object rendered as a string</returns>
/// <remarks>
/// <para>
/// This is a convenience method used to render an object to a string.
/// The alternative method <see cref="FindAndRender(object,TextWriter)"/>
/// should be used when streaming output to a <see cref="TextWriter"/>.
/// </para>
/// </remarks>
public static string FindAndRender(object obj) {
// Optimization for strings
string strData = obj as String;
if (strData != null) {
return strData;
}
StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
FindAndRender(obj, stringWriter);
return stringWriter.ToString();
}
/// <summary>
/// Render <paramref name="obj"/> using the appropriate renderer.
/// </summary>
/// <param name="obj">the object to render to a string</param>
/// <param name="writer">The writer to render to</param>
/// <remarks>
/// <para>
/// Find the appropriate renderer for the type of the
/// <paramref name="obj"/> parameter. This is accomplished by calling the
/// <see cref="Get(Type)"/> method. Once a renderer is found, it is
/// applied on the object <paramref name="obj"/> and the result is returned
/// as a <see cref="string"/>.
/// </para>
/// </remarks>
public static void FindAndRender(object obj, TextWriter writer) {
if (obj == null) {
writer.Write("<null>");
} else {
// Optimization for strings
string str = obj as string;
if (str != null) {
writer.Write(str);
} else {
// Lookup the renderer for the specific type
try {
Get(obj.GetType()).RenderObject(obj, writer);
} catch (Exception ex) {
// return default message
string objectTypeName = "";
if (obj != null && obj.GetType() != null) {
objectTypeName = obj.GetType().FullName;
}
writer.Write("<TracerX.Error>Exception rendering object type [" + objectTypeName + "]");
if (ex != null) {
string exceptionText = null;
try {
exceptionText = ex.ToString();
} catch {
// Ignore exception
}
writer.Write("<stackTrace>" + exceptionText + "</stackTrace>");
}
writer.Write("</TracerX.Error>");
}
}
}
}
/// <summary>
/// Gets the renderer for the specified object type
/// </summary>
/// <param name="obj">the object to lookup the renderer for</param>
/// <returns>the renderer for <paramref name="obj"/></returns>
/// <remarks>
/// <param>
/// Gets the renderer for the specified object type.
/// </param>
/// <param>
/// Syntactic sugar method that calls <see cref="Get(Type)"/>
/// with the type of the object parameter.
/// </param>
/// </remarks>
public static IObjectRenderer Get(Object obj) {
if (obj == null) {
return null;
} else {
return Get(obj.GetType());
}
}
/// <summary>
/// Gets the renderer for the specified type
/// </summary>
/// <param name="type">the type to lookup the renderer for</param>
/// <returns>the renderer for the specified type</returns>
/// <remarks>
/// <para>
/// Returns the renderer for the specified type.
/// If no specific renderer has been defined the
/// <see cref="DefaultRenderer"/> will be returned.
/// </para>
/// </remarks>
public static IObjectRenderer Get(Type type) {
if (type == null) {
throw new ArgumentNullException("type");
}
IObjectRenderer result = null;
// Check cache
result = (IObjectRenderer)m_cache[type];
if (result == null) {
for (Type cur = type; cur != null; cur = cur.BaseType) {
// Search the type's interfaces
result = SearchTypeAndInterfaces(cur);
if (result != null) {
break;
}
}
// if not set then use the default renderer
if (result == null) {
result = s_defaultRenderer;
}
// Add to cache
m_cache[type] = result;
}
return result;
}
/// <summary>
/// Internal function to recursively search interfaces
/// </summary>
/// <param name="type">the type to lookup the renderer for</param>
/// <returns>the renderer for the specified type</returns>
private static IObjectRenderer SearchTypeAndInterfaces(Type type) {
IObjectRenderer r = (IObjectRenderer)m_map[type];
if (r != null) {
return r;
} else {
foreach (Type t in type.GetInterfaces()) {
r = SearchTypeAndInterfaces(t);
if (r != null) {
return r;
}
}
}
return null;
}
/// <summary>
/// Get the default renderer instance
/// </summary>
/// <value>the default renderer</value>
/// <remarks>
/// <para>
/// Get the default renderer
/// </para>
/// </remarks>
public static IObjectRenderer DefaultRenderer {
get { return s_defaultRenderer; }
}
/// <summary>
/// Clear the map of renderers
/// </summary>
/// <remarks>
/// <para>
/// Clear the custom renderers defined by using
/// <see cref="Put"/>. The <see cref="DefaultRenderer"/>
/// cannot be removed.
/// </para>
/// </remarks>
public static void Clear() {
m_map.Clear();
m_cache.Clear();
}
/// <summary>
/// Register an <see cref="IObjectRenderer"/> for <paramref name="typeToRender"/>.
/// </summary>
/// <param name="typeToRender">the type that will be rendered by <paramref name="renderer"/></param>
/// <param name="renderer">the renderer for <paramref name="typeToRender"/></param>
/// <remarks>
/// <para>
/// Register an object renderer for a specific source type.
/// This renderer will be returned from a call to <see cref="Get(Type)"/>
/// specifying the same <paramref name="typeToRender"/> as an argument.
/// </para>
/// </remarks>
public static void Put(Type typeToRender, IObjectRenderer renderer) {
m_cache.Clear();
if (typeToRender == null) {
throw new ArgumentNullException("typeToRender");
}
if (renderer == null) {
throw new ArgumentNullException("renderer");
}
m_map[typeToRender] = renderer;
}
}
}
| |
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Data;
using NServiceKit.Common.Utils;
using NServiceKit.DataAnnotations;
using NServiceKit.Common;
using System.Reflection;
using NServiceKit.OrmLite;
using NServiceKit.OrmLite.Oracle;
namespace TestExpressions
{
/// <summary>An author.</summary>
public class Author{
/// <summary>Initializes a new instance of the TestExpressions.Author class.</summary>
public Author(){}
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
[AutoIncrement]
[Alias("AuthorID")]
public Int32 Id { get; set;}
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
[Index(Unique = true)]
[StringLength(40)]
public string Name { get; set;}
/// <summary>Gets or sets the Date/Time of the birthday.</summary>
/// <value>The birthday.</value>
public DateTime Birthday { get; set;}
/// <summary>Gets or sets the Date/Time of the last activity.</summary>
/// <value>The last activity.</value>
public DateTime ? LastActivity { get; set;}
/// <summary>Gets or sets the earnings.</summary>
/// <value>The earnings.</value>
public Decimal? Earnings { get; set;}
/// <summary>Gets or sets a value indicating whether the active.</summary>
/// <value>true if active, false if not.</value>
public bool Active { get; set; }
/// <summary>Gets or sets the city.</summary>
/// <value>The city.</value>
[StringLength(80)]
[Alias("JobCity")]
public string City { get; set;}
/// <summary>Gets or sets the comments.</summary>
/// <value>The comments.</value>
[StringLength(80)]
[Alias("Comment")]
public string Comments { get; set;}
/// <summary>Gets or sets the rate.</summary>
/// <value>The rate.</value>
public Int16 Rate{ get; set;}
}
/// <summary>A main class.</summary>
class MainClass
{
/// <summary>Main entry-point for this application.</summary>
/// <param name="args">Array of command-line argument strings.</param>
public static void Main (string[] args)
{
Console.WriteLine ("Hello World!");
OrmLiteConfig.DialectProvider = new OracleOrmLiteDialectProvider();
SqlExpressionVisitor<Author> ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<Author>();
using (IDbConnection db =
"Data Source=x;User Id=x;Password=x;".OpenDbConnection())
{
db.DropTable<Author>();
db.CreateTable<Author>();
db.DeleteAll<Author>();
List<Author> authors = new List<Author>();
authors.Add(new Author(){Name="Demis Bellot",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 99.9m,Comments="CSharp books", Rate=10, City="London"});
authors.Add(new Author(){Name="Angel Colmenares",Birthday= DateTime.Today.AddYears(-25),Active=true,Earnings= 50.0m,Comments="CSharp books", Rate=5, City="Bogota"});
authors.Add(new Author(){Name="Adam Witco",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 80.0m,Comments="Math Books", Rate=9, City="London"});
authors.Add(new Author(){Name="Claudia Espinel",Birthday= DateTime.Today.AddYears(-23),Active=true,Earnings= 60.0m,Comments="Cooking books", Rate=10, City="Bogota"});
authors.Add(new Author(){Name="Libardo Pajaro",Birthday= DateTime.Today.AddYears(-25),Active=true,Earnings= 80.0m,Comments="CSharp books", Rate=9, City="Bogota"});
authors.Add(new Author(){Name="Jorge Garzon",Birthday= DateTime.Today.AddYears(-28),Active=true,Earnings= 70.0m,Comments="CSharp books", Rate=9, City="Bogota"});
authors.Add(new Author(){Name="Alejandro Isaza",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 70.0m,Comments="Java books", Rate=0, City="Bogota"});
authors.Add(new Author(){Name="Wilmer Agamez",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 30.0m,Comments="Java books", Rate=0, City="Cartagena"});
authors.Add(new Author(){Name="Rodger Contreras",Birthday= DateTime.Today.AddYears(-25),Active=true,Earnings= 90.0m,Comments="CSharp books", Rate=8, City="Cartagena"});
authors.Add(new Author(){Name="Chuck Benedict",Birthday= DateTime.Today.AddYears(-22),Active=true,Earnings= 85.5m,Comments="CSharp books", Rate=8, City="London"});
authors.Add(new Author(){Name="James Benedict II",Birthday= DateTime.Today.AddYears(-22),Active=true,Earnings= 85.5m,Comments="Java books", Rate=5, City="Berlin"});
authors.Add(new Author(){Name="Ethan Brown",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 45.0m,Comments="CSharp books", Rate=5, City="Madrid"});
authors.Add(new Author(){Name="Xavi Garzon",Birthday= DateTime.Today.AddYears(-22),Active=true,Earnings= 75.0m,Comments="CSharp books", Rate=9, City="Madrid"});
authors.Add(new Author(){Name="Luis garzon",Birthday= DateTime.Today.AddYears(-22),Active=true,Earnings= 85.0m,Comments="CSharp books", Rate=10, City="Mexico"});
db.InsertAll(authors);
// lets start !
// select authors born 20 year ago
int year = DateTime.Today.AddYears(-20).Year;
int expected=5;
ev.Where(rn=> rn.Birthday>=new DateTime(year, 1,1) && rn.Birthday<=new DateTime(year, 12,31));
List<Author> result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
result = db.Select<Author>(qry => qry.Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= new DateTime(year, 12, 31)));
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count);
result = db.Select<Author>(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= new DateTime(year, 12, 31));
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count);
// select authors from London, Berlin and Madrid : 6
expected=6;
//Sql.In can take params object[]
ev.Where(rn=> Sql.In( rn.City, new object[]{"London", "Madrid", "Berlin"}) );
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors from Bogota and Cartagena : 7
expected=7;
//... or Sql.In can take IList<Object>
List<Object> cities= new List<Object>();
cities.Add("Bogota");
cities.Add("Cartagena");
ev.Where(rn => Sql.In(rn.City, cities ));
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors which name starts with A
expected=3;
ev.Where(rn=> rn.Name.StartsWith("A") );
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors which name ends with Garzon o GARZON o garzon ( no case sensitive )
expected=3;
ev.Where(rn=> rn.Name.ToUpper().EndsWith("GARZON") );
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors which name ends with garzon ( no case sensitive )
expected=3;
ev.Where(rn=> rn.Name.EndsWith("garzon") );
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors which name contains Benedict
expected=2;
ev.Where(rn=> rn.Name.Contains("Benedict") );
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors with Earnings <= 50
expected=3;
ev.Where(rn=> rn.Earnings<=50 );
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors with Rate = 10 and city=Mexio
expected=1;
ev.Where(rn=> rn.Rate==10 && rn.City=="Mexico");
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// enough selecting, lets update;
// set Active=false where rate =0
expected=2;
ev.Where(rn=> rn.Rate==0 ).Update(rn=> rn.Active);
var rows = db.UpdateOnly( new Author(){ Active=false }, ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, rows, expected==rows);
// insert values only in Id, Name, Birthday, Rate and Active fields
expected=4;
ev.Insert(rn =>new { rn.Id, rn.Name, rn.Birthday, rn.Active, rn.Rate} );
db.InsertOnly( new Author(){Active=false, Rate=0, Name="Victor Grozny", Birthday=DateTime.Today.AddYears(-18) }, ev);
db.InsertOnly( new Author(){Active=false, Rate=0, Name="Ivan Chorny", Birthday=DateTime.Today.AddYears(-19) }, ev);
ev.Where(rn=> !rn.Active);
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
//update comment for City == null
expected=2;
ev.Where( rn => rn.City==null ).Update(rn=> rn.Comments);
rows=db.UpdateOnly(new Author(){Comments="No comments"}, ev);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, rows, expected==rows);
// delete where City is null
expected=2;
rows = db.Delete( ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, rows, expected==rows);
// lets select all records ordered by Rate Descending and Name Ascending
expected=14;
ev.Where().OrderBy(rn=> new{ at=Sql.Desc(rn.Rate), rn.Name }); // clear where condition
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
Console.WriteLine(ev.OrderByExpression);
var author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Claudia Espinel", author.Name, "Claudia Espinel"==author.Name);
// select only first 5 rows ....
expected=5;
ev.Limit(5); // note: order is the same as in the last sentence
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// lets select only Name and City (name will be "UPPERCASED" )
ev.Select(rn=> new { at= Sql.As( rn.Name.ToUpper(), "Name" ), rn.City} );
Console.WriteLine(ev.SelectExpression);
result=db.Select(ev);
author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper()==author.Name);
//paging :
ev.Limit(0,4);// first page, page size=4;
result=db.Select(ev);
author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper()==author.Name);
ev.Limit(4,4);// second page
result=db.Select(ev);
author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Jorge Garzon".ToUpper(), author.Name, "Jorge Garzon".ToUpper()==author.Name);
ev.Limit(8,4);// third page
result=db.Select(ev);
author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Rodger Contreras".ToUpper(), author.Name, "Rodger Contreras".ToUpper()==author.Name);
// select distinct..
ev.Limit(); // clear limit
ev.SelectDistinct(r=>r.City).OrderBy();
expected=6;
result=db.Select(ev);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
Console.ReadLine();
Console.WriteLine("Press Enter to continue");
}
Console.WriteLine ("This is The End my friend!");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
using System.Threading;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation
{
internal class Signature : ISignature
{
private const int MaxParamColumnCount = 100;
private readonly SignatureHelpItem _signatureHelpItem;
public Signature(ITrackingSpan applicableToSpan, SignatureHelpItem signatureHelpItem, int selectedParameterIndex)
{
if (selectedParameterIndex < -1 || selectedParameterIndex >= signatureHelpItem.Parameters.Length)
{
throw new ArgumentOutOfRangeException(nameof(selectedParameterIndex));
}
this.ApplicableToSpan = applicableToSpan;
_signatureHelpItem = signatureHelpItem;
_parameterIndex = selectedParameterIndex;
}
private bool _isInitialized;
private void EnsureInitialized()
{
if (!_isInitialized)
{
_isInitialized = true;
Initialize();
}
}
private Signature InitializedThis
{
get
{
EnsureInitialized();
return this;
}
}
private IList<SymbolDisplayPart> _displayParts;
internal IList<SymbolDisplayPart> DisplayParts => InitializedThis._displayParts;
public ITrackingSpan ApplicableToSpan { get; }
private string _content;
public string Content => InitializedThis._content;
private int _parameterIndex = -1;
public IParameter CurrentParameter
{
get
{
EnsureInitialized();
return _parameterIndex >= 0 && _parameters != null ? _parameters[_parameterIndex] : null;
}
}
public string Documentation => null;
private ReadOnlyCollection<IParameter> _parameters;
public ReadOnlyCollection<IParameter> Parameters => InitializedThis._parameters;
private string _prettyPrintedContent;
public string PrettyPrintedContent => InitializedThis._prettyPrintedContent;
// This event is required by the ISignature interface but it's not actually used
// (once created the CurrentParameter property cannot change)
public event EventHandler<CurrentParameterChangedEventArgs> CurrentParameterChanged
{
add
{
}
remove
{
}
}
private IList<SymbolDisplayPart> _prettyPrintedDisplayParts;
internal IList<SymbolDisplayPart> PrettyPrintedDisplayParts
{
get
{
return InitializedThis._prettyPrintedDisplayParts;
}
set
{
_prettyPrintedDisplayParts = value;
}
}
private void Initialize()
{
var content = new StringBuilder();
var prettyPrintedContent = new StringBuilder();
var parts = new List<SymbolDisplayPart>();
var prettyPrintedParts = new List<SymbolDisplayPart>();
var parameters = new List<IParameter>();
var signaturePrefixParts = _signatureHelpItem.PrefixDisplayParts;
var signaturePrefixContent = _signatureHelpItem.PrefixDisplayParts.GetFullText();
AddRange(signaturePrefixParts, parts, prettyPrintedParts);
Append(signaturePrefixContent, content, prettyPrintedContent);
var separatorParts = _signatureHelpItem.SeparatorDisplayParts;
var separatorContent = separatorParts.GetFullText();
var newLinePart = new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n");
var newLineContent = newLinePart.ToString();
var spacerPart = new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', signaturePrefixContent.Length));
var spacerContent = spacerPart.ToString();
var paramColumnCount = 0;
for (int i = 0; i < _signatureHelpItem.Parameters.Length; i++)
{
var sigHelpParameter = _signatureHelpItem.Parameters[i];
var parameterPrefixParts = sigHelpParameter.PrefixDisplayParts;
var parameterPrefixContext = sigHelpParameter.PrefixDisplayParts.GetFullText();
var parameterParts = AddOptionalBrackets(sigHelpParameter.IsOptional, sigHelpParameter.DisplayParts);
var parameterContent = parameterParts.GetFullText();
var parameterSuffixParts = sigHelpParameter.SuffixDisplayParts;
var parameterSuffixContext = sigHelpParameter.SuffixDisplayParts.GetFullText();
paramColumnCount += separatorContent.Length + parameterPrefixContext.Length + parameterContent.Length + parameterSuffixContext.Length;
if (i > 0)
{
AddRange(separatorParts, parts, prettyPrintedParts);
Append(separatorContent, content, prettyPrintedContent);
if (paramColumnCount > MaxParamColumnCount)
{
prettyPrintedParts.Add(newLinePart);
prettyPrintedParts.Add(spacerPart);
prettyPrintedContent.Append(newLineContent);
prettyPrintedContent.Append(spacerContent);
paramColumnCount = 0;
}
}
AddRange(parameterPrefixParts, parts, prettyPrintedParts);
Append(parameterPrefixContext, content, prettyPrintedContent);
parameters.Add(new Parameter(this, sigHelpParameter, parameterContent, content.Length, prettyPrintedContent.Length));
AddRange(parameterParts, parts, prettyPrintedParts);
Append(parameterContent, content, prettyPrintedContent);
AddRange(parameterSuffixParts, parts, prettyPrintedParts);
Append(parameterSuffixContext, content, prettyPrintedContent);
}
AddRange(_signatureHelpItem.SuffixDisplayParts, parts, prettyPrintedParts);
Append(_signatureHelpItem.SuffixDisplayParts.GetFullText(), content, prettyPrintedContent);
if (_parameterIndex >= 0)
{
var sigHelpParameter = _signatureHelpItem.Parameters[_parameterIndex];
AddRange(sigHelpParameter.SelectedDisplayParts, parts, prettyPrintedParts);
Append(sigHelpParameter.SelectedDisplayParts.GetFullText(), content, prettyPrintedContent);
}
AddRange(_signatureHelpItem.DescriptionParts, parts, prettyPrintedParts);
Append(_signatureHelpItem.DescriptionParts.GetFullText(), content, prettyPrintedContent);
var documentation = _signatureHelpItem.DocumentationFactory(CancellationToken.None).ToList();
if (documentation.Count > 0)
{
AddRange(new[] { newLinePart }, parts, prettyPrintedParts);
Append(newLineContent, content, prettyPrintedContent);
AddRange(documentation, parts, prettyPrintedParts);
Append(documentation.GetFullText(), content, prettyPrintedContent);
}
_content = content.ToString();
_prettyPrintedContent = prettyPrintedContent.ToString();
_displayParts = parts.ToImmutableArrayOrEmpty();
_prettyPrintedDisplayParts = prettyPrintedParts.ToImmutableArrayOrEmpty();
_parameters = parameters.ToReadOnlyCollection();
}
private void AddRange(IList<SymbolDisplayPart> values, List<SymbolDisplayPart> parts, List<SymbolDisplayPart> prettyPrintedParts)
{
parts.AddRange(values);
prettyPrintedParts.AddRange(values);
}
private void Append(string text, StringBuilder content, StringBuilder prettyPrintedContent)
{
content.Append(text);
prettyPrintedContent.Append(text);
}
private IList<SymbolDisplayPart> AddOptionalBrackets(bool isOptional, IList<SymbolDisplayPart> list)
{
if (isOptional)
{
var result = new List<SymbolDisplayPart>();
result.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "["));
result.AddRange(list);
result.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "]"));
return result;
}
return list;
}
}
}
| |
// -----------------------------------------------------------------------
//
// Copyright (C) 2003-2006 Angel Marin
//
// This file is part of SharpMimeTools
//
// SharpMimeTools is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// SharpMimeTools 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 SharpMimeTools; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
// -----------------------------------------------------------------------
using System;
namespace anmar.SharpMimeTools
{
/// <summary>
/// Decodes <a href="http://msdn.microsoft.com/library/en-us/mapi/html/ca148ec3-8586-4c74-8ff8-cd542256e385.asp">ms-tnef</a> streams (those winmail.dat attachments).
/// </summary>
/// <remarks>Only tnef attributes related to attachments are decoded right now. All the MAPI properties encoded in the stream (rtf body, ...) are ignored. <br />
/// While decoding, the cheksum of each attribute is verified to ensure the tnef stream is not corupt.</remarks>
public class SharpTnefMessage {
#if LOG
private static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endif
private System.IO.BinaryReader _reader;
private System.Collections.ArrayList _attachments;
private System.String _body;
/// <summary>
/// Initializes a new instance of the <see cref="anmar.SharpMimeTools.SharpTnefMessage" /> class based on the supplied <see cref="System.IO.Stream" />.
/// </summary>
/// <param name="input"><see cref="System.IO.Stream" /> that contains the ms-tnef strream.</param>
/// <remarks>The tnef stream isn't automatically parsed, you must call <see cref="Parse()" /> or <see cref="Parse(string)" />.</remarks>
public SharpTnefMessage ( System.IO.Stream input ) {
if ( input!=null && input.CanRead ) {
if ( input is System.IO.BufferedStream )
this._reader = new System.IO.BinaryReader(input);
else
this._reader = new System.IO.BinaryReader(new System.IO.BufferedStream(input));
}
}
/// <summary>
/// Gets a <see cref="System.Collections.ArrayList" /> instance that contains the attachments found in the tnef stream.
/// </summary>
/// <value><see cref="System.Collections.ArrayList" /> instance that contains the <see cref="SharpAttachment" /> found in the tnef stream. The <b>null</b> reference is retuned when no attachments found.</value>
/// <remarks>Each attachment is a <see cref="SharpAttachment" /> instance.</remarks>
public System.Collections.ArrayList Attachments {
get { return this._attachments; }
}
/// <summary>
/// Gets a the text body from the ms-tnef stream (<b>BODY</b> tnef attribute).
/// </summary>
/// <value>Text body from the ms-tnef stream (<b>BODY</b> tnef attribute). Or the <b>null</b> reference if the attribute is not part of the stream.</value>
public System.String TextBody {
get { return this._body; }
}
/// <summary>
/// Closes and releases the reading resources associated with this instance.
/// </summary>
/// <remarks>Be carefull before calling this method, as it also close the underlying <see cref="System.IO.Stream" />.</remarks>
public void Close () {
if ( this._reader!=null )
this._reader.Close();
this._reader = null;
}
/// <summary>
/// Parses the ms-tnef stream from the provided <see cref="System.IO.Stream" />.
/// </summary>
/// <returns><b>true</b> if parsing is successful. <b>false</b> otherwise.</returns>
/// <remarks>The attachments found are saved in memory as <see cref="System.IO.MemoryStream" /> instances.</remarks>
public bool Parse () {
return this.Parse(null);
}
/// <summary>
/// Parses the ms-tnef stream from the provided <see cref="System.IO.Stream" />.
/// </summary>
/// <param name="path">A <see cref="System.String" /> specifying the path on which to save the attachments found. Specify the <b>null</b> reference to save them in memory as <see cref="System.IO.MemoryStream" /> instances instead.</param>
/// <returns><b>true</b> if parsing is successful. <b>false</b> otherwise.</returns>
public bool Parse ( System.String path ) {
if ( this._reader==null || !this._reader.BaseStream.CanRead )
return false;
int sig = this.ReadInt();
if ( sig!=TnefSignature ) {
#if LOG
if ( logger.IsErrorEnabled )
logger.Error(System.String.Concat("Tnef signature not matched [", sig, "]<>[", TnefSignature, "]"));
#endif
return false;
}
bool error = false;
this._attachments = new System.Collections.ArrayList();
ushort key = this.ReadUInt16();
System.Text.Encoding enc = anmar.SharpMimeTools.SharpMimeHeader.EncodingDefault;
anmar.SharpMimeTools.SharpAttachment attachment_cur = null;
for ( System.Byte cur=this.ReadByte(); cur!=System.Byte.MinValue; cur=ReadByte() ) {
TnefLvlType lvl = (TnefLvlType)anmar.SharpMimeTools.SharpMimeTools.ParseEnum(typeof(TnefLvlType), cur, TnefLvlType.Unknown);
// Type
int type = this.ReadInt();
// Size
int size = this.ReadInt();
// Attibute name and type
TnefAttribute att_n = (TnefAttribute)anmar.SharpMimeTools.SharpMimeTools.ParseEnum(typeof(TnefAttribute), (ushort)((type<<16)>>16), TnefAttribute.Unknown);
TnefDataType att_t = (TnefDataType)anmar.SharpMimeTools.SharpMimeTools.ParseEnum(typeof(TnefDataType), (ushort)(type>>16), TnefDataType.Unknown);
if ( lvl==TnefLvlType.Unknown || att_n==TnefAttribute.Unknown || att_t==TnefDataType.Unknown ) {
#if LOG
if ( logger.IsErrorEnabled )
logger.Error(System.String.Concat("Attribute data is not valid [", lvl ,"] [type=", type, "->(", att_n, ",", att_t, ")] [size=", size, "]"));
#endif
error = true;
break;
}
// Read data
System.Byte[] buffer = this.ReadBytes(size);
// Read checkSum
ushort checksum = this.ReadUInt16();
// Verify checksum
if ( !this.VerifyChecksum(buffer, checksum) ) {
#if LOG
if ( logger.IsErrorEnabled )
logger.Error(System.String.Concat("Checksum validation failed [", lvl ,"] [type=", type, "->(", att_n, ",", att_t, ")] [size=", size, "(", (buffer!=null)?buffer.Length:0, ")] [checksum=", checksum, "]"));
#endif
error = true;
break;
}
size = buffer.Length;
#if LOG
if ( logger.IsDebugEnabled )
logger.Debug(System.String.Concat("[", lvl ,"] [type=", type, "->(", att_n, ",", att_t, ")] [size=", size, "(", (buffer!=null)?buffer.Length:0, ")] [checksum=", checksum, "]"));
#endif
if ( lvl==TnefLvlType.Message ) {
// Text body
if ( att_n==TnefAttribute.Body ) {
if ( att_t==TnefDataType.atpString ) {
this._body = enc.GetString(buffer, 0, size);
}
// Message mapi props (html body, rtf body, ...)
} else if ( att_n==TnefAttribute.MapiProps ) {
this.ReadMapi(buffer, size);
// Stream Codepage
} else if ( att_n==TnefAttribute.OEMCodepage ) {
uint codepage1 = (uint)(buffer[0] + (buffer[1]<<8) +(buffer[2]<<16) + (buffer[3]<<24));
if ( codepage1>0 ) {
try {
enc = System.Text.Encoding.GetEncoding((int)codepage1);
#if LOG
if ( logger.IsDebugEnabled ) {
logger.Debug(System.String.Concat("Now using [", enc.EncodingName, "] encoding to decode strings."));
}
#endif
} catch ( System.Exception ) {}
}
}
} else if ( lvl==TnefLvlType.Attachment ) {
// Attachment start
if ( att_n==TnefAttribute.AttachRendData ) {
System.String name = System.String.Concat("generated_", key, "_", (this._attachments.Count+1), ".binary" );
if ( path==null ) {
attachment_cur = new anmar.SharpMimeTools.SharpAttachment(new System.IO.MemoryStream());
} else {
attachment_cur = new anmar.SharpMimeTools.SharpAttachment(new System.IO.FileInfo(System.IO.Path.Combine(path, name)));
}
attachment_cur.Name = name;
// Attachment name
} else if ( att_n==TnefAttribute.AttachTitle ) {
if ( attachment_cur!=null && att_t==TnefDataType.atpString && buffer!=null && this._attachments.Count>0 ) {
// NULL terminated string
if ( buffer[size-1]=='\0' ) {
size--;
}
if ( size>0 ) {
System.String name = enc.GetString(buffer, 0, size);
if ( name.Length>0 ) {
attachment_cur.Name = name;
// Content already saved, so we have to rename
if ( attachment_cur.SavedFile!=null && attachment_cur.SavedFile.Exists ) {
try {
attachment_cur.SavedFile.MoveTo(System.IO.Path.Combine(path, attachment_cur.Name));
} catch ( System.Exception ) {}
}
}
}
}
// Modification and creation date
} else if ( att_n==TnefAttribute.AttachModifyDate || att_n==TnefAttribute.AttachCreateDate ) {
if ( attachment_cur!=null && att_t==TnefDataType.atpDate && buffer!=null && size==14 ) {
int pos = 0;
System.DateTime date = new System.DateTime((buffer[pos++]+(buffer[pos++]<<8)), (buffer[pos++]+(buffer[pos++]<<8)), (buffer[pos++]+(buffer[pos++]<<8)), (buffer[pos++]+(buffer[pos++]<<8)), (buffer[pos++]+(buffer[pos++]<<8)), (buffer[pos++]+(buffer[pos++]<<8)));
if ( att_n==TnefAttribute.AttachModifyDate ) {
attachment_cur.LastWriteTime = date;
} else if ( att_n==TnefAttribute.AttachCreateDate ) {
attachment_cur.CreationTime = date;
}
}
// Attachment data
} else if ( att_n==TnefAttribute.AttachData ) {
if ( attachment_cur!=null && att_t==TnefDataType.atpByte && buffer!=null ) {
if ( attachment_cur.SavedFile!=null ) {
System.IO.FileStream stream = null;
try {
stream = attachment_cur.SavedFile.OpenWrite();
} catch ( System.Exception e ) {
#if LOG
if ( logger.IsErrorEnabled )
logger.Error(System.String.Concat("Error writting file [", attachment_cur.SavedFile.FullName, "]"), e);
#endif
error = true;
break;
}
stream.Write(buffer, 0, size);
stream.Flush();
attachment_cur.Size = stream.Length;
stream.Close();
stream = null;
attachment_cur.SavedFile.Refresh();
// Is name has changed, we have to rename
if ( attachment_cur.SavedFile.Name!=attachment_cur.Name )
try {
attachment_cur.SavedFile.MoveTo(System.IO.Path.Combine(path, attachment_cur.Name));
} catch ( System.Exception ) {}
} else {
attachment_cur.Stream.Write(buffer, 0, size);
attachment_cur.Stream.Flush();
attachment_cur.Size = attachment_cur.Stream.Length;
}
this._attachments.Add(attachment_cur);
}
// Attachment mapi props
} else if ( att_n==TnefAttribute.Attachment ) {
this.ReadMapi(buffer, size);
}
}
}
if ( this._attachments.Count==0 )
this._attachments = null;
return !error;
}
private System.Byte ReadByte () {
System.Byte cur;
try {
cur = this._reader.ReadByte();
} catch ( System.Exception ) {
cur = System.Byte.MinValue;
}
return cur;
}
private System.Byte[] ReadBytes ( int length ) {
if ( length<=0 )
return null;
System.Byte[] buffer = null;
try {
buffer = this._reader.ReadBytes(length);
} catch ( System.Exception ) {}
return buffer;
}
private int ReadBytesTo ( int length, System.IO.Stream stream ) {
if ( length<=0 || stream==null || !stream.CanWrite )
return -1;
int written=0;
ushort checksum_calc = 0;
while ( length>0 ) {
System.Byte[] buffer = this.ReadBytes((length>4096)?4096:length);
if ( buffer!=null ) {
stream.Write(buffer, 0, buffer.Length);
written+=buffer.Length;
length-=buffer.Length;
// Checksum for this data portion
for ( int i=0, j=buffer.Length; i<j; i++ ) {
checksum_calc += buffer[i];
}
}
}
if ( length==0 ) {
ushort checksum = this.ReadUInt16();
checksum_calc = (ushort)(checksum_calc%65536);
if (checksum_calc!=checksum)
return -2;
}
return written;
}
private int ReadInt () {
int cur;
try {
cur = this._reader.ReadInt32();
} catch ( System.Exception ) {
cur = System.Int32.MinValue;
}
return cur;
}
private ushort ReadUInt16 () {
ushort cur;
try {
cur = this._reader.ReadUInt16();
} catch ( System.Exception ) {
cur = System.UInt16.MinValue;
}
return cur;
}
private void ReadMapi ( System.Byte[] data, int size ) {
int pos = 0;
ushort count = (ushort)(data[pos++]+(data[pos++]<<8));
#if LOG
if ( logger.IsDebugEnabled )
logger.Debug(System.String.Concat("[MAPIPROPS] Found [", count ,"]"));
#endif
if ( count==0 )
return;
//FIXME: Read each mapi prop
}
private bool VerifyChecksum ( System.Byte[] data, ushort checksum ) {
if ( data==null )
return false;
ushort checksum_calc = 0;
for ( int i=0, count=data.Length; i<count; i++ ) {
checksum_calc += data[i];
}
checksum_calc = (ushort)(checksum_calc%65536);
return (checksum_calc==checksum);
}
// TNEF signature
private const int TnefSignature = 0x223e9f78;
private enum TnefLvlType : byte {
Message = 0x01,
Attachment = 0x02,
Unknown = System.Byte.MaxValue
}
// TNEF attributes
private enum TnefAttribute : ushort {
Owner = 0x0000,
SentFor = 0x0001,
Delegate = 0x0002,
DateStart = 0x0006,
DateEnd = 0x0007,
AIDOwner = 0x0008,
Requestres = 0x0009,
From = 0x8000,
Subject = 0x8004,
DateSent = 0x8005,
DateRecd = 0x8006,
MessageStatus = 0x8007,
MessageClass = 0x8008,
MessageId = 0x8009,
ParentId = 0x800a,
ConversationId = 0x800b,
Body = 0x800c,
Priority = 0x800d,
AttachData = 0x800f,
AttachTitle = 0x8010,
AttachMetafile = 0x8011,
AttachCreateDate = 0x8012,
AttachModifyDate = 0x8013,
DateModify = 0x8020,
AttachTransportFilename = 0x9001,
AttachRendData = 0x9002,
MapiProps = 0x9003,
RecipTable = 0x9004,
Attachment = 0x9005,
TnefVersion = 0x9006,
OEMCodepage = 0x9007,
OriginalMessageClass = 0x9008,
Unknown = System.UInt16.MaxValue
}
// TNEF data types
private enum TnefDataType : ushort {
atpTriples = 0x0000,
atpString = 0x0001,
atpText = 0x0002,
atpDate = 0x0003,
atpShort = 0x0004,
atpLong = 0x0005,
atpByte = 0x0006,
atpWord = 0x0007,
atpDword = 0x0008,
atpMax = 0x0009,
Unknown = System.UInt16.MaxValue
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.IO
{
/// <summary>Provides an implementation of FileSystem for Unix systems.</summary>
internal sealed partial class UnixFileSystem : FileSystem
{
public override int MaxPath { get { return Interop.Sys.MaxPath; } }
public override int MaxDirectoryPath { get { return Interop.Sys.MaxPath; } }
public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent);
}
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
// The destination path may just be a directory into which the file should be copied.
// If it is, append the filename from the source onto the destination directory
if (DirectoryExists(destFullPath))
{
destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));
}
// Copy the contents of the file from the source to the destination, creating the destination in the process
using (var src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, FileOptions.None))
using (var dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, FileStream.DefaultBufferSize, FileOptions.None))
{
Interop.CheckIo(Interop.Sys.CopyFile(src.SafeFileHandle, dst.SafeFileHandle));
}
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
// The desired behavior for Move(source, dest) is to not overwrite the destination file
// if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,
// link/unlink are used instead. Note that the Unix FileSystemWatcher will treat a Move
// as a Creation and Deletion instead of a Rename and thus differ from Windows.
if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EXDEV) // rename fails across devices / mount points
{
CopyFile(sourceFullPath, destFullPath, overwrite: false);
}
else if (errorInfo.Error == Interop.Error.ENOENT && !Directory.Exists(Path.GetDirectoryName(destFullPath))) // The parent directory of destFile can't be found
{
// Windows distinguishes between whether the directory or the file isn't found,
// and throws a different exception in these cases. We attempt to approximate that
// here; there is a race condition here, where something could change between
// when the error occurs and our checks, but it's the best we can do, and the
// worst case in such a race condition (which could occur if the file system is
// being manipulated concurrently with these checks) is that we throw a
// FileNotFoundException instead of DirectoryNotFoundexception.
throw Interop.GetExceptionForIoErrno(errorInfo, destFullPath, isDirectory: true);
}
else
{
throw Interop.GetExceptionForIoErrno(errorInfo);
}
}
DeleteFile(sourceFullPath);
}
public override void DeleteFile(string fullPath)
{
if (Interop.Sys.Unlink(fullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
// ENOENT means it already doesn't exist; nop
if (errorInfo.Error != Interop.Error.ENOENT)
{
if (errorInfo.Error == Interop.Error.EISDIR)
errorInfo = Interop.Error.EACCES.Info();
throw Interop.GetExceptionForIoErrno(errorInfo, fullPath);
}
}
}
public override void CreateDirectory(string fullPath)
{
// NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))
{
length--;
}
// For paths that are only // or ///
if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
{
throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
}
// We can save a bunch of work if the directory we want to create already exists.
if (DirectoryExists(fullPath))
{
return;
}
// Attempt to figure out which directories don't exist, and only create the ones we need.
bool somepathexists = false;
Stack<string> stackDir = new Stack<string>();
int lengthRoot = PathInternal.GetRootLength(fullPath);
if (length > lengthRoot)
{
int i = length - 1;
while (i >= lengthRoot && !somepathexists)
{
string dir = fullPath.Substring(0, i + 1);
if (!DirectoryExists(dir)) // Create only the ones missing
{
stackDir.Push(dir);
}
else
{
somepathexists = true;
}
while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
{
i--;
}
i--;
}
}
int count = stackDir.Count;
if (count == 0 && !somepathexists)
{
string root = Directory.InternalGetDirectoryRoot(fullPath);
if (!DirectoryExists(root))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
return;
}
// Create all the directories
int result = 0;
Interop.ErrorInfo firstError = default(Interop.ErrorInfo);
string errorString = fullPath;
while (stackDir.Count > 0)
{
string name = stackDir.Pop();
if (name.Length >= MaxDirectoryPath)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.S_IRWXU);
if (result < 0 && firstError.Error == 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
// While we tried to avoid creating directories that don't
// exist above, there are a few cases that can fail, e.g.
// a race condition where another process or thread creates
// the directory first, or there's a file at the location.
if (errorInfo.Error != Interop.Error.EEXIST)
{
firstError = errorInfo;
}
else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))
{
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
firstError = errorInfo;
errorString = name;
}
}
}
// Only throw an exception if creating the exact directory we wanted failed to work correctly.
if (result < 0 && firstError.Error != 0)
{
throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
}
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
if (Interop.Sys.Rename(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EACCES: // match Win32 exception
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno);
default:
throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true);
}
}
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
if (!DirectoryExists(fullPath))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
RemoveDirectoryInternal(fullPath, recursive, throwOnTopLevelDirectoryNotFound: true);
}
private void RemoveDirectoryInternal(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
Exception firstException = null;
if (recursive)
{
try
{
foreach (string item in EnumeratePaths(fullPath, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
{
if (!ShouldIgnoreDirectory(Path.GetFileName(item)))
{
try
{
if (DirectoryExists(item))
{
RemoveDirectoryInternal(item, recursive, throwOnTopLevelDirectoryNotFound: false);
}
else
{
DeleteFile(item);
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
}
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
if (firstException != null)
{
throw firstException;
}
}
if (Interop.Sys.RmDir(fullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EACCES:
case Interop.Error.EPERM:
case Interop.Error.EROFS:
case Interop.Error.EISDIR:
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); // match Win32 exception
case Interop.Error.ENOENT:
if (!throwOnTopLevelDirectoryNotFound)
{
return;
}
goto default;
default:
throw Interop.GetExceptionForIoErrno(errorInfo, fullPath, isDirectory: true);
}
}
}
public override bool DirectoryExists(string fullPath)
{
Interop.ErrorInfo ignored;
return DirectoryExists(fullPath, out ignored);
}
private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo)
{
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo);
}
public override bool FileExists(string fullPath)
{
Interop.ErrorInfo ignored;
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFREG, out ignored);
}
private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo)
{
Interop.Sys.FileStatus fileinfo;
errorInfo = default(Interop.ErrorInfo);
int result = Interop.Sys.Stat(fullPath, out fileinfo);
if (result < 0)
{
errorInfo = Interop.Sys.GetLastErrorInfo();
return false;
}
return (fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == fileType;
}
public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p);
}
public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
switch (searchTarget)
{
case SearchTarget.Files:
return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new FileInfo(path, null));
case SearchTarget.Directories:
return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new DirectoryInfo(path, null));
default:
return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ?
(FileSystemInfo)new DirectoryInfo(path, null) :
(FileSystemInfo)new FileInfo(path, null));
}
}
private sealed class FileSystemEnumerable<T> : IEnumerable<T>
{
private readonly PathPair _initialDirectory;
private readonly string _searchPattern;
private readonly SearchOption _searchOption;
private readonly bool _includeFiles;
private readonly bool _includeDirectories;
private readonly Func<string, bool, T> _translateResult;
private IEnumerator<T> _firstEnumerator;
internal FileSystemEnumerable(
string userPath, string searchPattern,
SearchOption searchOption, SearchTarget searchTarget,
Func<string, bool, T> translateResult)
{
// Basic validation of the input path
if (userPath == null)
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrWhiteSpace(userPath))
{
throw new ArgumentException(SR.Argument_EmptyPath, "path");
}
// Validate and normalize the search pattern. If after doing so it's empty,
// matching Win32 behavior we can skip all additional validation and effectively
// return an empty enumerable.
searchPattern = NormalizeSearchPattern(searchPattern);
if (searchPattern.Length > 0)
{
PathHelpers.CheckSearchPattern(searchPattern);
PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern);
// If the search pattern contains any paths, make sure we factor those into
// the user path, and then trim them off.
int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (lastSlash >= 0)
{
if (lastSlash >= 1)
{
userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash));
}
searchPattern = searchPattern.Substring(lastSlash + 1);
}
string fullPath = Path.GetFullPath(userPath);
// Store everything for the enumerator
_initialDirectory = new PathPair(userPath, fullPath);
_searchPattern = searchPattern;
_searchOption = searchOption;
_includeFiles = (searchTarget & SearchTarget.Files) != 0;
_includeDirectories = (searchTarget & SearchTarget.Directories) != 0;
_translateResult = translateResult;
}
// Open the first enumerator so that any errors are propagated synchronously.
_firstEnumerator = Enumerate();
}
public IEnumerator<T> GetEnumerator()
{
return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private IEnumerator<T> Enumerate()
{
return Enumerate(
_initialDirectory.FullPath != null ?
OpenDirectory(_initialDirectory.FullPath) :
null);
}
private IEnumerator<T> Enumerate(Microsoft.Win32.SafeHandles.SafeDirectoryHandle dirHandle)
{
if (dirHandle == null)
{
// Empty search
yield break;
}
Debug.Assert(!dirHandle.IsInvalid);
Debug.Assert(!dirHandle.IsClosed);
// Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories
// Lazily-initialized only if we find subdirectories that will be explored.
Stack<PathPair> toExplore = null;
PathPair dirPath = _initialDirectory;
while (dirHandle != null)
{
try
{
// Read each entry from the enumerator
Interop.Sys.DirectoryEntry dirent;
while (Interop.Sys.ReadDir(dirHandle, out dirent) == 0)
{
// Get from the dir entry whether the entry is a file or directory.
// We classify everything as a file unless we know it to be a directory.
bool isDir;
if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR)
{
// We know it's a directory.
isDir = true;
}
else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN)
{
// It's a symlink or unknown: stat to it to see if we can resolve it to a directory.
// If we can't (e.g.symlink to a file, broken symlink, etc.), we'll just treat it as a file.
Interop.ErrorInfo errnoIgnored;
isDir = DirectoryExists(Path.Combine(dirPath.FullPath, dirent.InodeName), out errnoIgnored);
}
else
{
// Otherwise, treat it as a file. This includes regular files, FIFOs, etc.
isDir = false;
}
// Yield the result if the user has asked for it. In the case of directories,
// always explore it by pushing it onto the stack, regardless of whether
// we're returning directories.
if (isDir)
{
if (!ShouldIgnoreDirectory(dirent.InodeName))
{
string userPath = null;
if (_searchOption == SearchOption.AllDirectories)
{
if (toExplore == null)
{
toExplore = new Stack<PathPair>();
}
userPath = Path.Combine(dirPath.UserPath, dirent.InodeName);
toExplore.Push(new PathPair(userPath, Path.Combine(dirPath.FullPath, dirent.InodeName)));
}
if (_includeDirectories &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(userPath ?? Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/true);
}
}
}
else if (_includeFiles &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/false);
}
}
}
finally
{
// Close the directory enumerator
dirHandle.Dispose();
dirHandle = null;
}
if (toExplore != null && toExplore.Count > 0)
{
// Open the next directory.
dirPath = toExplore.Pop();
dirHandle = OpenDirectory(dirPath.FullPath);
}
}
}
private static string NormalizeSearchPattern(string searchPattern)
{
if (searchPattern == "." || searchPattern == "*.*")
{
searchPattern = "*";
}
else if (PathHelpers.EndsInDirectorySeparator(searchPattern))
{
searchPattern += "*";
}
return searchPattern;
}
private static Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDirectory(string fullPath)
{
Microsoft.Win32.SafeHandles.SafeDirectoryHandle handle = Interop.Sys.OpenDir(fullPath);
if (handle.IsInvalid)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true);
}
return handle;
}
}
/// <summary>Determines whether the specified directory name should be ignored.</summary>
/// <param name="name">The name to evaluate.</param>
/// <returns>true if the name is "." or ".."; otherwise, false.</returns>
private static bool ShouldIgnoreDirectory(string name)
{
return name == "." || name == "..";
}
public override string GetCurrentDirectory()
{
return Interop.Sys.GetCwd();
}
public override void SetCurrentDirectory(string fullPath)
{
Interop.CheckIo(Interop.Sys.ChDir(fullPath), fullPath);
}
public override FileAttributes GetAttributes(string fullPath)
{
return new FileInfo(fullPath, null).Attributes;
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
new FileInfo(fullPath, null).Attributes = attributes;
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
return new FileInfo(fullPath, null).CreationTime;
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.CreationTime = time;
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
return new FileInfo(fullPath, null).LastAccessTime;
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastAccessTime = time;
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
return new FileInfo(fullPath, null).LastWriteTime;
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastWriteTime = time;
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
}
}
}
| |
// 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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Components.WebAssembly.Server
{
/// <summary>
/// Class for the target picker ui.
/// </summary>
public class TargetPickerUi
{
private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
private readonly string _browserHost;
private readonly string _debugProxyUrl;
/// <summary>
/// Initialize a new instance of <see cref="TargetPickerUi"/>.
/// </summary>
/// <param name="debugProxyUrl">The debug proxy url.</param>
/// <param name="devToolsHost">The dev tools host.</param>
public TargetPickerUi(string debugProxyUrl, string devToolsHost)
{
_debugProxyUrl = debugProxyUrl;
_browserHost = devToolsHost;
}
/// <summary>
/// Display the ui.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/>.</param>
/// <returns>The <see cref="Task"/>.</returns>
public async Task Display(HttpContext context)
{
context.Response.ContentType = "text/html";
var request = context.Request;
var targetApplicationUrl = request.Query["url"];
var debuggerTabsListUrl = $"{_browserHost}/json";
IEnumerable<BrowserTab> availableTabs;
try
{
availableTabs = await GetOpenedBrowserTabs();
}
catch (Exception ex)
{
await context.Response.WriteAsync($@"
<h1>Unable to find debuggable browser tab</h1>
<p>
Could not get a list of browser tabs from <code>{debuggerTabsListUrl}</code>.
Ensure your browser is running with debugging enabled.
</p>
<h2>Resolution</h2>
<p>
<h4>If you are using Google Chrome for your development, follow these instructions:</h4>
{GetLaunchChromeInstructions(targetApplicationUrl.ToString())}
</p>
<p>
<h4>If you are using Microsoft Edge (80+) for your development, follow these instructions:</h4>
{GetLaunchEdgeInstructions(targetApplicationUrl.ToString())}
</p>
<strong>This should launch a new browser window with debugging enabled..</p>
<h2>Underlying exception:</h2>
<pre>{ex}</pre>
");
return;
}
var matchingTabs = string.IsNullOrEmpty(targetApplicationUrl)
? availableTabs.ToList()
: availableTabs.Where(t => t.Url.Equals(targetApplicationUrl, StringComparison.Ordinal)).ToList();
if (matchingTabs.Count == 1)
{
// We know uniquely which tab to debug, so just redirect
var devToolsUrlWithProxy = GetDevToolsUrlWithProxy(request, matchingTabs.Single());
context.Response.Redirect(devToolsUrlWithProxy);
}
else if (matchingTabs.Count == 0)
{
await context.Response.WriteAsync("<h1>No inspectable pages found</h1>");
var suffix = string.IsNullOrEmpty(targetApplicationUrl)
? string.Empty
: $" matching the URL {WebUtility.HtmlEncode(targetApplicationUrl)}";
await context.Response.WriteAsync($"<p>The list of targets returned by {WebUtility.HtmlEncode(debuggerTabsListUrl)} contains no entries{suffix}.</p>");
await context.Response.WriteAsync("<p>Make sure your browser is displaying the target application.</p>");
}
else
{
await context.Response.WriteAsync("<h1>Inspectable pages</h1>");
await context.Response.WriteAsync(@"
<style type='text/css'>
body {
font-family: Helvetica, Arial, sans-serif;
margin: 2rem 3rem;
}
.inspectable-page {
display: block;
background-color: #eee;
padding: 1rem 1.2rem;
margin-bottom: 1rem;
border-radius: 0.5rem;
text-decoration: none;
color: #888;
}
.inspectable-page:hover {
background-color: #fed;
}
.inspectable-page h3 {
margin-top: 0px;
margin-bottom: 0.3rem;
color: black;
}
</style>
");
foreach (var tab in matchingTabs)
{
var devToolsUrlWithProxy = GetDevToolsUrlWithProxy(request, tab);
await context.Response.WriteAsync(
$"<a class='inspectable-page' href='{WebUtility.HtmlEncode(devToolsUrlWithProxy)}'>"
+ $"<h3>{WebUtility.HtmlEncode(tab.Title)}</h3>{WebUtility.HtmlEncode(tab.Url)}"
+ $"</a>");
}
}
}
private string GetDevToolsUrlWithProxy(HttpRequest request, BrowserTab tabToDebug)
{
var underlyingV8Endpoint = new Uri(tabToDebug.WebSocketDebuggerUrl);
var proxyEndpoint = new Uri(_debugProxyUrl);
var devToolsUrlAbsolute = new Uri(_browserHost + tabToDebug.DevtoolsFrontendUrl);
var devToolsUrlWithProxy = $"{devToolsUrlAbsolute.Scheme}://{devToolsUrlAbsolute.Authority}{devToolsUrlAbsolute.AbsolutePath}?{underlyingV8Endpoint.Scheme}={proxyEndpoint.Authority}{underlyingV8Endpoint.PathAndQuery}";
return devToolsUrlWithProxy;
}
private string GetLaunchChromeInstructions(string targetApplicationUrl)
{
var profilePath = Path.Combine(Path.GetTempPath(), "blazor-chrome-debug");
var debuggerPort = new Uri(_browserHost).Port;
if (OperatingSystem.IsWindows())
{
return $@"<p>Press Win+R and enter the following:</p>
<p><strong><code>chrome --remote-debugging-port={debuggerPort} --user-data-dir=""{profilePath}"" {targetApplicationUrl}</code></strong></p>";
}
else if (OperatingSystem.IsLinux())
{
return $@"<p>In a terminal window execute the following:</p>
<p><strong><code>google-chrome --remote-debugging-port={debuggerPort} --user-data-dir={profilePath} {targetApplicationUrl}</code></strong></p>";
}
else if (OperatingSystem.IsMacOS())
{
return $@"<p>Execute the following:</p>
<p><strong><code>open -n /Applications/Google\ Chrome.app --args --remote-debugging-port={debuggerPort} --user-data-dir={profilePath} {targetApplicationUrl}</code></strong></p>";
}
else
{
throw new InvalidOperationException("Unknown OS platform");
}
}
private string GetLaunchEdgeInstructions(string targetApplicationUrl)
{
var profilePath = Path.Combine(Path.GetTempPath(), "blazor-edge-debug");
var debuggerPort = new Uri(_browserHost).Port;
if (OperatingSystem.IsWindows())
{
return $@"<p>Press Win+R and enter the following:</p>
<p><strong><code>msedge --remote-debugging-port={debuggerPort} --user-data-dir=""{profilePath}"" --no-first-run {targetApplicationUrl}</code></strong></p>";
}
else if (OperatingSystem.IsMacOS())
{
return $@"<p>In a terminal window execute the following:</p>
<p><strong><code>open -n /Applications/Microsoft\ Edge.app --args --remote-debugging-port={debuggerPort} --user-data-dir={profilePath} {targetApplicationUrl}</code></strong></p>";
}
else
{
return $@"<p>Edge is not current supported on your platform</p>";
}
}
private static Uri GetProxyEndpoint(HttpRequest incomingRequest, string browserEndpoint)
{
var builder = new UriBuilder(
schemeName: incomingRequest.IsHttps ? "wss" : "ws",
hostName: incomingRequest.Host.Host)
{
Path = $"{incomingRequest.PathBase}/ws-proxy",
Query = $"browser={WebUtility.UrlEncode(browserEndpoint)}"
};
if (incomingRequest.Host.Port.HasValue)
{
builder.Port = incomingRequest.Host.Port.Value;
}
return builder.Uri;
}
private async Task<IEnumerable<BrowserTab>> GetOpenedBrowserTabs()
{
using var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
var jsonResponse = await httpClient.GetStringAsync($"{_browserHost}/json");
return JsonSerializer.Deserialize<BrowserTab[]>(jsonResponse, JsonOptions)!;
}
record BrowserTab
(
string Id,
string Type,
string Url,
string Title,
string DevtoolsFrontendUrl,
string WebSocketDebuggerUrl
);
}
}
| |
// <copyright file="PlainTextReader.cs" company="Jason Diamond">
//
// Copyright (c) 2009-2010 Jason Diamond
//
// This source code is released under the MIT License.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// </copyright>
namespace BehaveN
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
/// <summary>
/// Reads specifications in the Given/When/Then style from a plain text file.
/// </summary>
public class PlainTextReader
{
private const string HeaderPattern = @"^\s*#\s*(.+)\s*:\s*(.+)\s*$";
private const string CommentPattern = @"^\s*#.*$";
private const string FeaturePattern = @"^\s*(?:{0})\s*:\s*(.+)";
private const string ScenarioPattern = @"^\s*(?:{0})\s*\d*\s*:\s*(.*)";
private const string StepPattern = @"^\s*({0})\s+.+";
private readonly Regex headerRegex = new Regex(HeaderPattern);
private readonly Regex commentRegex = new Regex(CommentPattern);
private Regex featureRegex;
private Regex scenarioRegex;
private Regex givenRegex;
private Regex whenRegex;
private Regex thenRegex;
private Regex andRegex;
private Regex withRegex;
private Match match;
/// <summary>
/// Reads the contents of the file to the feature.
/// </summary>
/// <param name="text">The text to read.</param>
/// <param name="feature">The feature.</param>
public void ReadTo(string text, Feature feature)
{
this.CompileRegexes(text);
List<string> lines = TextParser.GetLines(text);
Scenario scenario = null;
StepType stepType = StepType.Unknown;
for (int i = 0; i < lines.Count; i++)
{
string line = lines[i];
if (scenario == null)
{
this.match = this.headerRegex.Match(line);
if (this.match.Success)
{
feature.Headers[this.match.Groups[1].Value] = this.match.Groups[2].Value;
continue;
}
if (this.commentRegex.IsMatch(line))
{
continue;
}
i = this.ParseTitleAndDescription(lines, i, feature);
}
else
{
if (this.commentRegex.IsMatch(line))
{
continue;
}
this.match = this.scenarioRegex.Match(line);
}
if (this.match.Success)
{
scenario = CreateScenario(feature, this.match.Groups[1].Value, out stepType);
}
else
{
if (scenario == null)
{
scenario = CreateScenario(feature, null, out stepType);
}
this.ParseStep(lines, ref i, scenario, ref stepType, line);
}
}
}
private Scenario CreateScenario(Feature feature, string name, out StepType stepType)
{
var scenario = new Scenario();
scenario.Name = string.IsNullOrEmpty(name) ? "(no name)" : name;
feature.Scenarios.Add(scenario);
stepType = StepType.Unknown;
return scenario;
}
private void CompileRegexes(string text)
{
var lm = new LanguageManager();
string language = TextParser.DiscoverLanguage(text);
string feature = lm.GetString(language, "Feature");
string scenario = lm.GetString(language, "Scenario");
string given = lm.GetString(language, "Given");
string when = lm.GetString(language, "When");
string then = lm.GetString(language, "Then");
string and = lm.GetString(language, "And");
string with = lm.GetString(language, "With");
this.featureRegex = new Regex(string.Format(FeaturePattern, feature), RegexOptions.IgnoreCase);
this.scenarioRegex = new Regex(string.Format(ScenarioPattern, scenario), RegexOptions.IgnoreCase);
this.givenRegex = new Regex(string.Format(StepPattern, given), RegexOptions.IgnoreCase);
this.whenRegex = new Regex(string.Format(StepPattern, when), RegexOptions.IgnoreCase);
this.thenRegex = new Regex(string.Format(StepPattern, then), RegexOptions.IgnoreCase);
this.andRegex = new Regex(string.Format(StepPattern, and), RegexOptions.IgnoreCase);
this.withRegex = new Regex(string.Format(StepPattern, with), RegexOptions.IgnoreCase);
}
private int ParseTitleAndDescription(List<string> lines, int i, Feature feature)
{
string line = lines[i];
if ((this.match = this.featureRegex.Match(line)).Success)
{
feature.Name = this.match.Groups[1].Value;
i++;
}
var featureLines = new List<string>();
for (; i < lines.Count; i++)
{
line = lines[i];
this.match = this.scenarioRegex.Match(line);
if (this.match.Success)
{
break;
}
featureLines.Add(line);
}
feature.Description = string.Join("\r\n", featureLines.ToArray()).Trim('\r', '\n');
return i;
}
private void ParseStep(List<string> lines, ref int i, Scenario scenario, ref StepType stepType, string line)
{
bool isPrimary = false;
if (this.givenRegex.Match(line).Success)
{
stepType = StepType.Given;
isPrimary = true;
}
else if (this.whenRegex.Match(line).Success)
{
stepType = StepType.When;
isPrimary = true;
}
else if (this.thenRegex.Match(line).Success)
{
stepType = StepType.Then;
isPrimary = true;
}
else if (this.andRegex.Match(line).Success)
{
if (stepType == StepType.Unknown)
{
throw new Exception("\"And\" steps cannot appear before \"given\", \"when\", or \"then\" steps.");
}
}
else if (this.withRegex.Match(line).Success)
{
if (stepType == StepType.Unknown)
{
throw new Exception("\"With\" steps cannot appear before \"given\", \"when\", or \"then\" steps.");
}
}
else
{
throw new Exception(string.Format("Unrecognized step: \"{0}\".", line));
}
IBlock block = this.ParseBlock(lines, ref i);
scenario.Steps.Add(new Step
{
Type = stepType,
IsPrimary = isPrimary,
Text = line,
Block = block
});
}
private IBlock ParseBlock(List<string> lines, ref int i)
{
if (i + 1 >= lines.Count)
{
return null;
}
string line = lines[i + 1];
var blockType = BlockTypes.GetBlockTypeForLine(line);
if (blockType == null)
{
return null;
}
var sb = new StringBuilder();
sb.AppendLine(line);
i += 2;
while (i < lines.Count && blockType.LineIsPartOfBlock(lines[i]))
{
sb.AppendLine(lines[i]);
i++;
}
i--;
IBlock block = blockType.Parse(sb.ToString());
return block;
}
}
}
| |
#if !NETCOREAPP
using System;
using System.Data.OleDb;
using FileHelpers.DataLink;
using NUnit.Framework;
namespace FileHelpers.Tests.DataLink
{
[TestFixture]
[Explicit]
[Category("Advanced")]
public class DataLinks
{
private FileDataLink mLink;
#region " FillRecordOrders "
protected void FillRecordOrders(object rec, object[] fields)
{
var record = (OrdersFixed) rec;
record.OrderID = (int) fields[0];
record.CustomerID = (string) fields[1];
record.EmployeeID = (int) fields[2];
record.OrderDate = (DateTime) fields[3];
record.RequiredDate = (DateTime) fields[4];
if (fields[5] != DBNull.Value)
record.ShippedDate = (DateTime) fields[5];
else
record.ShippedDate = DateTime.MinValue;
record.ShipVia = (int) fields[6];
record.Freight = (decimal) fields[7];
}
#endregion
[Test]
public void OrdersDbToFile()
{
var storage = new AccessStorage(typeof (OrdersFixed), @"..\data\TestData.mdb");
storage.SelectSql = "SELECT * FROM Orders";
storage.FillRecordCallback = new FillRecordHandler(FillRecordOrders);
mLink = new FileDataLink(storage);
mLink.ExtractToFile(@"..\data\temp.txt");
int extractNum = mLink.LastExtractedRecords.Length;
var records = (OrdersFixed[]) mLink.FileHelperEngine.ReadFile(@"..\data\temp.txt");
Assert.AreEqual(extractNum, records.Length);
}
[Test]
public void OrdersDbToFileEasy()
{
var storage = new AccessStorage(typeof (OrdersFixed), @"..\data\TestData.mdb");
storage.SelectSql = "SELECT * FROM Orders";
storage.FillRecordCallback = new FillRecordHandler(FillRecordOrders);
var records = (OrdersFixed[]) FileDataLink.EasyExtractToFile(storage, @"..\data\temp.txt");
int extractNum = records.Length;
records = (OrdersFixed[]) CommonEngine.ReadFile(typeof (OrdersFixed), @"..\data\temp.txt");
Assert.AreEqual(extractNum, records.Length);
}
private void FillRecordCustomers(object rec, object[] fields)
{
var record = (CustomersVerticalBar) rec;
record.CustomerID = (string) fields[0];
record.CompanyName = (string) fields[1];
record.ContactName = (string) fields[2];
record.ContactTitle = (string) fields[3];
record.Address = (string) fields[4];
record.City = (string) fields[5];
record.Country = (string) fields[6];
}
[Test]
public void CustomersDbToFile()
{
var storage = new AccessStorage(typeof (CustomersVerticalBar), @"..\data\TestData.mdb");
storage.SelectSql = "SELECT * FROM Customers";
storage.FillRecordCallback = new FillRecordHandler(FillRecordCustomers);
mLink = new FileDataLink(storage);
mLink.ExtractToFile(@"..\data\temp.txt");
int extractNum = mLink.LastExtractedRecords.Length;
var records = (CustomersVerticalBar[]) mLink.FileHelperEngine.ReadFile(@"..\data\temp.txt");
Assert.AreEqual(extractNum, records.Length);
}
private object FillRecord(object[] fields)
{
var record = new CustomersVerticalBar();
record.CustomerID = (string) fields[0];
record.CompanyName = (string) fields[1];
record.ContactName = (string) fields[2];
record.ContactTitle = (string) fields[3];
record.Address = (string) fields[4];
record.City = (string) fields[5];
record.Country = (string) fields[6];
return record;
}
#region " GetInsertSql "
protected string GetInsertSqlCust(object record)
{
var obj = (CustomersVerticalBar) record;
return
string.Format(
"INSERT INTO CustomersTemp (Address, City, CompanyName, ContactName, ContactTitle, Country, CustomerID) " +
" VALUES ( \"{0}\" , \"{1}\" , \"{2}\" , \"{3}\" , \"{4}\" , \"{5}\" , \"{6}\" ); ",
obj.Address,
obj.City,
obj.CompanyName,
obj.ContactName,
obj.ContactTitle,
obj.Country,
obj.CustomerID
);
}
#endregion
[Test]
public void CustomersFileToDb()
{
var storage = new AccessStorage(typeof (CustomersVerticalBar), @"..\data\TestData.mdb");
storage.InsertSqlCallback = new InsertSqlHandler(GetInsertSqlCust);
mLink = new FileDataLink(storage);
ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp");
int count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp");
Assert.AreEqual(0, count);
mLink.InsertFromFile(@"..\data\UpLoadCustomers.txt");
count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp");
Assert.AreEqual(91, count);
ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp");
}
protected object FillRecordOrder(object[] fields)
{
var record = new OrdersFixed();
record.OrderID = (int) fields[0];
record.CustomerID = (string) fields[1];
record.EmployeeID = (int) fields[2];
record.OrderDate = (DateTime) fields[3];
record.RequiredDate = (DateTime) fields[4];
if (fields[5] != DBNull.Value)
record.ShippedDate = (DateTime) fields[5];
else
record.ShippedDate = DateTime.MinValue;
record.ShipVia = (int) fields[6];
record.Freight = (decimal) fields[7];
return record;
}
#region " GetInsertSql "
protected string GetInsertSqlOrder(object record)
{
var obj = (OrdersFixed) record;
return
string.Format(
"INSERT INTO OrdersTemp (CustomerID, EmployeeID, Freight, OrderDate, OrderID, RequiredDate, ShippedDate, ShipVia) " +
" VALUES ( \"{0}\" , \"{1}\" , \"{2}\" , \"{3}\" , \"{4}\" , \"{5}\" , \"{6}\" , \"{7}\" ) ",
obj.CustomerID,
obj.EmployeeID,
obj.Freight,
obj.OrderDate,
obj.OrderID,
obj.RequiredDate,
obj.ShippedDate,
obj.ShipVia
);
}
#endregion
[Test]
[Ignore("Needs Access Installed")]
public void OrdersFileToDb()
{
var storage = new AccessStorage(typeof (OrdersFixed), @"..\data\TestData.mdb");
storage.InsertSqlCallback = new InsertSqlHandler(GetInsertSqlOrder);
mLink = new FileDataLink(storage);
ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
int count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
Assert.AreEqual(0, count);
mLink.InsertFromFile(@"..\data\UpLoadOrders.txt");
count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
Assert.AreEqual(830, count);
ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
}
private const string AccessConnStr =
@"Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Database Password=;Data Source=""<BASE>"";Password=;Jet OLEDB:Engine Type=5;Jet OLEDB:Global Bulk Transactions=1;Provider=""Microsoft.Jet.OLEDB.4.0"";Jet OLEDB:System database=;Jet OLEDB:SFP=False;Extended Properties=;Mode=Share Deny None;Jet OLEDB:New Database Password=;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;User ID=Admin;Jet OLEDB:Encrypt Database=False";
public void ClearData(string fileName, string table)
{
string conString = AccessConnStr.Replace("<BASE>", fileName);
var conn = new OleDbConnection(conString);
var cmd = new OleDbCommand("DELETE FROM " + table, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
int count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp");
}
public int Count(string fileName, string table)
{
string conString = AccessConnStr.Replace("<BASE>", fileName);
var conn = new OleDbConnection(conString);
var cmd = new OleDbCommand("SELECT COUNT (*) FROM " + table, conn);
conn.Open();
var res = (int) cmd.ExecuteScalar();
conn.Close();
return res;
}
}
}
#endif
| |
using System;
using Pulsar.Helpers;
namespace Pulsar
{
/// <summary>
/// Color.
/// </summary>
[Serializable]
public sealed class Color : ICloneable, IEquatable<Color>
{
/// <summary>
/// Gets or sets alpha.
/// </summary>
/// <value>Alpha.</value>
public byte A { get; set;}
/// <summary>
/// Gets or sets the red.
/// </summary>
/// <value>The red.</value>
public byte R { get; set;}
/// <summary>
/// Gets or sets the green.
/// </summary>
/// <value>The green.</value>
public byte G { get; set;}
/// <summary>
/// Gets or sets the blue.
/// </summary>
/// <value>The blue.</value>
public byte B { get; set;}
/// <summary>
/// Initializes a new instance of the <see cref="Pulsar.Color"/> class.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
public Color(byte r, byte g, byte b)
: this(r, g, b, 255)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Pulsar.Color"/> class.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
/// <param name="a">The alpha component.</param>
public Color(byte r, byte g, byte b, byte a)
{
R = r;
G = g;
B = b;
A = a;
}
/// <summary>
/// Gets the black color.
/// </summary>
/// <value>The black color.</value>
public static Color Black
{
get
{
return new Color(0, 0, 0);
}
}
/// <summary>
/// Gets the white color.
/// </summary>
/// <value>The white color.</value>
public static Color White
{
get
{
return new Color(255, 255, 255);
}
}
/// <summary>
/// Gets the red color.
/// </summary>
/// <value>The red color.</value>
public static Color Red
{
get
{
return new Color(255, 0, 0);
}
}
/// <summary>
/// Gets the green color.
/// </summary>
/// <value>The green color.</value>
public static Color Green
{
get
{
return new Color(255, 0, 0);
}
}
/// <summary>
/// Gets the blue color.
/// </summary>
/// <value>The blue color.</value>
public static Color Blue
{
get
{
return new Color(0, 0, 255);
}
}
/// <summary>
/// Gets the yellow color.
/// </summary>
/// <value>The yellow color.</value>
public static Color Yellow
{
get
{
return new Color(255, 255, 0);
}
}
/// <summary>
/// Gets the magenta color.
/// </summary>
/// <value>The magenta color.</value>
public static Color Magenta
{
get
{
return new Color(255, 0, 255);
}
}
/// <summary>
/// Gets the cyan color.
/// </summary>
/// <value>The cyan color.</value>
public static Color Cyan
{
get
{
return new Color(0, 255, 255);
}
}
/// <summary>
/// Gets the transparent color.
/// </summary>
/// <value>The transparent color.</value>
public static Color Transparent
{
get
{
return new Color(0, 0, 0, 0);
}
}
/// <summary>
/// Clone this instance.
/// </summary>
public object Clone()
{
return new Color(R, G, B, A);
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="Pulsar.Color"/>.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="Pulsar.Color"/>.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current <see cref="Pulsar.Color"/>;
/// otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
var a = obj as Color;
return a != null && Equals(a);
}
/// <summary>
/// Determines whether the specified <see cref="Pulsar.Color"/> is equal to the current <see cref="Pulsar.Color"/>.
/// </summary>
/// <param name="other">The <see cref="Pulsar.Color"/> to compare with the current <see cref="Pulsar.Color"/>.</param>
/// <returns><c>true</c> if the specified <see cref="Pulsar.Color"/> is equal to the current <see cref="Pulsar.Color"/>;
/// otherwise, <c>false</c>.</returns>
public bool Equals(Color other)
{
if (this == other)
return true;
return A == other.A && R == other.R && G == other.G && B == other.B;
}
/// <summary>
/// Lerp the color on rgb.
/// </summary>
/// <returns>The rgb lerp color.</returns>
/// <param name="value1">Value1.</param>
/// <param name="value2">Value2.</param>
/// <param name="amount">Amount.</param>
public static Color LerpRgb(Color value1, Color value2, float amount)
{
return new Color(
(byte)MathHelper.Lerp(value1.R, value2.R, amount),
(byte)MathHelper.Lerp(value1.G, value2.G, amount),
(byte)MathHelper.Lerp(value1.B, value2.B, amount));
}
/// <summary>
/// Lerp the color on argb.
/// </summary>
/// <returns>The argb color.</returns>
/// <param name="value1">Value1.</param>
/// <param name="value2">Value2.</param>
/// <param name="amount">Amount.</param>
public static Color LerpArgb(Color value1, Color value2, float amount)
{
return new Color(
(byte)MathHelper.Lerp(value1.R, value2.R, amount),
(byte)MathHelper.Lerp(value1.G, value2.G, amount),
(byte)MathHelper.Lerp(value1.B, value2.B, amount),
(byte)MathHelper.Lerp(value1.A, value2.A, amount));
}
/// <param name="c1">C1.</param>
/// <param name="c2">C2.</param>
public static bool operator ==(Color c1, Color c2)
{
return c1 != null && c1.Equals(c2);
}
/// <param name="c1">C1.</param>
/// <param name="c2">C2.</param>
public static bool operator !=(Color c1, Color c2)
{
return c1 != null && !c1.Equals(c2);
}
/// <summary>
/// Serves as a hash function for a <see cref="Pulsar.Color"/> object.
/// </summary>
/// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a hash table.</returns>
public override int GetHashCode()
{
return A * R * G * B;
}
}
}
| |
/*
* Clipboard.cs - Widget class that manages an X clipboard.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace Xsharp
{
using System;
using System.Text;
using Xsharp.Types;
using Xsharp.Events;
using OpenSystem.Platform.X11;
/// <summary>
/// <para>The <see cref="T:Xsharp.Clipboard"/> class manages clipboards
/// within the X system.</para>
/// </summary>
public class Clipboard : InputOutputWidget
{
// Internal state.
private XAtom name;
private XAtom targets;
private String[] formats;
private byte[][] values;
/// <summary>
/// <para>Construct a new clipboard, associated with a particular
/// screen and selection name.</para>
/// </summary>
///
/// <param name="screen">
/// <para>The screen to attach the clipboard to, or <see langword="null"/>
/// to use the default screen.</para>
/// </param>
///
/// <param name="name">
/// <para>The name of the selection to use for clipboard access.
/// This is usually <c>PRIMARY</c> for the X selection or
/// <c>CLIPBOARD</c> for the explicit copy/cut/paste clipboard.</para>
/// </param>
///
/// <exception cref="T:System.ArgumentNullException">
/// <para>The <paramref name="name"/> parameter is
/// <see langword="null"/>.</para>
/// </exception>
public Clipboard(Screen screen, String name)
: base(TopLevelWindow.GetRoot(screen), -1, -1, 1, 1)
{
if(name == null)
{
throw new ArgumentNullException("name");
}
try
{
IntPtr display = dpy.Lock();
this.name = Xlib.XInternAtom
(display, name, XBool.False);
this.targets = Xlib.XInternAtom
(display, "TARGETS", XBool.False);
}
finally
{
dpy.Unlock();
}
}
/// <summary>
/// <para>Determine if we currently own the clipboard.</para>
/// </summary>
///
/// <value>
/// <para>Returns <see langword="true"/> if this process currently
/// has ownership of the clipboard.</para>
/// </value>
public bool OwnsClipboard
{
get
{
try
{
IntPtr display = dpy.Lock();
XWindow handle = GetWidgetHandle();
if(Xlib.XGetSelectionOwner (display, name) == handle)
{
return true;
}
else
{
return false;
}
}
finally
{
dpy.Unlock();
}
}
}
/// <summary>
/// <para>Get the list of formats that are currently stored on the
/// clipboard.</para>
/// </summary>
///
/// <returns>
/// <para>Returns an array of MIME types corresponding to the types
/// of values on the clipboard.</para>
/// </returns>
public String[] GetFormats()
{
// Bail out early if we own the clipboard ourselves.
if(OwnsClipboard)
{
return formats;
}
// TODO
// Could not get the format list.
return new String [0];
}
/// <summary>
/// <para>Get clipboard data in a particular MIME format.</para>
/// </summary>
///
/// <param name="format">
/// <para>The MIME format to request data for, or <see langword="null"/>
/// for plain text.</para>
/// </param>
///
/// <returns>
/// <para>The format's data, or <see langword="null"/> if data is
/// not available in the specified format.</para>
/// </returns>
public byte[] GetData(String format)
{
int posn;
// If no format is supplied, then assume "text/plain".
if(format == null)
{
format = "text/plain";
}
// Search our list of values if we have the clipboard.
if(OwnsClipboard)
{
if(formats == null)
{
return null;
}
for(posn = 0; posn < formats.Length; ++posn)
{
if(formats[posn] == format)
{
return values[posn];
}
}
return null;
}
// Ask the current clipboard owner for the data.
// TODO
// Could not get the data in the requested format.
return null;
}
/// <summary>
/// <para>Get clipboard data in string format.</para>
/// </summary>
///
/// <returns>
/// <para>The string data on the clipboard, or <see langword="null"/>
/// if there is no string data on the clipboard.</para>
/// </returns>
///
/// <remarks>
/// <para>This is a convenience routine to fetch data in
/// <c>text/plain</c> format.</para>
/// </remarks>
public String GetStringData()
{
byte[] data = GetData("text/plain");
if(data != null)
{
return Encoding.UTF8.GetString(data);
}
return null;
}
/// <summary>
/// <para>Set the contents of the clipboard to a specific set of
/// formats and values.</para>
/// </summary>
///
/// <param name="formats">
/// <para>The data formats that make up the data that is being placed
/// onto the clipboard.</para>
/// </param>
///
/// <param name="values">
/// <para>The data values that make up the data that is being placed
/// onto the clipboard.</para>
/// </param>
///
/// <exception cref="T:System.ArgumentNullException">
/// <para>Either <paramref name="formats"/> or <paramref name="values"/>
/// is <see langword="null"/>.</para>
/// </exception>
///
/// <exception cref="T:System.ArgumentException">
/// <para>The lengths of <paramref name="formats"/> and
/// <paramref name="values"/> do not match.</para>
/// </exception>
public void SetData(String[] formats, byte[][] values)
{
// Validate the parameters.
if(formats == null)
{
throw new ArgumentNullException("formats");
}
if(values == null)
{
throw new ArgumentNullException("values");
}
if(formats.Length != values.Length)
{
throw new ArgumentException
(S._("X_MismatchedClipboardLists"));
}
// Make a copy of the values that we were supplied.
this.formats = formats;
this.values = values;
// Grab the selection for ourselves, since we're now the owner.
try
{
IntPtr display = dpy.Lock();
Xlib.XSetSelectionOwner
(display, name, GetWidgetHandle(), dpy.knownEventTime);
}
finally
{
dpy.Unlock();
}
}
// Dispatch an event to this widget.
internal override void DispatchEvent(ref XEvent xevent)
{
switch((EventType)(xevent.xany.type__))
{
case EventType.SelectionClear:
{
// We have lost ownership of the selection.
formats = null;
values = null;
}
break;
case EventType.SelectionRequest:
{
// Bail out if we received a request from ourselves!
if(xevent.xselectionrequest.requestor ==
GetWidgetHandle())
{
break;
}
// Build the SelectionNotify event for the reply.
XEvent response = new XEvent();
response.xany.type = (int)(EventType.SelectionNotify);
response.xselection.requestor =
xevent.xselectionrequest.requestor;
response.xselection.selection =
xevent.xselectionrequest.selection;
response.xselection.target =
xevent.xselectionrequest.target;
response.xselection.property = XAtom.Zero;
response.xselection.time =
xevent.xselectionrequest.time;
// TODO
// Transmit the response back to the requestor.
try
{
IntPtr display = dpy.Lock();
Xlib.XSendEvent
(display,
xevent.xselectionrequest.requestor,
XBool.False,
(int)(EventMask.NoEventMask),
ref response);
}
finally
{
dpy.Unlock();
}
}
break;
}
base.DispatchEvent(ref xevent);
}
} // class Clipboard
} // namespace Xsharp
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Avalonia.Data;
using Avalonia.Logging;
using Avalonia.Utilities;
namespace Avalonia
{
/// <summary>
/// Maintains a list of prioritised bindings together with a current value.
/// </summary>
/// <remarks>
/// Bindings, in the form of <see cref="IObservable{Object}"/>s are added to the object using
/// the <see cref="Add"/> method. With the observable is passed a priority, where lower values
/// represent higher priorites. The current <see cref="Value"/> is selected from the highest
/// priority binding that doesn't return <see cref="AvaloniaProperty.UnsetValue"/>. Where there
/// are multiple bindings registered with the same priority, the most recently added binding
/// has a higher priority. Each time the value changes, the
/// <see cref="IPriorityValueOwner.Changed(PriorityValue, object, object)"/> method on the
/// owner object is fired with the old and new values.
/// </remarks>
internal class PriorityValue
{
private readonly Type _valueType;
private readonly SingleOrDictionary<int, PriorityLevel> _levels = new SingleOrDictionary<int, PriorityLevel>();
private object _value;
private readonly Func<object, object> _validate;
/// <summary>
/// Initializes a new instance of the <see cref="PriorityValue"/> class.
/// </summary>
/// <param name="owner">The owner of the object.</param>
/// <param name="property">The property that the value represents.</param>
/// <param name="valueType">The value type.</param>
/// <param name="validate">An optional validation function.</param>
public PriorityValue(
IPriorityValueOwner owner,
AvaloniaProperty property,
Type valueType,
Func<object, object> validate = null)
{
Owner = owner;
Property = property;
_valueType = valueType;
_value = AvaloniaProperty.UnsetValue;
ValuePriority = int.MaxValue;
_validate = validate;
}
/// <summary>
/// Gets the owner of the value.
/// </summary>
public IPriorityValueOwner Owner { get; }
/// <summary>
/// Gets the property that the value represents.
/// </summary>
public AvaloniaProperty Property { get; }
/// <summary>
/// Gets the current value.
/// </summary>
public object Value => _value;
/// <summary>
/// Gets the priority of the binding that is currently active.
/// </summary>
public int ValuePriority
{
get;
private set;
}
/// <summary>
/// Adds a new binding.
/// </summary>
/// <param name="binding">The binding.</param>
/// <param name="priority">The binding priority.</param>
/// <returns>
/// A disposable that will remove the binding.
/// </returns>
public IDisposable Add(IObservable<object> binding, int priority)
{
return GetLevel(priority).Add(binding);
}
/// <summary>
/// Sets the value for a specified priority.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="priority">The priority</param>
public void SetValue(object value, int priority)
{
GetLevel(priority).DirectValue = value;
}
/// <summary>
/// Gets the currently active bindings on this object.
/// </summary>
/// <returns>An enumerable collection of bindings.</returns>
public IEnumerable<PriorityBindingEntry> GetBindings()
{
foreach (var level in _levels)
{
foreach (var binding in level.Value.Bindings)
{
yield return binding;
}
}
}
/// <summary>
/// Returns diagnostic string that can help the user debug the bindings in effect on
/// this object.
/// </summary>
/// <returns>A diagnostic string.</returns>
public string GetDiagnostic()
{
var b = new StringBuilder();
var first = true;
foreach (var level in _levels)
{
if (!first)
{
b.AppendLine();
}
b.Append(ValuePriority == level.Key ? "*" : string.Empty);
b.Append("Priority ");
b.Append(level.Key);
b.Append(": ");
b.AppendLine(level.Value.Value?.ToString() ?? "(null)");
b.AppendLine("--------");
b.Append("Direct: ");
b.AppendLine(level.Value.DirectValue?.ToString() ?? "(null)");
foreach (var binding in level.Value.Bindings)
{
b.Append(level.Value.ActiveBindingIndex == binding.Index ? "*" : string.Empty);
b.Append(binding.Description ?? binding.Observable.GetType().Name);
b.Append(": ");
b.AppendLine(binding.Value?.ToString() ?? "(null)");
}
first = false;
}
return b.ToString();
}
/// <summary>
/// Called when the value for a priority level changes.
/// </summary>
/// <param name="level">The priority level of the changed entry.</param>
public void LevelValueChanged(PriorityLevel level)
{
if (level.Priority <= ValuePriority)
{
if (level.Value != AvaloniaProperty.UnsetValue)
{
UpdateValue(level.Value, level.Priority);
}
else
{
foreach (var i in _levels.Values.OrderBy(x => x.Priority))
{
if (i.Value != AvaloniaProperty.UnsetValue)
{
UpdateValue(i.Value, i.Priority);
return;
}
}
UpdateValue(AvaloniaProperty.UnsetValue, int.MaxValue);
}
}
}
/// <summary>
/// Called when a priority level encounters an error.
/// </summary>
/// <param name="level">The priority level of the changed entry.</param>
/// <param name="error">The binding error.</param>
public void LevelError(PriorityLevel level, BindingNotification error)
{
Logger.Log(
LogEventLevel.Error,
LogArea.Binding,
Owner,
"Error in binding to {Target}.{Property}: {Message}",
Owner,
Property,
error.Error.Message);
}
/// <summary>
/// Causes a revalidation of the value.
/// </summary>
public void Revalidate()
{
if (_validate != null)
{
PriorityLevel level;
if (_levels.TryGetValue(ValuePriority, out level))
{
UpdateValue(level.Value, level.Priority);
}
}
}
/// <summary>
/// Gets the <see cref="PriorityLevel"/> with the specified priority, creating it if it
/// doesn't already exist.
/// </summary>
/// <param name="priority">The priority.</param>
/// <returns>The priority level.</returns>
private PriorityLevel GetLevel(int priority)
{
PriorityLevel result;
if (!_levels.TryGetValue(priority, out result))
{
result = new PriorityLevel(this, priority);
_levels.Add(priority, result);
}
return result;
}
/// <summary>
/// Updates the current <see cref="Value"/> and notifies all subscibers.
/// </summary>
/// <param name="value">The value to set.</param>
/// <param name="priority">The priority level that the value came from.</param>
private void UpdateValue(object value, int priority)
{
var notification = value as BindingNotification;
object castValue;
if (notification != null)
{
value = (notification.HasValue) ? notification.Value : null;
}
if (TypeUtilities.TryConvertImplicit(_valueType, value, out castValue))
{
var old = _value;
if (_validate != null && castValue != AvaloniaProperty.UnsetValue)
{
castValue = _validate(castValue);
}
ValuePriority = priority;
_value = castValue;
if (notification?.HasValue == true)
{
notification.SetValue(castValue);
}
if (notification == null || notification.HasValue)
{
Owner?.Changed(this, old, _value);
}
if (notification != null)
{
Owner?.BindingNotificationReceived(this, notification);
}
}
else
{
Logger.Error(
LogArea.Binding,
Owner,
"Binding produced invalid value for {$Property} ({$PropertyType}): {$Value} ({$ValueType})",
Property.Name,
_valueType,
value,
value?.GetType());
}
}
}
}
| |
//Copyright 2010 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.
#if ASTORIA_CLIENT
namespace System.Data.Services.Client
#else
namespace System.Data.Services
#endif
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
#if ASTORIA_CLIENT
#if !ASTORIA_LIGHT
using System.Net;
#else
using System.Data.Services.Http;
#endif
#endif
internal class BatchStream : Stream
{
private const int DefaultBufferSize = 8000;
private readonly bool batchRequest;
private readonly byte[] byteBuffer;
private Stream reader;
private int byteLength;
private int bytePosition;
private Encoding batchEncoding;
private bool checkPreamble;
private string batchBoundary;
private int batchLength;
private int totalCount;
private string changesetBoundary;
private Encoding changesetEncoding;
private Dictionary<string, string> contentHeaders;
private Stream contentStream;
private bool disposeWithContentStreamDispose;
#if ASTORIA_SERVER
private string contentUri;
#else
private string statusCode;
#endif
private BatchStreamState batchState;
#if DEBUG && !ASTORIA_LIGHT
private MemoryStream writer = new MemoryStream();
#else
#pragma warning disable 649
private MemoryStream writer;
#pragma warning restore 649
#endif
internal BatchStream(Stream stream, string boundary, Encoding batchEncoding, bool requestStream)
{
Debug.Assert(null != stream, "null stream");
this.reader = stream;
this.byteBuffer = new byte[DefaultBufferSize];
this.batchBoundary = VerifyBoundary(boundary);
this.batchState = BatchStreamState.StartBatch;
this.batchEncoding = batchEncoding;
this.checkPreamble = (null != batchEncoding);
this.batchRequest = requestStream;
}
#region batch properties ContentHeaders, ContentStream, Encoding, Sate
public Dictionary<string, string> ContentHeaders
{
get { return this.contentHeaders; }
}
#if ASTORIA_SERVER
public string ContentUri
{
get { return this.contentUri; }
}
#endif
public Encoding Encoding
{
get { return this.changesetEncoding ?? this.batchEncoding; }
}
public BatchStreamState State
{
get { return this.batchState; }
}
#endregion
#region Stream properties
public override bool CanRead
{
get { return (null != this.reader && this.reader.CanRead); }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Length
{
get { throw Error.NotSupported(); }
}
public override long Position
{
get { throw Error.NotSupported(); }
set { throw Error.NotSupported(); }
}
#endregion
#region Stream methods
public override void Flush()
{
this.reader.Flush();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw Error.NotSupported();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw Error.NotSupported();
}
public override long Seek(long offset, SeekOrigin origin)
{
this.AssertOpen();
if (offset < 0)
{
throw Error.ArgumentOutOfRange("offset");
}
if (SeekOrigin.Current != origin)
{
throw Error.ArgumentOutOfRange("origin");
}
if (Int32.MaxValue == offset)
{
byte[] buffer = new byte[256];
while (0 < this.ReadDelimiter(buffer, 0, buffer.Length))
{
}
}
else if (0 < offset)
{
do
{
int count = Math.Min(checked((int)offset), Math.Min(this.byteLength, this.batchLength));
this.totalCount += count;
this.bytePosition += count;
this.byteLength -= count;
this.batchLength -= count;
offset -= count;
}
while ((0 < offset) && (this.batchLength != 0) && this.ReadBuffer());
}
Debug.Assert(0 <= this.byteLength, "negative byteLength");
Debug.Assert(0 <= this.batchLength, "negative batchLength");
return 0;
}
public override void SetLength(long value)
{
throw Error.NotSupported();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw Error.NotSupported();
}
#endregion
internal static bool GetBoundaryAndEncodingFromMultipartMixedContentType(string contentType, out string boundary, out Encoding encoding)
{
boundary = null;
encoding = null;
string mime;
KeyValuePair<string, string>[] parameters = HttpProcessUtility.ReadContentType(contentType, out mime, out encoding);
if (String.Equals(XmlConstants.MimeMultiPartMixed, mime, StringComparison.OrdinalIgnoreCase))
{
if (null != parameters)
{
foreach (KeyValuePair<string, string> parameter in parameters)
{
if (String.Equals(parameter.Key, XmlConstants.HttpMultipartBoundary, StringComparison.OrdinalIgnoreCase))
{
if (boundary != null)
{
boundary = null;
break;
}
boundary = parameter.Value;
}
}
}
if (String.IsNullOrEmpty(boundary))
{
throw Error.BatchStreamMissingBoundary();
}
}
return (null != boundary);
}
#if !ASTORIA_CLIENT
internal static bool IsBatchStream(Stream stream)
{
return (stream is StreamWithDelimiter || stream is StreamWithLength);
}
internal Exception ValidateNoDataBeyondEndOfBatch()
{
if (this.reader.ReadByte() >= 0)
{
return Error.BatchStreamMoreDataAfterEndOfBatch();
}
return null;
}
#endif
#if ASTORIA_CLIENT
internal string GetResponseVersion()
{
string result;
this.ContentHeaders.TryGetValue(XmlConstants.HttpDataServiceVersion, out result);
return result;
}
internal HttpStatusCode GetStatusCode()
{
return (HttpStatusCode)(null != this.statusCode ? Int32.Parse(this.statusCode, CultureInfo.InvariantCulture) : 500);
}
#endif
internal bool MoveNext()
{
#region dispose previous content stream
if (null == this.reader || this.disposeWithContentStreamDispose)
{
return false;
}
if (null != this.contentStream)
{
this.contentStream.Dispose();
}
Debug.Assert(0 <= this.byteLength, "negative byteLength");
Debug.Assert(0 <= this.batchLength, "negative batchLength");
#endregion
#region initialize start state to EndBatch or EndChangeSet
switch (this.batchState)
{
case BatchStreamState.EndBatch:
Debug.Assert(null == this.batchBoundary, "non-null batch boundary");
Debug.Assert(null == this.changesetBoundary, "non-null changesetBoundary boundary");
throw Error.BatchStreamInvalidBatchFormat();
case BatchStreamState.Get:
case BatchStreamState.GetResponse:
this.ClearPreviousOperationInformation();
goto case BatchStreamState.StartBatch;
case BatchStreamState.StartBatch:
case BatchStreamState.EndChangeSet:
Debug.Assert(null != this.batchBoundary, "null batch boundary");
Debug.Assert(null == this.changesetBoundary, "non-null changeset boundary");
this.batchState = BatchStreamState.EndBatch;
this.batchLength = Int32.MaxValue;
break;
case BatchStreamState.BeginChangeSet:
Debug.Assert(null != this.batchBoundary, "null batch boundary");
Debug.Assert(null != this.contentHeaders, "null contentHeaders");
Debug.Assert(null != this.changesetBoundary, "null changeset boundary");
this.contentHeaders = null;
this.changesetEncoding = null;
this.batchState = BatchStreamState.EndChangeSet;
break;
case BatchStreamState.ChangeResponse:
case BatchStreamState.Delete:
Debug.Assert(null != this.changesetBoundary, "null changeset boundary");
this.ClearPreviousOperationInformation();
this.batchState = BatchStreamState.EndChangeSet;
break;
case BatchStreamState.Post:
case BatchStreamState.Put:
case BatchStreamState.Merge:
Debug.Assert(null != this.changesetBoundary, "null changeset boundary");
this.batchState = BatchStreamState.EndChangeSet;
break;
default:
Debug.Assert(false, "unknown state");
throw Error.BatchStreamInvalidBatchFormat();
}
Debug.Assert(null == this.contentHeaders, "non-null content headers");
Debug.Assert(null == this.contentStream, "non-null content stream");
#if ASTORIA_SERVER
Debug.Assert(null == this.contentUri, "non-null content uri");
#endif
#if ASTORIA_CLIENT
Debug.Assert(null == this.statusCode, "non-null statusCode");
#endif
Debug.Assert(
this.batchState == BatchStreamState.EndBatch ||
this.batchState == BatchStreamState.EndChangeSet,
"unexpected state at start");
#endregion
#region read --delimiter
string delimiter = this.ReadLine();
if (String.IsNullOrEmpty(delimiter))
{
delimiter = this.ReadLine();
}
if (String.IsNullOrEmpty(delimiter))
{
throw Error.BatchStreamInvalidBatchFormat();
}
if (delimiter.EndsWith("--", StringComparison.Ordinal))
{
delimiter = delimiter.Substring(0, delimiter.Length - 2);
if ((null != this.changesetBoundary) && (delimiter == this.changesetBoundary))
{
Debug.Assert(this.batchState == BatchStreamState.EndChangeSet, "bad changeset boundary state");
this.changesetBoundary = null;
return true;
}
else if (delimiter == this.batchBoundary)
{
if (BatchStreamState.EndChangeSet == this.batchState)
{
throw Error.BatchStreamMissingEndChangesetDelimiter();
}
this.changesetBoundary = null;
this.batchBoundary = null;
if (this.byteLength != 0)
{
throw Error.BatchStreamMoreDataAfterEndOfBatch();
}
return false;
}
else
{
throw Error.BatchStreamInvalidDelimiter(delimiter);
}
}
else if ((null != this.changesetBoundary) && (delimiter == this.changesetBoundary))
{
Debug.Assert(this.batchState == BatchStreamState.EndChangeSet, "bad changeset boundary state");
}
else if (delimiter == this.batchBoundary)
{
if (this.batchState != BatchStreamState.EndBatch)
{
if (this.batchState == BatchStreamState.EndChangeSet)
{
throw Error.BatchStreamMissingEndChangesetDelimiter();
}
else
{
throw Error.BatchStreamInvalidBatchFormat();
}
}
}
else
{
throw Error.BatchStreamInvalidDelimiter(delimiter);
}
#endregion
#region read header with values in this form (([^:]*:.*)\r\n)*\r\n
this.ReadContentHeaders();
#endregion
#region should start changeset?
string contentType;
bool readHttpHeaders = false;
if (this.contentHeaders.TryGetValue(XmlConstants.HttpContentType, out contentType))
{
if (String.Equals(contentType, XmlConstants.MimeApplicationHttp, StringComparison.OrdinalIgnoreCase))
{
if (this.contentHeaders.Count != 2)
{
throw Error.BatchStreamInvalidNumberOfHeadersAtOperationStart(
XmlConstants.HttpContentType,
XmlConstants.HttpContentTransferEncoding);
}
string transferEncoding;
if (!this.contentHeaders.TryGetValue(XmlConstants.HttpContentTransferEncoding, out transferEncoding) ||
XmlConstants.BatchRequestContentTransferEncoding != transferEncoding)
{
throw Error.BatchStreamMissingOrInvalidContentEncodingHeader(
XmlConstants.HttpContentTransferEncoding,
XmlConstants.BatchRequestContentTransferEncoding);
}
readHttpHeaders = true;
}
else if (BatchStreamState.EndBatch == this.batchState)
{
string boundary;
Encoding encoding;
if (GetBoundaryAndEncodingFromMultipartMixedContentType(contentType, out boundary, out encoding))
{
this.changesetBoundary = VerifyBoundary(boundary);
this.changesetEncoding = encoding;
this.batchState = BatchStreamState.BeginChangeSet;
}
else
{
throw Error.BatchStreamInvalidContentTypeSpecified(
XmlConstants.HttpContentType,
contentType,
XmlConstants.MimeApplicationHttp,
XmlConstants.MimeMultiPartMixed);
}
if (this.contentHeaders.Count > 2 ||
(this.contentHeaders.Count == 2 && !this.contentHeaders.ContainsKey(XmlConstants.HttpContentLength)))
{
throw Error.BatchStreamInvalidNumberOfHeadersAtChangeSetStart(XmlConstants.HttpContentType, XmlConstants.HttpContentLength);
}
}
else
{
throw Error.BatchStreamInvalidContentTypeSpecified(
XmlConstants.HttpContentType,
contentType,
XmlConstants.MimeApplicationHttp,
XmlConstants.MimeMultiPartMixed);
}
}
else
{
throw Error.BatchStreamMissingContentTypeHeader(XmlConstants.HttpContentType);
}
#endregion
#region what is the operation and uri?
if (readHttpHeaders)
{
this.ReadHttpHeaders();
this.contentHeaders.TryGetValue(XmlConstants.HttpContentType, out contentType);
}
#endregion
#region does content have a fixed length?
string text = null;
int length = -1;
if (this.contentHeaders.TryGetValue(XmlConstants.HttpContentLength, out text))
{
length = Int32.Parse(text, CultureInfo.InvariantCulture);
if (length < 0)
{
throw Error.BatchStreamInvalidContentLengthSpecified(text);
}
if (this.batchState == BatchStreamState.BeginChangeSet)
{
this.batchLength = length;
}
else if (length != 0)
{
Debug.Assert(
this.batchState == BatchStreamState.Delete ||
this.batchState == BatchStreamState.Get ||
this.batchState == BatchStreamState.Post ||
this.batchState == BatchStreamState.Put ||
this.batchState == BatchStreamState.Merge,
"unexpected contentlength location");
this.contentStream = new StreamWithLength(this, length);
}
}
else
{
if (this.batchState == BatchStreamState.EndBatch)
{
this.batchLength = Int32.MaxValue;
}
if (this.batchState != BatchStreamState.BeginChangeSet)
{
this.contentStream = new StreamWithDelimiter(this);
}
}
#endregion
Debug.Assert(
this.batchState == BatchStreamState.BeginChangeSet ||
(this.batchRequest && (this.batchState == BatchStreamState.Delete ||
this.batchState == BatchStreamState.Get ||
this.batchState == BatchStreamState.Post ||
this.batchState == BatchStreamState.Put ||
this.batchState == BatchStreamState.Merge)) ||
(!this.batchRequest && (this.batchState == BatchStreamState.GetResponse ||
this.batchState == BatchStreamState.ChangeResponse)),
"unexpected state at return");
#region enforce if contentStream is expected, caller needs to enforce if contentStream is not expected
if (null == this.contentStream)
{
switch (this.batchState)
{
case BatchStreamState.BeginChangeSet:
case BatchStreamState.Delete:
case BatchStreamState.Get:
case BatchStreamState.ChangeResponse:
case BatchStreamState.GetResponse:
break;
case BatchStreamState.Post:
case BatchStreamState.Put:
case BatchStreamState.Merge:
default:
throw Error.BatchStreamContentExpected(this.batchState);
}
}
#endregion
#region enforce if contentType not is expected, caller needs to enforce if contentType is expected
if (!String.IsNullOrEmpty(contentType))
{
switch (this.batchState)
{
case BatchStreamState.BeginChangeSet:
case BatchStreamState.Post:
case BatchStreamState.Put:
case BatchStreamState.Merge:
case BatchStreamState.GetResponse:
case BatchStreamState.ChangeResponse:
break;
case BatchStreamState.Get:
case BatchStreamState.Delete:
default:
throw Error.BatchStreamContentUnexpected(this.batchState);
}
}
#endregion
return true;
}
internal Stream GetContentStream()
{
return this.contentStream;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (null != this.contentStream)
{
this.disposeWithContentStreamDispose = true;
}
else
{
this.byteLength = 0;
if (null != this.reader)
{
this.reader.Dispose();
this.reader = null;
}
this.contentHeaders = null;
if (null != this.contentStream)
{
this.contentStream.Dispose();
}
if (null != this.writer)
{
this.writer.Dispose();
}
}
}
base.Dispose(disposing);
}
private static BatchStreamState GetStateBasedOnHttpMethodName(string methodName)
{
if (XmlConstants.HttpMethodGet.Equals(methodName, StringComparison.Ordinal))
{
return BatchStreamState.Get;
}
else if (XmlConstants.HttpMethodDelete.Equals(methodName, StringComparison.Ordinal))
{
return BatchStreamState.Delete;
}
else if (XmlConstants.HttpMethodPost.Equals(methodName, StringComparison.Ordinal))
{
return BatchStreamState.Post;
}
else if (XmlConstants.HttpMethodPut.Equals(methodName, StringComparison.Ordinal))
{
return BatchStreamState.Put;
}
else if (XmlConstants.HttpMethodMerge.Equals(methodName, StringComparison.Ordinal))
{
return BatchStreamState.Merge;
}
else
{
throw Error.BatchStreamInvalidHttpMethodName(methodName);
}
}
private static string VerifyBoundary(string boundary)
{
if ((null == boundary) || (70 < boundary.Length))
{
throw Error.BatchStreamInvalidDelimiter(boundary);
}
foreach (char c in boundary)
{
if ((127 < (int)c) || Char.IsWhiteSpace(c) || Char.IsControl(c))
{
throw Error.BatchStreamInvalidDelimiter(boundary);
}
}
return "--" + boundary;
}
private void ClearPreviousOperationInformation()
{
this.contentHeaders = null;
this.contentStream = null;
#if ASTORIA_SERVER
this.contentUri = null;
#endif
#if ASTORIA_CLIENT
this.statusCode = null;
#endif
}
private void Append(ref byte[] buffer, int count)
{
int oldSize = (null != buffer) ? buffer.Length : 0;
byte[] tmp = new byte[oldSize + count];
if (0 < oldSize)
{
Buffer.BlockCopy(buffer, 0, tmp, 0, oldSize);
}
Buffer.BlockCopy(this.byteBuffer, this.bytePosition, tmp, oldSize, count);
buffer = tmp;
this.totalCount += count;
this.bytePosition += count;
this.byteLength -= count;
this.batchLength -= count;
Debug.Assert(0 <= this.byteLength, "negative byteLength");
Debug.Assert(0 <= this.batchLength, "negative batchLength");
}
private void AssertOpen()
{
if (null == this.reader)
{
Error.ThrowObjectDisposed(this.GetType());
}
}
private bool ReadBuffer()
{
this.AssertOpen();
if (0 == this.byteLength)
{
this.bytePosition = 0;
this.byteLength = this.reader.Read(this.byteBuffer, this.bytePosition, this.byteBuffer.Length);
if (null != this.writer)
{
this.writer.Write(this.byteBuffer, this.bytePosition, this.byteLength);
}
if (null == this.batchEncoding)
{
this.batchEncoding = this.DetectEncoding();
}
else if (null != this.changesetEncoding)
{
this.changesetEncoding = this.DetectEncoding();
}
else if (this.checkPreamble)
{
bool match = true;
byte[] preamble = this.batchEncoding.GetPreamble();
if (preamble.Length <= this.byteLength)
{
for (int i = 0; i < preamble.Length; ++i)
{
if (preamble[i] != this.byteBuffer[i])
{
match = false;
break;
}
}
if (match)
{
this.byteLength -= preamble.Length;
this.bytePosition += preamble.Length;
}
}
this.checkPreamble = false;
}
return (0 < this.byteLength);
}
return true;
}
private String ReadLine()
{
if ((0 == this.batchLength) || !this.ReadBuffer())
{
return null;
}
byte[] buffer = null;
do
{
Debug.Assert(0 < this.byteLength, "out of bytes");
Debug.Assert(this.bytePosition + this.byteLength <= this.byteBuffer.Length, "byte tracking out of range");
int i = this.bytePosition;
int end = i + Math.Min(this.byteLength, this.batchLength);
do
{
char ch = (char)this.byteBuffer[i];
if (('\r' == ch) || ('\n' == ch))
{
string s;
i -= this.bytePosition;
if (null != buffer)
{
this.Append(ref buffer, i);
s = this.Encoding.GetString(buffer, 0, buffer.Length);
}
else
{
s = this.Encoding.GetString(this.byteBuffer, this.bytePosition, i);
this.totalCount += i;
this.bytePosition += i;
this.byteLength -= i;
this.batchLength -= i;
}
this.totalCount++;
this.bytePosition++;
this.byteLength--;
this.batchLength--;
if (('\r' == ch) && ((0 < this.byteLength) || this.ReadBuffer()) && (0 < this.batchLength))
{
ch = (char)this.byteBuffer[this.bytePosition];
if ('\n' == ch)
{
this.totalCount++;
this.bytePosition++;
this.byteLength--;
this.batchLength--;
}
}
Debug.Assert(0 <= this.byteLength, "negative byteLength");
Debug.Assert(0 <= this.batchLength, "negative batchLength");
return s;
}
i++;
}
while (i < end);
i -= this.bytePosition;
this.Append(ref buffer, i);
}
while (this.ReadBuffer() && (0 < this.batchLength));
Debug.Assert(0 <= this.byteLength, "negative byteLength");
Debug.Assert(0 <= this.batchLength, "negative batchLength");
return this.Encoding.GetString(buffer, 0, buffer.Length);
}
private Encoding DetectEncoding()
{
if (this.byteLength < 2)
{
#if !ASTORIA_LIGHT
return Encoding.ASCII;
#else
return HttpProcessUtility.FallbackEncoding;
#endif
}
else if (this.byteBuffer[0] == 0xFE && this.byteBuffer[1] == 0xFF)
{
this.bytePosition = 2;
this.byteLength -= 2;
return new UnicodeEncoding(true, true);
}
else if (this.byteBuffer[0] == 0xFF && this.byteBuffer[1] == 0xFE)
{
if (this.byteLength >= 4 &&
this.byteBuffer[2] == 0 &&
this.byteBuffer[3] == 0)
{
#if !ASTORIA_LIGHT
this.bytePosition = 4;
this.byteLength -= 4;
return new UTF32Encoding(false, true);
#else
throw Error.NotSupported();
#endif
}
else
{
this.bytePosition = 2;
this.byteLength -= 2;
return new UnicodeEncoding(false, true);
}
}
else if (this.byteLength >= 3 &&
this.byteBuffer[0] == 0xEF &&
this.byteBuffer[1] == 0xBB &&
this.byteBuffer[2] == 0xBF)
{
this.bytePosition = 3;
this.byteLength -= 3;
return Encoding.UTF8;
}
else if (this.byteLength >= 4 &&
this.byteBuffer[0] == 0 &&
this.byteBuffer[1] == 0 &&
this.byteBuffer[2] == 0xFE &&
this.byteBuffer[3] == 0xFF)
{
#if !ASTORIA_LIGHT
this.bytePosition = 4;
this.byteLength -= 4;
return new UTF32Encoding(true, true);
#else
throw Error.NotSupported();
#endif
}
else
{
#if !ASTORIA_LIGHT
return Encoding.ASCII;
#else
return HttpProcessUtility.FallbackEncoding;
#endif
}
}
private int ReadDelimiter(byte[] buffer, int offset, int count)
{
Debug.Assert(null != buffer, "null != buffer");
Debug.Assert(0 <= offset, "0 <= offset");
Debug.Assert(0 <= count, "0 <= count");
Debug.Assert(offset + count <= buffer.Length, "offset + count <= buffer.Length");
int copied = 0;
string boundary = null;
string boundary1 = this.batchBoundary;
string boundary2 = this.changesetBoundary;
while ((0 < count) && (0 < this.batchLength) && this.ReadBuffer())
{
int boundaryIndex = 0;
int boundary1Index = 0;
int boundary2Index = 0;
int size = Math.Min(Math.Min(count, this.byteLength), this.batchLength) + this.bytePosition;
byte[] data = this.byteBuffer;
for (int i = this.bytePosition; i < size; ++i)
{
byte value = data[i];
buffer[offset++] = value;
if ((char)value == boundary1[boundary1Index])
{
if (boundary1.Length == ++boundary1Index)
{
size = (1 + i) - boundary1Index;
offset -= boundary1Index;
Debug.Assert(this.bytePosition <= size, "negative size");
break;
}
}
else
{
boundary1Index = 0;
}
if ((null != boundary2) && ((char)value == boundary2[boundary2Index]))
{
if (boundary2.Length == ++boundary2Index)
{
size = (1 + i) - boundary2Index;
offset -= boundary2Index;
Debug.Assert(this.bytePosition <= size, "negative size");
break;
}
}
else
{
boundary2Index = 0;
}
}
size -= this.bytePosition;
Debug.Assert(0 <= size, "negative size");
if (boundary1Index < boundary2Index)
{
boundaryIndex = boundary2Index;
boundary = boundary2;
}
else
{
Debug.Assert(null != boundary1, "batch boundary shouldn't be null");
boundaryIndex = boundary1Index;
boundary = boundary1;
}
if (size == this.batchLength)
{
boundaryIndex = 0;
}
if ((0 < boundaryIndex) && (boundary.Length != boundaryIndex))
{
if ((size + copied == boundaryIndex) && (boundaryIndex < this.byteLength))
{
throw Error.BatchStreamInternalBufferRequestTooSmall();
}
else
{
size -= boundaryIndex;
offset -= boundaryIndex;
}
}
this.totalCount += size;
this.bytePosition += size;
this.byteLength -= size;
this.batchLength -= size;
count -= size;
copied += size;
if (boundaryIndex > 0 && copied >= 2 && buffer[copied - 2] == '\r' && buffer[copied - 1] == '\n')
{
copied -= 2;
}
if (boundary.Length == boundaryIndex)
{
break;
}
else if (0 < boundaryIndex)
{
if (boundaryIndex == this.byteLength)
{
if (0 < this.bytePosition)
{
Buffer.BlockCopy(data, this.bytePosition, data, 0, this.byteLength);
this.bytePosition = 0;
}
int tmp = this.reader.Read(this.byteBuffer, this.byteLength, this.byteBuffer.Length - this.byteLength);
if (null != this.writer)
{
this.writer.Write(this.byteBuffer, this.byteLength, tmp);
}
if (0 == tmp)
{
this.totalCount += boundaryIndex;
this.bytePosition += boundaryIndex;
this.byteLength -= boundaryIndex;
this.batchLength -= boundaryIndex;
offset += boundaryIndex;
count -= boundaryIndex;
copied += boundaryIndex;
break;
}
this.byteLength += tmp;
}
else
{
break;
}
}
}
return copied;
}
private int ReadLength(byte[] buffer, int offset, int count)
{
Debug.Assert(null != buffer, "null != buffer");
Debug.Assert(0 <= offset, "0 <= offset");
Debug.Assert(0 <= count, "0 <= count");
Debug.Assert(offset + count <= buffer.Length, "offset + count <= buffer.Length");
int copied = 0;
if (0 < this.byteLength)
{
int size = Math.Min(Math.Min(count, this.byteLength), this.batchLength);
Buffer.BlockCopy(this.byteBuffer, this.bytePosition, buffer, offset, size);
this.totalCount += size;
this.bytePosition += size;
this.byteLength -= size;
this.batchLength -= size;
offset += size;
count -= size;
copied = size;
}
if (0 < count && this.batchLength > 0)
{
int size = this.reader.Read(buffer, offset, Math.Min(count, this.batchLength));
if (null != this.writer)
{
this.writer.Write(buffer, offset, size);
}
this.totalCount += size;
this.batchLength -= size;
copied += size;
}
Debug.Assert(0 <= this.byteLength, "negative byteLength");
Debug.Assert(0 <= this.batchLength, "negative batchLength");
return copied;
}
private void ReadContentHeaders()
{
this.contentHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
while (true)
{
string line = this.ReadLine();
if (0 < line.Length)
{
int colon = line.IndexOf(':');
if (colon <= 0)
{
throw Error.BatchStreamInvalidHeaderValueSpecified(line);
}
string name = line.Substring(0, colon).Trim();
string value = line.Substring(colon + 1).Trim();
this.contentHeaders.Add(name, value);
}
else
{
break;
}
}
}
private void ReadHttpHeaders()
{
string line = this.ReadLine();
int index1 = line.IndexOf(' ');
if ((index1 <= 0) || ((line.Length - 3) <= index1))
{
throw Error.BatchStreamInvalidMethodHeaderSpecified(line);
}
int index2 = (this.batchRequest ? line.LastIndexOf(' ') : line.IndexOf(' ', index1 + 1));
if ((index2 < 0) || (index2 - index1 - 1 <= 0) || ((line.Length - 1) <= index2))
{
throw Error.BatchStreamInvalidMethodHeaderSpecified(line);
}
string segment1 = line.Substring(0, index1);
string segment2 = line.Substring(index1 + 1, index2 - index1 - 1);
string segment3 = line.Substring(index2 + 1);
#region validate HttpVersion
string httpVersion = this.batchRequest ? segment3 : segment1;
if (httpVersion != XmlConstants.HttpVersionInBatching)
{
throw Error.BatchStreamInvalidHttpVersionSpecified(httpVersion, XmlConstants.HttpVersionInBatching);
}
#endregion
this.ReadContentHeaders();
BatchStreamState state;
if (this.batchRequest)
{
state = GetStateBasedOnHttpMethodName(segment1);
#if ASTORIA_SERVER
this.contentUri = segment2;
#endif
}
else
{
state = (BatchStreamState.EndBatch == this.batchState) ? BatchStreamState.GetResponse : BatchStreamState.ChangeResponse;
#if ASTORIA_CLIENT
this.statusCode = segment2;
#endif
}
#region validate state change
Debug.Assert(
BatchStreamState.EndBatch == this.batchState ||
BatchStreamState.EndChangeSet == this.batchState,
"unexpected BatchStreamState");
if (this.batchState == BatchStreamState.EndBatch)
{
if ((this.batchRequest && (state == BatchStreamState.Get)) ||
(!this.batchRequest && (state == BatchStreamState.GetResponse)))
{
this.batchState = state;
}
else
{
throw Error.BatchStreamOnlyGETOperationsCanBeSpecifiedInBatch();
}
}
else if (this.batchState == BatchStreamState.EndChangeSet)
{
if ((this.batchRequest && ((BatchStreamState.Post == state) || (BatchStreamState.Put == state) || (BatchStreamState.Delete == state) || (BatchStreamState.Merge == state))) ||
(!this.batchRequest && (state == BatchStreamState.ChangeResponse)))
{
this.batchState = state;
}
else
{
this.batchState = BatchStreamState.Post;
throw Error.BatchStreamGetMethodNotSupportInChangeset();
}
}
else
{
throw Error.BatchStreamInvalidOperationHeaderSpecified();
}
#endregion
}
private sealed class StreamWithDelimiter : StreamWithLength
{
internal StreamWithDelimiter(BatchStream stream)
: base(stream, Int32.MaxValue)
{
}
public override int Read(byte[] buffer, int offset, int count)
{
if (null == this.Target)
{
Error.ThrowObjectDisposed(this.GetType());
}
int result = this.Target.ReadDelimiter(buffer, offset, count);
return result;
}
}
private class StreamWithLength : Stream
{
private BatchStream target;
private int length;
internal StreamWithLength(BatchStream stream, int contentLength)
{
Debug.Assert(null != stream, "null != stream");
Debug.Assert(0 < contentLength, "0 < contentLength");
this.target = stream;
this.length = contentLength;
}
public override bool CanRead
{
get { return (null != this.target && this.target.CanRead); }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Length
{
get { throw Error.NotSupported(); }
}
public override long Position
{
get { throw Error.NotSupported(); }
set { throw Error.NotSupported(); }
}
internal BatchStream Target
{
get { return this.target; }
}
public override void Flush()
{
}
#if DEBUG && !ASTORIA_LIGHT
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw Error.NotSupported();
}
#endif
public override int Read(byte[] buffer, int offset, int count)
{
if (null == this.target)
{
Error.ThrowObjectDisposed(this.GetType());
}
int result = this.target.ReadLength(buffer, offset, Math.Min(count, this.length));
this.length -= result;
Debug.Assert(0 <= this.length, "Read beyond expected length");
return result;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw Error.NotSupported();
}
public override void SetLength(long value)
{
throw Error.NotSupported();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw Error.NotSupported();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && (null != this.target))
{
if (this.target.disposeWithContentStreamDispose)
{
this.target.contentStream = null;
this.target.Dispose();
}
else if (0 < this.length)
{
if (null != this.target.reader)
{
this.target.Seek(this.length, SeekOrigin.Current);
}
this.length = 0;
}
this.target.ClearPreviousOperationInformation();
}
this.target = null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Zenject;
using NUnit.Framework;
using ModestTree;
using Assert=ModestTree.Assert;
namespace Zenject.Tests
{
[TestFixture]
public class TestAllInjectionTypes : TestWithContainer
{
[Test]
// Test all variations of injection
public void TestCase1()
{
Container.Bind<Test0>().ToInstance(new Test0());
Container.Bind<IFoo>().ToSingle<FooDerived>();
Assert.That(Container.ValidateResolve<IFoo>().IsEmpty());
var foo = Container.Resolve<IFoo>();
Assert.That(foo.DidPostInjectBase);
Assert.That(foo.DidPostInjectDerived);
}
class Test0
{
}
interface IFoo
{
bool DidPostInjectBase
{
get;
}
bool DidPostInjectDerived
{
get;
}
}
abstract class FooBase : IFoo
{
bool _didPostInjectBase;
[Inject]
public static Test0 BaseStaticFieldPublic = null;
[Inject]
private static Test0 BaseStaticFieldPrivate = null;
[Inject]
protected static Test0 BaseStaticFieldProtected = null;
[Inject]
public static Test0 BaseStaticPropertyPublic
{
get;
set;
}
[Inject]
private static Test0 BaseStaticPropertyPrivate
{
get;
set;
}
[Inject]
protected static Test0 BaseStaticPropertyProtected
{
get;
set;
}
// Instance
[Inject]
public Test0 BaseFieldPublic = null;
[Inject]
private Test0 BaseFieldPrivate = null;
[Inject]
protected Test0 BaseFieldProtected = null;
[Inject]
public Test0 BasePropertyPublic
{
get;
set;
}
[Inject]
private Test0 BasePropertyPrivate
{
get;
set;
}
[Inject]
protected Test0 BasePropertyProtected
{
get;
set;
}
[PostInject]
public void PostInjectBase()
{
Assert.IsNull(BaseStaticFieldPublic);
Assert.IsNull(BaseStaticFieldPrivate);
Assert.IsNull(BaseStaticFieldProtected);
Assert.IsNull(BaseStaticPropertyPublic);
Assert.IsNull(BaseStaticPropertyPrivate);
Assert.IsNull(BaseStaticPropertyProtected);
Assert.IsNotNull(BaseFieldPublic);
Assert.IsNotNull(BaseFieldPrivate);
Assert.IsNotNull(BaseFieldProtected);
Assert.IsNotNull(BasePropertyPublic);
Assert.IsNotNull(BasePropertyPrivate);
Assert.IsNotNull(BasePropertyProtected);
_didPostInjectBase = true;
}
public bool DidPostInjectBase
{
get
{
return _didPostInjectBase;
}
}
public abstract bool DidPostInjectDerived
{
get;
}
}
class FooDerived : FooBase
{
public bool _didPostInject;
public Test0 ConstructorParam;
public override bool DidPostInjectDerived
{
get
{
return _didPostInject;
}
}
[Inject]
public static Test0 DerivedStaticFieldPublic = null;
[Inject]
private static Test0 DerivedStaticFieldPrivate = null;
[Inject]
protected static Test0 DerivedStaticFieldProtected = null;
[Inject]
public static Test0 DerivedStaticPropertyPublic
{
get;
set;
}
[Inject]
private static Test0 DerivedStaticPropertyPrivate
{
get;
set;
}
[Inject]
protected static Test0 DerivedStaticPropertyProtected
{
get;
set;
}
// Instance
public FooDerived(Test0 param)
{
ConstructorParam = param;
}
[PostInject]
public void PostInject()
{
Assert.IsNull(DerivedStaticFieldPublic);
Assert.IsNull(DerivedStaticFieldPrivate);
Assert.IsNull(DerivedStaticFieldProtected);
Assert.IsNull(DerivedStaticPropertyPublic);
Assert.IsNull(DerivedStaticPropertyPrivate);
Assert.IsNull(DerivedStaticPropertyProtected);
Assert.IsNotNull(DerivedFieldPublic);
Assert.IsNotNull(DerivedFieldPrivate);
Assert.IsNotNull(DerivedFieldProtected);
Assert.IsNotNull(DerivedPropertyPublic);
Assert.IsNotNull(DerivedPropertyPrivate);
Assert.IsNotNull(DerivedPropertyProtected);
Assert.IsNotNull(ConstructorParam);
_didPostInject = true;
}
[Inject]
public Test0 DerivedFieldPublic = null;
[Inject]
private Test0 DerivedFieldPrivate = null;
[Inject]
protected Test0 DerivedFieldProtected = null;
[Inject]
public Test0 DerivedPropertyPublic
{
get;
set;
}
[Inject]
private Test0 DerivedPropertyPrivate
{
get;
set;
}
[Inject]
protected Test0 DerivedPropertyProtected
{
get;
set;
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using Microsoft.Extensions.Logging.Internal;
using Xunit;
namespace LoggingAdvanced.Console.Test.Legacy
{
public class FormattedLogValuesTest
{
[Theory]
[InlineData("", "", null)]
[InlineData("", "", new object[] { })]
[InlineData("arg1 arg2", "{0} {1}", new object[] { "arg1", "arg2" })]
[InlineData("arg1 arg2", "{Start} {End}", new object[] { "arg1", "arg2" })]
[InlineData("arg1 arg2", "{Start,-6} {End,6}", new object[] { "arg1", "arg2" })]
[InlineData("0064", "{Hex:X4}", new object[] { 100 })]
public void LogValues_With_Basic_Types(string expected, string format, object[] args)
{
var logValues = new FormattedLogValues(format, args);
Assert.Equal(expected, logValues.ToString());
// Original format is expected to be returned from GetValues.
Assert.Equal(format, logValues.First(v => v.Key == "{OriginalFormat}").Value);
}
[Theory]
[InlineData("[null]", null, null)]
[InlineData("[null]", null, new object[] { })]
[InlineData("[null]", null, new object[] { null })]
[InlineData("[null]", null, new object[] { 1 })]
public void Log_NullFormat(string expected, string format, object[] args)
{
var logValues = new FormattedLogValues(format, args);
Assert.Equal(expected, logValues.ToString());
}
[Theory]
[InlineData("(null), (null) : (null)", "{0} : {1}", new object[] { new object[] { null, null }, null })]
[InlineData("(null)", "{0}", new object[] { null })]
public void LogValues_WithNulls(string expected, string format, object[] args)
{
var logValues = new FormattedLogValues(format, args);
Assert.Equal(expected, logValues.ToString());
}
[Theory]
[InlineData("1 2015", "{Year,6:d yyyy}")]
[InlineData("1:01:2015 AM,: 01", "{Year,-10:d:MM:yyyy tt},:{second,10:ss}")]
[InlineData("{prefix{1 2015}suffix}", "{{prefix{{{Year,6:d yyyy}}}suffix}}")]
public void LogValues_With_DateTime(string expected, string format)
{
var dateTime = new DateTime(2015, 1, 1, 1, 1, 1);
var logValues = new FormattedLogValues(format, new object[] { dateTime, dateTime });
Assert.Equal(expected, logValues.ToString());
// Original format is expected to be returned from GetValues.
Assert.Equal(format, logValues.First(v => v.Key == "{OriginalFormat}").Value);
}
[Theory]
[InlineData("{{", "{{", null)]
[InlineData("'{{'", "'{{'", null)]
[InlineData("'{{}}'", "'{{}}'", null)]
[InlineData("arg1 arg2 '{}' '{' '{:}' '{,:}' {,}- test string",
"{0} {1} '{{}}' '{{' '{{:}}' '{{,:}}' {{,}}- test string",
new object[] { "arg1", "arg2" })]
[InlineData("{prefix{arg1}suffix}", "{{prefix{{{Argument}}}suffix}}", new object[] { "arg1" })]
public void LogValues_With_Escaped_Braces(string expected, string format, object[] args)
{
var logValues = args == null ?
new FormattedLogValues(format) :
new FormattedLogValues(format, args);
Assert.Equal(expected, logValues.ToString());
// Original format is expected to be returned from GetValues.
Assert.Equal(format, logValues.First(v => v.Key == "{OriginalFormat}").Value);
}
[Theory]
[InlineData("{foo")]
[InlineData("bar}")]
[InlineData("{foo bar}}")]
public void LogValues_With_UnbalancedBraces(string format)
{
Assert.Throws<FormatException>(() =>
{
var logValues = new FormattedLogValues(format, new object[] { "arg1" });
logValues.ToString();
});
}
// message format, format arguments, expected message
public static TheoryData<string, object[], string> FormatsEnumerableValuesData
{
get
{
return new TheoryData<string, object[], string>
{
// null value
{
"The view '{ViewName}' was not found. Searched locations: {SearchedLocations}",
new object[] { "Index", null },
"The view 'Index' was not found. Searched locations: (null)"
},
// empty enumerable
{
"The view '{ViewName}' was not found. Searched locations: {SearchedLocations}",
new object[] { "Index", new string[] { } },
"The view 'Index' was not found. Searched locations: "
},
// single item enumerable
{
"The view '{ViewName}' was not found. Searched locations: {SearchedLocations}",
new object[] { "Index", new[] { "Views/Home/Index.cshtml" } },
"The view 'Index' was not found. Searched locations: Views/Home/Index.cshtml"
},
// null value item in enumerable
{
"The view '{ViewName}' was not found. Searched locations: {SearchedLocations}",
new object[] { "Index", new string[] { null } },
"The view 'Index' was not found. Searched locations: (null)"
},
// null value item in enumerable
{
"The view '{ViewName}' was not found. Searched locations: {SearchedLocations}",
new object[] { "Index", new string[] { null, "Views/Home/Index.cshtml" } },
"The view 'Index' was not found. Searched locations: (null), Views/Home/Index.cshtml"
},
// multi item enumerable
{
"The view '{ViewName}' was not found. Searched locations: {SearchedLocations}",
new object[] { "Index", new[] { "Views/Home/Index.cshtml", "Views/Shared/Index.cshtml" } },
"The view 'Index' was not found. Searched locations: " +
"Views/Home/Index.cshtml, Views/Shared/Index.cshtml"
},
// non-string enumerable. ToString() should be called on non-string types
{
"Media type '{MediaType}' did not match any of the supported media types." +
"Supported media types: {SupportedMediaTypes}",
new object[]
{
new MediaType("application", "blah"),
new[]
{
new MediaType("text", "foo"),
new MediaType("application", "xml")
}
},
"Media type 'application/blah' did not match any of the supported media types." +
"Supported media types: text/foo, application/xml"
},
// List<string> parameter
{
"The view '{ViewName}' was not found. Searched locations: {SearchedLocations}",
new object[] { "Index", new[] { "Home/Index.cshtml", "Shared/Index.cshtml" }.ToList() },
"The view 'Index' was not found. Searched locations: " +
"Home/Index.cshtml, Shared/Index.cshtml"
},
// We support only one level of enumerable value
{
"The view '{ViewName}' was not found. Searched locations: {SearchedLocations}",
new object[] { "Index", new[] { new[] { "abc", "def" }, new[] { "ghi", "jkl" } } },
"The view 'Index' was not found. Searched locations: " +
"System.String[], System.String[]"
},
// sub-enumerable having null value item
{
"The view '{ViewName}' was not found. Searched locations: {SearchedLocations}",
new object[] { "Index", new Uri[][] { null, new[] { new Uri("http://def") } } },
"The view 'Index' was not found. Searched locations: " +
"(null), System.Uri[]"
},
// non-string sub-enumerables
{
"The view '{ViewName}' was not found. Searched locations: {SearchedLocations}",
new object[] { "Index", new[] { new Uri[] { null }, new[] { new Uri("http://def") } } },
"The view 'Index' was not found. Searched locations: " +
"System.Uri[], System.Uri[]"
}
};
}
}
[Theory]
[MemberData(nameof(FormatsEnumerableValuesData))]
public void FormatsEnumerableValues(string messageFormat, object[] arguments, string expected)
{
var logValues = new FormattedLogValues(messageFormat, arguments);
Assert.Equal(expected, logValues.ToString());
}
private class MediaType
{
public MediaType(string type, string subType)
{
Type = type;
SubType = subType;
}
public string Type { get; }
public string SubType { get; }
public override string ToString()
{
return $"{Type}/{SubType}";
}
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
#if FEATURE_PERFTRACING
namespace System.Diagnostics.Tracing
{
[StructLayout(LayoutKind.Sequential)]
internal struct EventPipeEventInstanceData
{
internal IntPtr ProviderID;
internal uint EventID;
internal uint ThreadID;
internal long TimeStamp;
internal Guid ActivityId;
internal Guid ChildActivityId;
internal IntPtr Payload;
internal uint PayloadLength;
}
[StructLayout(LayoutKind.Sequential)]
internal struct EventPipeSessionInfo
{
internal long StartTimeAsUTCFileTime;
internal long StartTimeStamp;
internal long TimeStampFrequency;
}
[StructLayout(LayoutKind.Sequential)]
internal struct EventPipeProviderConfiguration
{
[MarshalAs(UnmanagedType.LPWStr)]
private readonly string m_providerName;
private readonly ulong m_keywords;
private readonly uint m_loggingLevel;
[MarshalAs(UnmanagedType.LPWStr)]
private readonly string? m_filterData;
internal EventPipeProviderConfiguration(
string providerName,
ulong keywords,
uint loggingLevel,
string? filterData)
{
if (string.IsNullOrEmpty(providerName))
{
throw new ArgumentNullException(nameof(providerName));
}
if (loggingLevel > 5) // 5 == Verbose, the highest value in EventPipeLoggingLevel.
{
throw new ArgumentOutOfRangeException(nameof(loggingLevel));
}
m_providerName = providerName;
m_keywords = keywords;
m_loggingLevel = loggingLevel;
m_filterData = filterData;
}
internal string ProviderName
{
get { return m_providerName; }
}
internal ulong Keywords
{
get { return m_keywords; }
}
internal uint LoggingLevel
{
get { return m_loggingLevel; }
}
internal string? FilterData => m_filterData;
}
internal enum EventPipeSerializationFormat
{
NetPerf,
NetTrace
}
internal sealed class EventPipeWaitHandle : WaitHandle
{
}
internal sealed class EventPipeConfiguration
{
private readonly string m_outputFile;
private readonly EventPipeSerializationFormat m_format;
private readonly uint m_circularBufferSizeInMB;
private readonly List<EventPipeProviderConfiguration> m_providers;
private TimeSpan m_minTimeBetweenSamples = TimeSpan.FromMilliseconds(1);
internal EventPipeConfiguration(
string outputFile,
EventPipeSerializationFormat format,
uint circularBufferSizeInMB)
{
if (string.IsNullOrEmpty(outputFile))
{
throw new ArgumentNullException(nameof(outputFile));
}
if (circularBufferSizeInMB == 0)
{
throw new ArgumentOutOfRangeException(nameof(circularBufferSizeInMB));
}
m_outputFile = outputFile;
m_format = format;
m_circularBufferSizeInMB = circularBufferSizeInMB;
m_providers = new List<EventPipeProviderConfiguration>();
}
internal string OutputFile
{
get { return m_outputFile; }
}
internal EventPipeSerializationFormat Format
{
get { return m_format; }
}
internal uint CircularBufferSizeInMB
{
get { return m_circularBufferSizeInMB; }
}
internal EventPipeProviderConfiguration[] Providers
{
get { return m_providers.ToArray(); }
}
internal void EnableProvider(string providerName, ulong keywords, uint loggingLevel)
{
EnableProviderWithFilter(providerName, keywords, loggingLevel, null);
}
internal void EnableProviderWithFilter(string providerName, ulong keywords, uint loggingLevel, string? filterData)
{
m_providers.Add(new EventPipeProviderConfiguration(
providerName,
keywords,
loggingLevel,
filterData));
}
private void EnableProviderConfiguration(EventPipeProviderConfiguration providerConfig)
{
m_providers.Add(providerConfig);
}
internal void EnableProviderRange(EventPipeProviderConfiguration[] providerConfigs)
{
foreach (EventPipeProviderConfiguration config in providerConfigs)
{
EnableProviderConfiguration(config);
}
}
internal void SetProfilerSamplingRate(TimeSpan minTimeBetweenSamples)
{
if (minTimeBetweenSamples.Ticks <= 0)
{
throw new ArgumentOutOfRangeException(nameof(minTimeBetweenSamples));
}
m_minTimeBetweenSamples = minTimeBetweenSamples;
}
}
internal static class EventPipe
{
private static ulong s_sessionID = 0;
internal static void Enable(EventPipeConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
if (configuration.Providers == null)
{
throw new ArgumentNullException(nameof(configuration.Providers));
}
EventPipeProviderConfiguration[] providers = configuration.Providers;
s_sessionID = EventPipeInternal.Enable(
configuration.OutputFile,
configuration.Format,
configuration.CircularBufferSizeInMB,
providers);
}
internal static void Disable()
{
EventPipeInternal.Disable(s_sessionID);
}
}
internal static class EventPipeInternal
{
private unsafe struct EventPipeProviderConfigurationNative
{
private char* m_pProviderName;
private ulong m_keywords;
private uint m_loggingLevel;
private char* m_pFilterData;
internal static void MarshalToNative(EventPipeProviderConfiguration managed, ref EventPipeProviderConfigurationNative native)
{
native.m_pProviderName = (char*)Marshal.StringToCoTaskMemUni(managed.ProviderName);
native.m_keywords = managed.Keywords;
native.m_loggingLevel = managed.LoggingLevel;
native.m_pFilterData = (char*)Marshal.StringToCoTaskMemUni(managed.FilterData);
}
internal void Release()
{
if (m_pProviderName != null)
{
Marshal.FreeCoTaskMem((IntPtr)m_pProviderName);
}
if (m_pFilterData != null)
{
Marshal.FreeCoTaskMem((IntPtr)m_pFilterData);
}
}
}
//
// These PInvokes are used by the configuration APIs to interact with EventPipe.
//
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static unsafe extern ulong Enable(
char* outputFile,
EventPipeSerializationFormat format,
uint circularBufferSizeInMB,
EventPipeProviderConfigurationNative* providers,
uint numProviders);
internal static unsafe ulong Enable(
string? outputFile,
EventPipeSerializationFormat format,
uint circularBufferSizeInMB,
EventPipeProviderConfiguration[] providers)
{
Span<EventPipeProviderConfigurationNative> providersNative = new Span<EventPipeProviderConfigurationNative>((void*)Marshal.AllocCoTaskMem(sizeof(EventPipeProviderConfigurationNative) * providers.Length), providers.Length);
providersNative.Clear();
try
{
for (int i = 0; i < providers.Length; i++)
{
EventPipeProviderConfigurationNative.MarshalToNative(providers[i], ref providersNative[i]);
}
fixed (char* outputFilePath = outputFile)
fixed (EventPipeProviderConfigurationNative* providersNativePointer = providersNative)
{
return Enable(outputFilePath, format, circularBufferSizeInMB, providersNativePointer, (uint)providersNative.Length);
}
}
finally
{
for (int i = 0; i < providers.Length; i++)
{
providersNative[i].Release();
}
fixed (EventPipeProviderConfigurationNative* providersNativePointer = providersNative)
{
Marshal.FreeCoTaskMem((IntPtr)providersNativePointer);
}
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void Disable(ulong sessionID);
//
// These PInvokes are used by EventSource to interact with the EventPipe.
//
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern IntPtr CreateProvider(string providerName, Interop.Advapi32.EtwEnableCallback callbackFunc);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern unsafe IntPtr DefineEvent(IntPtr provHandle, uint eventID, long keywords, uint eventVersion, uint level, void* pMetadata, uint metadataLength);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern IntPtr GetProvider(string providerName);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void DeleteProvider(IntPtr provHandle);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern int EventActivityIdControl(uint controlCode, ref Guid activityId);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern unsafe void WriteEvent(IntPtr eventHandle, uint eventID, void* pData, uint length, Guid* activityId, Guid* relatedActivityId);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern unsafe void WriteEventData(IntPtr eventHandle, uint eventID, EventProvider.EventData* pEventData, uint dataCount, Guid* activityId, Guid* relatedActivityId);
//
// These PInvokes are used as part of the EventPipeEventDispatcher.
//
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern unsafe bool GetSessionInfo(ulong sessionID, EventPipeSessionInfo* pSessionInfo);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern unsafe bool GetNextEvent(ulong sessionID, EventPipeEventInstanceData* pInstance);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern unsafe IntPtr GetWaitHandle(ulong sessionID);
}
}
#endif // FEATURE_PERFTRACING
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// SupplierEdit (editable root object).<br/>
/// This is a generated <see cref="SupplierEdit"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="Products"/> of type <see cref="SupplierProductColl"/> (1:M relation to <see cref="SupplierProductItem"/>)
/// </remarks>
[Serializable]
public partial class SupplierEdit : BusinessBase<SupplierEdit>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SupplierId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> SupplierIdProperty = RegisterProperty<int>(p => p.SupplierId, "Supplier Id");
/// <summary>
/// For simplicity sake, use the VAT number (no auto increment here).
/// </summary>
/// <value>The Supplier Id.</value>
public int SupplierId
{
get { return GetProperty(SupplierIdProperty); }
set { SetProperty(SupplierIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name, "Name");
/// <summary>
/// Gets or sets the Name.
/// </summary>
/// <value>The Name.</value>
public string Name
{
get { return GetProperty(NameProperty); }
set { SetProperty(NameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="AddressLine1"/> property.
/// </summary>
public static readonly PropertyInfo<string> AddressLine1Property = RegisterProperty<string>(p => p.AddressLine1, "Address Line1");
/// <summary>
/// Gets or sets the Address Line1.
/// </summary>
/// <value>The Address Line1.</value>
public string AddressLine1
{
get { return GetProperty(AddressLine1Property); }
set { SetProperty(AddressLine1Property, value); }
}
/// <summary>
/// Maintains metadata about <see cref="AddressLine2"/> property.
/// </summary>
public static readonly PropertyInfo<string> AddressLine2Property = RegisterProperty<string>(p => p.AddressLine2, "Address Line2");
/// <summary>
/// Gets or sets the Address Line2.
/// </summary>
/// <value>The Address Line2.</value>
public string AddressLine2
{
get { return GetProperty(AddressLine2Property); }
set { SetProperty(AddressLine2Property, value); }
}
/// <summary>
/// Maintains metadata about <see cref="ZipCode"/> property.
/// </summary>
public static readonly PropertyInfo<string> ZipCodeProperty = RegisterProperty<string>(p => p.ZipCode, "Zip Code");
/// <summary>
/// Gets or sets the Zip Code.
/// </summary>
/// <value>The Zip Code.</value>
public string ZipCode
{
get { return GetProperty(ZipCodeProperty); }
set { SetProperty(ZipCodeProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="State"/> property.
/// </summary>
public static readonly PropertyInfo<string> StateProperty = RegisterProperty<string>(p => p.State, "State");
/// <summary>
/// Gets or sets the State.
/// </summary>
/// <value>The State.</value>
public string State
{
get { return GetProperty(StateProperty); }
set { SetProperty(StateProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Country"/> property.
/// </summary>
public static readonly PropertyInfo<byte?> CountryProperty = RegisterProperty<byte?>(p => p.Country, "Country");
/// <summary>
/// Gets or sets the Country.
/// </summary>
/// <value>The Country.</value>
public byte? Country
{
get { return GetProperty(CountryProperty); }
set { SetProperty(CountryProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="Products"/> property.
/// </summary>
public static readonly PropertyInfo<SupplierProductColl> ProductsProperty = RegisterProperty<SupplierProductColl>(p => p.Products, "Products", RelationshipTypes.Child | RelationshipTypes.LazyLoad);
/// <summary>
/// Gets the Products ("lazy load" child property).
/// </summary>
/// <value>The Products.</value>
public SupplierProductColl Products
{
get
{
#if ASYNC
if (!FieldManager.FieldExists(ProductsProperty))
{
LoadProperty(ProductsProperty, null);
if (this.IsNew)
{
DataPortal.BeginCreate<SupplierProductColl>((o, e) =>
{
if (e.Error != null)
throw e.Error;
else
{
// set the property so OnPropertyChanged is raised
Products = e.Object;
}
});
return null;
}
else
{
DataPortal.BeginFetch<SupplierProductColl>(ReadProperty(SupplierIdProperty), (o, e) =>
{
if (e.Error != null)
throw e.Error;
else
{
// set the property so OnPropertyChanged is raised
Products = e.Object;
}
});
return null;
}
}
else
{
return GetProperty(ProductsProperty);
}
#else
if (!FieldManager.FieldExists(ProductsProperty))
if (this.IsNew)
Products = DataPortal.Create<SupplierProductColl>();
else
Products = DataPortal.Fetch<SupplierProductColl>(ReadProperty(SupplierIdProperty));
return GetProperty(ProductsProperty);
#endif
}
private set
{
LoadProperty(ProductsProperty, value);
OnPropertyChanged(ProductsProperty);
}
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="SupplierEdit"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="SupplierEdit"/> object.</returns>
public static SupplierEdit NewSupplierEdit()
{
return DataPortal.Create<SupplierEdit>();
}
/// <summary>
/// Factory method. Loads a <see cref="SupplierEdit"/> object, based on given parameters.
/// </summary>
/// <param name="supplierId">The SupplierId parameter of the SupplierEdit to fetch.</param>
/// <returns>A reference to the fetched <see cref="SupplierEdit"/> object.</returns>
public static SupplierEdit GetSupplierEdit(int supplierId)
{
return DataPortal.Fetch<SupplierEdit>(supplierId);
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="SupplierEdit"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewSupplierEdit(EventHandler<DataPortalResult<SupplierEdit>> callback)
{
DataPortal.BeginCreate<SupplierEdit>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="SupplierEdit"/> object, based on given parameters.
/// </summary>
/// <param name="supplierId">The SupplierId parameter of the SupplierEdit to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetSupplierEdit(int supplierId, EventHandler<DataPortalResult<SupplierEdit>> callback)
{
DataPortal.BeginFetch<SupplierEdit>(supplierId, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="SupplierEdit"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public SupplierEdit()
{
// Use factory methods and do not use direct creation.
Saved += OnSupplierEditSaved;
SupplierEditSaved += SupplierEditSavedHandler;
}
#endregion
#region Cache Invalidation
// TODO: edit "SupplierEdit.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: SupplierEditSaved += SupplierEditSavedHandler;
private void SupplierEditSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
// this runs on the client
SupplierList.InvalidateCache();
}
/// <summary>
/// Called by the server-side DataPortal after calling the requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
protected override void DataPortal_OnDataPortalInvokeComplete(Csla.DataPortalEventArgs e)
{
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Server &&
e.Operation == DataPortalOperations.Update)
{
// this runs on the server
SupplierList.InvalidateCache();
}
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="SupplierEdit"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(AddressLine1Property, null);
LoadProperty(AddressLine2Property, null);
LoadProperty(ZipCodeProperty, null);
LoadProperty(StateProperty, null);
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="SupplierEdit"/> object from the database, based on given criteria.
/// </summary>
/// <param name="supplierId">The Supplier Id.</param>
protected void DataPortal_Fetch(int supplierId)
{
var args = new DataPortalHookArgs(supplierId);
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<ISupplierEditDal>();
var data = dal.Fetch(supplierId);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="SupplierEdit"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(SupplierIdProperty, dr.GetInt32("SupplierId"));
LoadProperty(NameProperty, dr.GetString("Name"));
LoadProperty(AddressLine1Property, dr.IsDBNull("AddressLine1") ? null : dr.GetString("AddressLine1"));
LoadProperty(AddressLine2Property, dr.IsDBNull("AddressLine2") ? null : dr.GetString("AddressLine2"));
LoadProperty(ZipCodeProperty, dr.IsDBNull("ZipCode") ? null : dr.GetString("ZipCode"));
LoadProperty(StateProperty, dr.IsDBNull("State") ? null : dr.GetString("State"));
LoadProperty(CountryProperty, (byte?)dr.GetValue("Country"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="SupplierEdit"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<ISupplierEditDal>();
using (BypassPropertyChecks)
{
dal.Insert(
SupplierId,
Name,
AddressLine1,
AddressLine2,
ZipCode,
State,
Country
);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="SupplierEdit"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<ISupplierEditDal>();
using (BypassPropertyChecks)
{
dal.Update(
SupplierId,
Name,
AddressLine1,
AddressLine2,
ZipCode,
State,
Country
);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
#endregion
#region Saved Event
// TODO: edit "SupplierEdit.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: Saved += OnSupplierEditSaved;
private void OnSupplierEditSaved(object sender, Csla.Core.SavedEventArgs e)
{
if (SupplierEditSaved != null)
SupplierEditSaved(sender, e);
}
/// <summary> Use this event to signal a <see cref="SupplierEdit"/> object was saved.</summary>
public static event EventHandler<Csla.Core.SavedEventArgs> SupplierEditSaved;
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Configuration;
using System.Runtime.Serialization;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.ServiceModel;
using ServiceStack.Text;
namespace ServiceStack.ServiceInterface.Auth
{
/// <summary>
/// Inject logic into existing services by introspecting the request and injecting your own
/// validation logic. Exceptions thrown will have the same behaviour as if the service threw it.
///
/// If a non-null object is returned the request will short-circuit and return that response.
/// </summary>
/// <param name="service">The instance of the service</param>
/// <param name="httpMethod">GET,POST,PUT,DELETE</param>
/// <param name="requestDto"></param>
/// <returns>Response DTO; non-null will short-circuit execution and return that response</returns>
public delegate object ValidateFn(IServiceBase service, string httpMethod, object requestDto);
[DataContract]
public class Auth : IReturn<AuthResponse>
{
[DataMember(Order=1)] public string provider { get; set; }
[DataMember(Order=2)] public string State { get; set; }
[DataMember(Order=3)] public string oauth_token { get; set; }
[DataMember(Order=4)] public string oauth_verifier { get; set; }
[DataMember(Order=5)] public string UserName { get; set; }
[DataMember(Order=6)] public string Password { get; set; }
[DataMember(Order=7)] public bool? RememberMe { get; set; }
[DataMember(Order=8)] public string Continue { get; set; }
// Thise are used for digest auth
[DataMember(Order=9)] public string nonce { get; set; }
[DataMember(Order=10)] public string uri { get; set; }
[DataMember(Order=11)] public string response { get; set; }
[DataMember(Order=12)] public string qop { get; set; }
[DataMember(Order=13)] public string nc { get; set; }
[DataMember(Order=14)] public string cnonce { get; set; }
}
[DataContract]
public class AuthResponse
{
public AuthResponse()
{
this.ResponseStatus = new ResponseStatus();
}
[DataMember(Order=1)] public string SessionId { get; set; }
[DataMember(Order=2)] public string UserName { get; set; }
[DataMember(Order=3)] public string ReferrerUrl { get; set; }
[DataMember(Order=4)] public ResponseStatus ResponseStatus { get; set; }
}
[DefaultRequest(typeof(Auth))]
public class AuthService : Service
{
public const string BasicProvider = "basic";
public const string CredentialsProvider = "credentials";
public const string LogoutAction = "logout";
public const string DigestProvider = "digest";
public static Func<IAuthSession> CurrentSessionFactory { get; set; }
public static ValidateFn ValidateFn { get; set; }
public static string DefaultOAuthProvider { get; private set; }
public static string DefaultOAuthRealm { get; private set; }
public static string HtmlRedirect { get; internal set; }
public static IAuthProvider[] AuthProviders { get; private set; }
static AuthService()
{
CurrentSessionFactory = () => new AuthUserSession();
}
public static IAuthProvider GetAuthProvider(string provider)
{
if (AuthProviders == null || AuthProviders.Length == 0) return null;
if (provider == LogoutAction) return AuthProviders[0];
foreach (var authConfig in AuthProviders)
{
if (string.Compare(authConfig.Provider, provider,
StringComparison.InvariantCultureIgnoreCase) == 0)
return authConfig;
}
return null;
}
public static void Init(Func<IAuthSession> sessionFactory, params IAuthProvider[] authProviders)
{
if (authProviders.Length == 0)
throw new ArgumentNullException("authProviders");
DefaultOAuthProvider = authProviders[0].Provider;
DefaultOAuthRealm = authProviders[0].AuthRealm;
AuthProviders = authProviders;
if (sessionFactory != null)
CurrentSessionFactory = sessionFactory;
}
private void AssertAuthProviders()
{
if (AuthProviders == null || AuthProviders.Length == 0)
throw new ConfigurationException("No OAuth providers have been registered in your AppHost.");
}
public void Options(Auth request) {}
public object Get(Auth request)
{
return Post(request);
}
public object Post(Auth request)
{
AssertAuthProviders();
if (ValidateFn != null)
{
var validationResponse = ValidateFn(this, HttpMethods.Get, request);
if (validationResponse != null) return validationResponse;
}
if (request.RememberMe.HasValue)
{
var opt = request.RememberMe.GetValueOrDefault(false)
? SessionOptions.Permanent
: SessionOptions.Temporary;
base.RequestContext.Get<IHttpResponse>()
.AddSessionOptions(base.RequestContext.Get<IHttpRequest>(), opt);
}
var provider = request.provider ?? AuthProviders[0].Provider;
var oAuthConfig = GetAuthProvider(provider);
if (oAuthConfig == null)
throw HttpError.NotFound("No configuration was added for OAuth provider '{0}'".Fmt(provider));
if (request.provider == LogoutAction)
return oAuthConfig.Logout(this, request);
var session = this.GetSession();
var isHtml = base.RequestContext.ResponseContentType.MatchesContentType(ContentType.Html);
try
{
var response = Authenticate(request, provider, session, oAuthConfig);
// The above Authenticate call may end an existing session and create a new one so we need
// to refresh the current session reference.
session = this.GetSession();
var referrerUrl = request.Continue
?? session.ReferrerUrl
?? this.RequestContext.GetHeader("Referer")
?? oAuthConfig.CallbackUrl;
var alreadyAuthenticated = response == null;
response = response ?? new AuthResponse {
UserName = session.UserAuthName,
SessionId = session.Id,
ReferrerUrl = referrerUrl,
};
if (isHtml)
{
if (alreadyAuthenticated)
return this.Redirect(referrerUrl.AddHashParam("s", "0"));
if (!(response is IHttpResult) && !String.IsNullOrEmpty(referrerUrl))
{
return new HttpResult(response) {
Location = referrerUrl
};
}
}
return response;
}
catch (HttpError ex)
{
var errorReferrerUrl = this.RequestContext.GetHeader("Referer");
if (isHtml && errorReferrerUrl != null)
{
errorReferrerUrl = errorReferrerUrl.SetQueryParam("error", ex.Message);
return HttpResult.Redirect(errorReferrerUrl);
}
throw;
}
}
/// <summary>
/// Public API entry point to authenticate via code
/// </summary>
/// <param name="request"></param>
/// <returns>null; if already autenticated otherwise a populated instance of AuthResponse</returns>
public AuthResponse Authenticate(Auth request)
{
//Remove HTML Content-Type to avoid auth providers issuing browser re-directs
((HttpRequestContext)this.RequestContext).ResponseContentType = ContentType.PlainText;
var provider = request.provider ?? AuthProviders[0].Provider;
var oAuthConfig = GetAuthProvider(provider);
if (oAuthConfig == null)
throw HttpError.NotFound("No configuration was added for OAuth provider '{0}'".Fmt(provider));
if (request.provider == LogoutAction)
return oAuthConfig.Logout(this, request) as AuthResponse;
var result = Authenticate(request, provider, this.GetSession(), oAuthConfig);
var httpError = result as HttpError;
if (httpError != null)
throw httpError;
return result as AuthResponse;
}
/// <summary>
/// The specified <paramref name="session"/> may change as a side-effect of this method. If
/// subsequent code relies on current <see cref="IAuthSession"/> data be sure to reload
/// the session istance via <see cref="ServiceExtensions.GetSession(ServiceStack.ServiceInterface.IServiceBase,bool)"/>.
/// </summary>
private object Authenticate(Auth request, string provider, IAuthSession session, IAuthProvider oAuthConfig)
{
object response = null;
if (!oAuthConfig.IsAuthorized(session, session.GetOAuthTokens(provider), request))
{
response = oAuthConfig.Authenticate(this, session, request);
}
return response;
}
public object Delete(Auth request)
{
if (ValidateFn != null)
{
var response = ValidateFn(this, HttpMethods.Delete, request);
if (response != null) return response;
}
this.RemoveSession();
return new AuthResponse();
}
}
}
| |
// <copyright file="DefaultMetricContextRegistry.cs" company="App Metrics Contributors">
// Copyright (c) App Metrics Contributors. All rights reserved.
// </copyright>
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using App.Metrics.Apdex;
using App.Metrics.BucketHistogram;
using App.Metrics.BucketTimer;
using App.Metrics.Counter;
using App.Metrics.Gauge;
using App.Metrics.Histogram;
using App.Metrics.Logging;
using App.Metrics.Meter;
using App.Metrics.Registry;
using App.Metrics.Timer;
namespace App.Metrics.Internal
{
public sealed class DefaultMetricContextRegistry : IMetricContextRegistry
{
private static readonly ILog Logger = LogProvider.For<DefaultMetricsRegistry>();
private readonly MetricMetaCatalog<IApdex, ApdexValueSource, ApdexValue> _apdexScores =
new MetricMetaCatalog<IApdex, ApdexValueSource, ApdexValue>();
private readonly MetricMetaCatalog<ICounter, CounterValueSource, CounterValue> _counters =
new MetricMetaCatalog<ICounter, CounterValueSource, CounterValue>();
private readonly MetricMetaCatalog<IGauge, GaugeValueSource, double> _gauges =
new MetricMetaCatalog<IGauge, GaugeValueSource, double>();
private readonly GlobalMetricTags _globalTags;
private readonly ContextualMetricTagProviders _contextualTags;
private readonly MetricMetaCatalog<IHistogram, HistogramValueSource, HistogramValue> _histograms =
new MetricMetaCatalog<IHistogram, HistogramValueSource, HistogramValue>();
private readonly MetricMetaCatalog<IBucketHistogram, BucketHistogramValueSource, BucketHistogramValue> _bucketHistograms =
new MetricMetaCatalog<IBucketHistogram, BucketHistogramValueSource, BucketHistogramValue>();
private readonly MetricMetaCatalog<IMeter, MeterValueSource, MeterValue> _meters =
new MetricMetaCatalog<IMeter, MeterValueSource, MeterValue>();
private readonly MetricMetaCatalog<ITimer, TimerValueSource, TimerValue> _timers =
new MetricMetaCatalog<ITimer, TimerValueSource, TimerValue>();
private readonly MetricMetaCatalog<ITimer, BucketTimerValueSource, BucketTimerValue> _bucketTimers =
new MetricMetaCatalog<ITimer, BucketTimerValueSource, BucketTimerValue>();
public DefaultMetricContextRegistry(string context)
: this(context, new GlobalMetricTags(), new ContextualMetricTagProviders())
{
}
public DefaultMetricContextRegistry(string context, GlobalMetricTags globalTags, ContextualMetricTagProviders contextualTags)
{
_globalTags = globalTags ?? throw new ArgumentNullException(nameof(globalTags));
_contextualTags = contextualTags ?? throw new ArgumentNullException(nameof(contextualTags));
if (context.IsMissing())
{
throw new ArgumentException("Registry Context cannot be null or empty", nameof(context));
}
Context = context;
DataProvider = new DefaultMetricRegistryManager(
() => _gauges.All,
() => _counters.All,
() => _meters.All,
() => _histograms.All,
() => _bucketHistograms.All,
() => _timers.All,
() => _bucketTimers.All,
() => _apdexScores.All);
}
public string Context { get; }
public IMetricRegistryManager DataProvider { get; }
public IApdex Apdex<T>(ApdexOptions options, Func<T> builder)
where T : IApdexMetric
{
var allTags = AllTags(options.Tags);
var metricName = allTags.AsMetricName(options.Name);
return _apdexScores.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Apdex {Name} - {@Options} {MesurementUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), allTags.ToDictionary());
var apdex = builder();
var valueSource = new ApdexValueSource(
metricName,
apdex,
allTags,
options.ResetOnReporting);
return Tuple.Create((IApdex)apdex, valueSource);
});
}
/// <inheritdoc />
public IApdex Apdex<T>(ApdexOptions options, MetricTags tags, Func<T> builder)
where T : IApdexMetric
{
var allTags = AllTags(MetricTags.Concat(options.Tags, tags));
var metricName = allTags.AsMetricName(options.Name);
return _apdexScores.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Apdex {Name} - {@Options} {MesurementUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), allTags.ToDictionary());
var apdex = builder();
var valueSource = new ApdexValueSource(
metricName,
apdex,
allTags,
options.ResetOnReporting);
return Tuple.Create((IApdex)apdex, valueSource);
});
}
public void ClearAllMetrics()
{
Logger.Trace("Clearing all metrics");
_gauges.Clear();
_counters.Clear();
_meters.Clear();
_histograms.Clear();
_timers.Clear();
Logger.Trace("Cleared all metrics");
}
public ICounter Counter<T>(CounterOptions options, Func<T> builder)
where T : ICounterMetric
{
var allTags = AllTags(options.Tags);
var metricName = allTags.AsMetricName(options.Name);
return _counters.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Counter {Name} - {@Options} {MesurementUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), allTags.ToDictionary());
var counter = builder();
var valueSource = new CounterValueSource(
metricName,
counter,
options.MeasurementUnit,
allTags,
options.ResetOnReporting,
options.ReportItemPercentages,
options.ReportSetItems);
return Tuple.Create((ICounter)counter, valueSource);
});
}
/// <inheritdoc />
public ICounter Counter<T>(CounterOptions options, MetricTags tags, Func<T> builder)
where T : ICounterMetric
{
var allTags = AllTags(MetricTags.Concat(options.Tags, tags));
var metricName = allTags.AsMetricName(options.Name);
return _counters.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Counter {Name} - {@Options} {MesurementUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), allTags.ToDictionary());
var counter = builder();
var valueSource = new CounterValueSource(
metricName,
counter,
options.MeasurementUnit,
allTags,
options.ResetOnReporting,
options.ReportItemPercentages,
options.ReportSetItems);
return Tuple.Create((ICounter)counter, valueSource);
});
}
public IGauge Gauge<T>(GaugeOptions options, Func<T> builder)
where T : IGaugeMetric
{
var allTags = AllTags(options.Tags);
var metricName = allTags.AsMetricName(options.Name);
return _gauges.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Gauge {Name} - {@Options} {MesurementUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), allTags.ToDictionary());
var gauge = builder();
var valueSource = new GaugeValueSource(
metricName,
gauge,
options.MeasurementUnit,
allTags,
options.ResetOnReporting);
return Tuple.Create((IGauge)gauge, valueSource);
});
}
/// <inheritdoc />
public IGauge Gauge<T>(GaugeOptions options, MetricTags tags, Func<T> builder)
where T : IGaugeMetric
{
var allTags = AllTags(MetricTags.Concat(options.Tags, tags));
var metricName = allTags.AsMetricName(options.Name);
return _gauges.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Gauge {Name} - {@Options} {MesurementUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), allTags);
var gauge = builder();
var valueSource = new GaugeValueSource(
metricName,
gauge,
options.MeasurementUnit,
allTags,
options.ResetOnReporting);
return Tuple.Create((IGauge)gauge, valueSource);
});
}
public IHistogram Histogram<T>(HistogramOptions options, Func<T> builder)
where T : IHistogramMetric
{
var allTags = AllTags(options.Tags);
var metricName = allTags.AsMetricName(options.Name);
return _histograms.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Histogram {Name} - {@Options} {MesurementUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), allTags.ToDictionary());
var histogram = builder();
var valueSource = new HistogramValueSource(
metricName,
histogram,
options.MeasurementUnit,
allTags,
options.ResetOnReporting);
return Tuple.Create((IHistogram)histogram, valueSource);
});
}
/// <inheritdoc />
public IHistogram Histogram<T>(HistogramOptions options, MetricTags tags, Func<T> builder)
where T : IHistogramMetric
{
var allTags = AllTags(MetricTags.Concat(options.Tags, tags));
var metricName = allTags.AsMetricName(options.Name);
return _histograms.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Histogram {Name} - {@Options} {MesurementUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), allTags.ToDictionary());
var histogram = builder();
var valueSource = new HistogramValueSource(
metricName,
histogram,
options.MeasurementUnit,
allTags,
options.ResetOnReporting);
return Tuple.Create((IHistogram)histogram, valueSource);
});
}
public IBucketHistogram BucketHistogram<T>(BucketHistogramOptions options, Func<T> builder)
where T : IBucketHistogramMetric
{
var allTags = AllTags(options.Tags);
var metricName = allTags.AsMetricName(options.Name);
return _bucketHistograms.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Bucket Histogram {Name} - {@Options} {MesurementUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), allTags.ToDictionary());
var histogram = builder();
var valueSource = new BucketHistogramValueSource(
metricName,
histogram,
options.MeasurementUnit,
allTags);
return Tuple.Create((IBucketHistogram)histogram, valueSource);
});
}
/// <inheritdoc />
public IBucketHistogram BucketHistogram<T>(BucketHistogramOptions options, MetricTags tags, Func<T> builder)
where T : IBucketHistogramMetric
{
var allTags = AllTags(MetricTags.Concat(options.Tags, tags));
var metricName = allTags.AsMetricName(options.Name);
return _bucketHistograms.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Bucket Histogram {Name} - {@Options} {MesurementUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), allTags.ToDictionary());
var histogram = builder();
var valueSource = new BucketHistogramValueSource(
metricName,
histogram,
options.MeasurementUnit,
allTags);
return Tuple.Create((IBucketHistogram)histogram, valueSource);
});
}
public IMeter Meter<T>(MeterOptions options, Func<T> builder)
where T : IMeterMetric
{
var allTags = AllTags(options.Tags);
var metricName = allTags.AsMetricName(options.Name);
return _meters.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Meter {Name} - {@Options} {MesurementUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), allTags.ToDictionary());
var meter = builder();
var valueSource = new MeterValueSource(
metricName,
meter,
options.MeasurementUnit,
options.RateUnit,
allTags,
options.ResetOnReporting,
options.ReportSetItems);
return Tuple.Create((IMeter)meter, valueSource);
});
}
/// <inheritdoc />
public IMeter Meter<T>(MeterOptions options, MetricTags tags, Func<T> builder)
where T : IMeterMetric
{
var allTags = AllTags(MetricTags.Concat(options.Tags, tags));
var metricName = allTags.AsMetricName(options.Name);
return _meters.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Meter {Name} - {@Options} {MesurementUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), allTags.ToDictionary());
var meter = builder();
var valueSource = new MeterValueSource(
metricName,
meter,
options.MeasurementUnit,
options.RateUnit,
allTags,
options.ResetOnReporting,
options.ReportSetItems);
return Tuple.Create((IMeter)meter, valueSource);
});
}
public ITimer Timer<T>(TimerOptions options, Func<T> builder)
where T : ITimerMetric
{
var allTags = AllTags(options.Tags);
var metricName = allTags.AsMetricName(options.Name);
return _timers.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Timer {Name} - {@Options} {MesurementUnit} {DurationUnit} {RateUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), options.DurationUnit, options.RateUnit, allTags.ToDictionary());
var timer = builder();
var valueSource = new TimerValueSource(
metricName,
timer,
options.MeasurementUnit,
options.RateUnit,
options.DurationUnit,
allTags,
options.ResetOnReporting);
return Tuple.Create((ITimer)timer, valueSource);
});
}
/// <inheritdoc />
public ITimer Timer<T>(TimerOptions options, MetricTags tags, Func<T> builder)
where T : ITimerMetric
{
var allTags = AllTags(MetricTags.Concat(options.Tags, tags));
var metricName = allTags.AsMetricName(options.Name);
return _timers.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Timer {Name} - {@Options} {MesurementUnit} {DurationUnit} {RateUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), options.DurationUnit, options.RateUnit, allTags.ToDictionary());
var timer = builder();
var valueSource = new TimerValueSource(
metricName,
timer,
options.MeasurementUnit,
options.RateUnit,
options.DurationUnit,
allTags,
options.ResetOnReporting);
return Tuple.Create((ITimer)timer, valueSource);
});
}
public ITimer BucketTimer<T>(BucketTimerOptions options, Func<T> builder)
where T : IBucketTimerMetric
{
var allTags = AllTags(options.Tags);
var metricName = allTags.AsMetricName(options.Name);
return _bucketTimers.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Timer {Name} - {@Options} {MesurementUnit} {DurationUnit} {RateUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), options.DurationUnit, options.RateUnit, allTags.ToDictionary());
var timer = builder();
var valueSource = new BucketTimerValueSource(
metricName,
timer,
options.MeasurementUnit,
options.RateUnit,
options.DurationUnit,
allTags);
return Tuple.Create((ITimer)timer, valueSource);
});
}
/// <inheritdoc />
public ITimer BucketTimer<T>(BucketTimerOptions options, MetricTags tags, Func<T> builder)
where T : IBucketTimerMetric
{
var allTags = AllTags(MetricTags.Concat(options.Tags, tags));
var metricName = allTags.AsMetricName(options.Name);
return _bucketTimers.GetOrAdd(
metricName,
() =>
{
Logger.Trace("Adding Timer {Name} - {@Options} {MesurementUnit} {DurationUnit} {RateUnit} {@Tags}", metricName, options, options.MeasurementUnit.ToString(), options.DurationUnit, options.RateUnit, allTags.ToDictionary());
var timer = builder();
var valueSource = new BucketTimerValueSource(
metricName,
timer,
options.MeasurementUnit,
options.RateUnit,
options.DurationUnit,
allTags);
return Tuple.Create((ITimer)timer, valueSource);
});
}
private MetricTags AllTags(MetricTags metricTags)
{
return MetricTags.Concat(
MetricTags.Concat(metricTags, _globalTags),
_contextualTags.ComputeTagValues());
}
private sealed class MetricMetaCatalog<TMetric, TValue, TMetricValue>
where TValue : MetricValueSourceBase<TMetricValue>
{
private readonly ConcurrentDictionary<string, MetricMeta> _metrics =
new ConcurrentDictionary<string, MetricMeta>();
public IEnumerable<TValue> All
{
get { return _metrics.Values.OrderBy(m => m.Name).Select(v => v.Value); }
}
public void Clear()
{
var values = _metrics.Values;
_metrics.Clear();
foreach (var value in values)
{
using (value.Metric as IDisposable)
{
}
}
}
public TMetric GetOrAdd(string name, Func<Tuple<TMetric, TValue>> metricProvider)
{
return _metrics.GetOrAdd(
name,
n =>
{
var result = metricProvider();
return new MetricMeta(result.Item1, result.Item2);
}).
Metric;
}
private sealed class MetricMeta
{
public MetricMeta(TMetric metric, TValue valueUnit)
{
Metric = metric;
Value = valueUnit;
}
public TMetric Metric { get; }
public string Name => Value.Name;
public TValue Value { get; }
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * 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 Google Inc. 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.
#endregion
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Grpc.Core;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// grpc_call from <grpc/grpc.h>
/// </summary>
internal class CallSafeHandle : SafeHandleZeroIsInvalid
{
public static readonly CallSafeHandle NullInstance = new CallSafeHandle();
const uint GRPC_WRITE_BUFFER_HINT = 1;
CompletionRegistry completionRegistry;
[DllImport("grpc_csharp_ext.dll")]
static extern GRPCCallError grpcsharp_call_cancel(CallSafeHandle call);
[DllImport("grpc_csharp_ext.dll")]
static extern GRPCCallError grpcsharp_call_cancel_with_status(CallSafeHandle call, StatusCode status, string description);
[DllImport("grpc_csharp_ext.dll")]
static extern GRPCCallError grpcsharp_call_start_unary(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
[DllImport("grpc_csharp_ext.dll")]
static extern GRPCCallError grpcsharp_call_start_client_streaming(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport("grpc_csharp_ext.dll")]
static extern GRPCCallError grpcsharp_call_start_server_streaming(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len,
MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
[DllImport("grpc_csharp_ext.dll")]
static extern GRPCCallError grpcsharp_call_start_duplex_streaming(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport("grpc_csharp_ext.dll")]
static extern GRPCCallError grpcsharp_call_send_message(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, WriteFlags writeFlags, bool sendEmptyInitialMetadata);
[DllImport("grpc_csharp_ext.dll")]
static extern GRPCCallError grpcsharp_call_send_close_from_client(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
static extern GRPCCallError grpcsharp_call_send_status_from_server(CallSafeHandle call,
BatchContextSafeHandle ctx, StatusCode statusCode, string statusMessage, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata);
[DllImport("grpc_csharp_ext.dll")]
static extern GRPCCallError grpcsharp_call_recv_message(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
static extern GRPCCallError grpcsharp_call_start_serverside(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
static extern GRPCCallError grpcsharp_call_send_initial_metadata(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport("grpc_csharp_ext.dll")]
static extern CStringSafeHandle grpcsharp_call_get_peer(CallSafeHandle call);
[DllImport("grpc_csharp_ext.dll")]
static extern void grpcsharp_call_destroy(IntPtr call);
private CallSafeHandle()
{
}
public void SetCompletionRegistry(CompletionRegistry completionRegistry)
{
this.completionRegistry = completionRegistry;
}
public void StartUnary(BatchCompletionDelegate callback, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags)
{
var ctx = BatchContextSafeHandle.Create();
completionRegistry.RegisterBatchCompletion(ctx, callback);
grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray, writeFlags)
.CheckOk();
}
public void StartUnary(BatchContextSafeHandle ctx, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags)
{
grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray, writeFlags)
.CheckOk();
}
public void StartClientStreaming(BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray)
{
var ctx = BatchContextSafeHandle.Create();
completionRegistry.RegisterBatchCompletion(ctx, callback);
grpcsharp_call_start_client_streaming(this, ctx, metadataArray).CheckOk();
}
public void StartServerStreaming(BatchCompletionDelegate callback, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags)
{
var ctx = BatchContextSafeHandle.Create();
completionRegistry.RegisterBatchCompletion(ctx, callback);
grpcsharp_call_start_server_streaming(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray, writeFlags).CheckOk();
}
public void StartDuplexStreaming(BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray)
{
var ctx = BatchContextSafeHandle.Create();
completionRegistry.RegisterBatchCompletion(ctx, callback);
grpcsharp_call_start_duplex_streaming(this, ctx, metadataArray).CheckOk();
}
public void StartSendMessage(BatchCompletionDelegate callback, byte[] payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata)
{
var ctx = BatchContextSafeHandle.Create();
completionRegistry.RegisterBatchCompletion(ctx, callback);
grpcsharp_call_send_message(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, sendEmptyInitialMetadata).CheckOk();
}
public void StartSendCloseFromClient(BatchCompletionDelegate callback)
{
var ctx = BatchContextSafeHandle.Create();
completionRegistry.RegisterBatchCompletion(ctx, callback);
grpcsharp_call_send_close_from_client(this, ctx).CheckOk();
}
public void StartSendStatusFromServer(BatchCompletionDelegate callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata)
{
var ctx = BatchContextSafeHandle.Create();
completionRegistry.RegisterBatchCompletion(ctx, callback);
grpcsharp_call_send_status_from_server(this, ctx, status.StatusCode, status.Detail, metadataArray, sendEmptyInitialMetadata).CheckOk();
}
public void StartReceiveMessage(BatchCompletionDelegate callback)
{
var ctx = BatchContextSafeHandle.Create();
completionRegistry.RegisterBatchCompletion(ctx, callback);
grpcsharp_call_recv_message(this, ctx).CheckOk();
}
public void StartServerSide(BatchCompletionDelegate callback)
{
var ctx = BatchContextSafeHandle.Create();
completionRegistry.RegisterBatchCompletion(ctx, callback);
grpcsharp_call_start_serverside(this, ctx).CheckOk();
}
public void StartSendInitialMetadata(BatchCompletionDelegate callback, MetadataArraySafeHandle metadataArray)
{
var ctx = BatchContextSafeHandle.Create();
completionRegistry.RegisterBatchCompletion(ctx, callback);
grpcsharp_call_send_initial_metadata(this, ctx, metadataArray).CheckOk();
}
public void Cancel()
{
grpcsharp_call_cancel(this).CheckOk();
}
public void CancelWithStatus(Status status)
{
grpcsharp_call_cancel_with_status(this, status.StatusCode, status.Detail).CheckOk();
}
public string GetPeer()
{
using (var cstring = grpcsharp_call_get_peer(this))
{
return cstring.GetValue();
}
}
protected override bool ReleaseHandle()
{
grpcsharp_call_destroy(handle);
return true;
}
private static uint GetFlags(bool buffered)
{
return buffered ? 0 : GRPC_WRITE_BUFFER_HINT;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;
using Palmmedia.ReportGenerator.Core.Logging;
using Palmmedia.ReportGenerator.Core.Parser.Analysis;
using Palmmedia.ReportGenerator.Core.Parser.Filtering;
using Palmmedia.ReportGenerator.Core.Properties;
namespace Palmmedia.ReportGenerator.Core.Parser
{
/// <summary>
/// Parser for XML reports generated by dotCover.
/// </summary>
internal class DotCoverParser : ParserBase
{
/// <summary>
/// The Logger.
/// </summary>
private static readonly ILogger Logger = LoggerFactory.GetLogger(typeof(DotCoverParser));
/// <summary>
/// Regex to analyze if a method name belongs to a lamda expression.
/// </summary>
private static readonly Regex LambdaMethodNameRegex = new Regex(@"<.+>.+__.+\(.*\)", RegexOptions.Compiled);
/// <summary>
/// Regex to analyze if a method name is generated by compiler.
/// </summary>
private static readonly Regex CompilerGeneratedMethodNameRegex = new Regex(@"<(?<CompilerGeneratedName>.+)>.+__.+MoveNext\(\):.+$", RegexOptions.Compiled);
/// <summary>
/// Initializes a new instance of the <see cref="DotCoverParser" /> class.
/// </summary>
/// <param name="assemblyFilter">The assembly filter.</param>
/// <param name="classFilter">The class filter.</param>
/// <param name="fileFilter">The file filter.</param>
internal DotCoverParser(IFilter assemblyFilter, IFilter classFilter, IFilter fileFilter)
: base(assemblyFilter, classFilter, fileFilter)
{
}
/// <summary>
/// Parses the given XML report.
/// </summary>
/// <param name="report">The XML report.</param>
/// <returns>The parser result.</returns>
public ParserResult Parse(XContainer report)
{
if (report == null)
{
throw new ArgumentNullException(nameof(report));
}
var assemblies = new List<Assembly>();
var modules = report.Descendants("Assembly")
.ToArray();
var files = report.Descendants("File").ToArray();
var assemblyNames = modules
.Select(m => m.Attribute("Name").Value)
.Distinct()
.Where(a => this.AssemblyFilter.IsElementIncludedInReport(a))
.OrderBy(a => a)
.ToArray();
foreach (var assemblyName in assemblyNames)
{
assemblies.Add(this.ProcessAssembly(modules, files, assemblyName));
}
var result = new ParserResult(assemblies.OrderBy(a => a.Name).ToList(), false, this.ToString());
return result;
}
/// <summary>
/// Processes the given assembly.
/// </summary>
/// <param name="modules">The modules.</param>
/// <param name="files">The files.</param>
/// <param name="assemblyName">Name of the assembly.</param>
/// <returns>The <see cref="Assembly"/>.</returns>
private Assembly ProcessAssembly(XElement[] modules, XElement[] files, string assemblyName)
{
Logger.DebugFormat(Resources.CurrentAssembly, assemblyName);
var assemblyElement = modules
.Where(m => m.Attribute("Name").Value.Equals(assemblyName));
var classNames = assemblyElement
.Elements("Namespace")
.Elements("Type")
.Concat(assemblyElement.Elements("Type"))
.Where(c => !Regex.IsMatch(c.Attribute("Name").Value, "<.*>.+__", RegexOptions.Compiled))
.Select(c => c.Parent.Attribute("Name").Value + "." + c.Attribute("Name").Value)
.Distinct()
.Where(c => this.ClassFilter.IsElementIncludedInReport(c))
.OrderBy(name => name)
.ToArray();
var assembly = new Assembly(assemblyName);
Parallel.ForEach(classNames, className => this.ProcessClass(modules, files, assembly, className));
return assembly;
}
/// <summary>
/// Processes the given class.
/// </summary>
/// <param name="modules">The modules.</param>
/// <param name="files">The files.</param>
/// <param name="assembly">The assembly.</param>
/// <param name="className">Name of the class.</param>
private void ProcessClass(XElement[] modules, XElement[] files, Assembly assembly, string className)
{
var assemblyElement = modules
.Where(m => m.Attribute("Name").Value.Equals(assembly.Name));
var fileIdsOfClass = assemblyElement
.Elements("Namespace")
.Elements("Type")
.Concat(assemblyElement.Elements("Type"))
.Where(c => (c.Parent.Attribute("Name").Value + "." + c.Attribute("Name").Value).Equals(className))
.Descendants("Statement")
.Select(c => c.Attribute("FileIndex").Value)
.Distinct()
.ToArray();
var filteredFilesOfClass = fileIdsOfClass
.Select(fileId =>
new
{
FileId = fileId,
FilePath = files.First(f => f.Attribute("Index").Value == fileId).Attribute("Name").Value
})
.Where(f => this.FileFilter.IsElementIncludedInReport(f.FilePath))
.ToArray();
// If all files are removed by filters, then the whole class is omitted
if ((fileIdsOfClass.Length == 0 && !this.FileFilter.HasCustomFilters) || filteredFilesOfClass.Length > 0)
{
var @class = new Class(className, assembly);
foreach (var file in filteredFilesOfClass)
{
@class.AddFile(ProcessFile(modules, file.FileId, @class, file.FilePath));
}
assembly.AddClass(@class);
}
}
/// <summary>
/// Processes the file.
/// </summary>
/// <param name="modules">The modules.</param>
/// <param name="fileId">The file id.</param>
/// <param name="class">The class.</param>
/// <param name="filePath">The file path.</param>
/// <returns>The <see cref="CodeFile"/>.</returns>
private static CodeFile ProcessFile(XElement[] modules, string fileId, Class @class, string filePath)
{
var assemblyElement = modules
.Where(m => m.Attribute("Name").Value.Equals(@class.Assembly.Name));
var methodsOfFile = assemblyElement
.Elements("Namespace")
.Elements("Type")
.Concat(assemblyElement.Elements("Type"))
.Where(c => (c.Parent.Attribute("Name").Value + "." + c.Attribute("Name").Value).Equals(@class.Name))
.Descendants("Method")
.ToArray();
var statements = methodsOfFile
.Elements("Statement")
.Where(c => c.Attribute("FileIndex").Value == fileId)
.Select(c => new
{
LineNumberStart = int.Parse(c.Attribute("Line").Value, CultureInfo.InvariantCulture),
LineNumberEnd = int.Parse(c.Attribute("EndLine").Value, CultureInfo.InvariantCulture),
Visited = c.Attribute("Covered").Value == "True"
})
.OrderBy(seqpnt => seqpnt.LineNumberEnd)
.ToArray();
int[] coverage = new int[] { };
LineVisitStatus[] lineVisitStatus = new LineVisitStatus[] { };
if (statements.Length > 0)
{
coverage = new int[statements[statements.LongLength - 1].LineNumberEnd + 1];
lineVisitStatus = new LineVisitStatus[statements[statements.LongLength - 1].LineNumberEnd + 1];
for (int i = 0; i < coverage.Length; i++)
{
coverage[i] = -1;
}
foreach (var statement in statements)
{
for (int lineNumber = statement.LineNumberStart; lineNumber <= statement.LineNumberEnd; lineNumber++)
{
int visits = statement.Visited ? 1 : 0;
coverage[lineNumber] = coverage[lineNumber] == -1 ? visits : Math.Min(coverage[lineNumber] + visits, 1);
lineVisitStatus[lineNumber] = lineVisitStatus[lineNumber] == LineVisitStatus.Covered || statement.Visited ? LineVisitStatus.Covered : LineVisitStatus.NotCovered;
}
}
}
var codeFile = new CodeFile(filePath, coverage, lineVisitStatus);
SetCodeElements(codeFile, fileId, methodsOfFile);
return codeFile;
}
/// <summary>
/// Extracts the methods/properties of the given <see cref="XElement">XElements</see>.
/// </summary>
/// <param name="codeFile">The code file.</param>
/// <param name="fileId">The id of the file.</param>
/// <param name="methods">The methods.</param>
private static void SetCodeElements(CodeFile codeFile, string fileId, IEnumerable<XElement> methods)
{
foreach (var method in methods)
{
string methodName = ExtractMethodName(method.Parent.Attribute("Name").Value, method.Attribute("Name").Value);
if (LambdaMethodNameRegex.IsMatch(methodName))
{
continue;
}
CodeElementType type = CodeElementType.Method;
if (methodName.StartsWith("get_", StringComparison.OrdinalIgnoreCase)
|| methodName.StartsWith("set_", StringComparison.OrdinalIgnoreCase))
{
type = CodeElementType.Property;
methodName = methodName.Substring(4);
}
var seqpnts = method
.Elements("Statement")
.Where(c => c.Attribute("FileIndex").Value == fileId)
.Select(c => new
{
LineNumberStart = int.Parse(c.Attribute("Line").Value, CultureInfo.InvariantCulture),
LineNumberEnd = int.Parse(c.Attribute("EndLine").Value, CultureInfo.InvariantCulture)
})
.ToArray();
if (seqpnts.Length > 0)
{
int firstLine = seqpnts.Min(s => s.LineNumberStart);
int lastLine = seqpnts.Max(s => s.LineNumberEnd);
codeFile.AddCodeElement(new CodeElement(
methodName,
type,
seqpnts.Min(s => s.LineNumberStart),
seqpnts.Max(s => s.LineNumberEnd),
codeFile.CoverageQuota(firstLine, lastLine)));
}
}
}
/// <summary>
/// Extracts the method name. For async methods the original name is returned.
/// </summary>
/// <param name="typeName">The name of the class.</param>
/// <param name="methodName">The full method name.</param>
/// <returns>The method name.</returns>
private static string ExtractMethodName(string typeName, string methodName)
{
// Quick check before expensive regex is called
if (methodName.Contains("MoveNext()"))
{
Match match = CompilerGeneratedMethodNameRegex.Match(typeName + methodName);
if (match.Success)
{
return match.Groups["CompilerGeneratedName"].Value + "()";
}
}
return methodName.Substring(0, methodName.LastIndexOf(':'));
}
}
}
| |
using Loon.Utils;
using System;
using Microsoft.Xna.Framework;
using Loon.Java;
namespace Loon.Core.Geom {
public class RectBox : Shape {
public class Rect2i {
public int left;
public int top;
public int right;
public int bottom;
public override int GetHashCode()
{
return base.GetHashCode();
}
public Rect2i() {
}
public Rect2i(int left_0, int top_1, int right_2, int bottom_3) {
this.left = left_0;
this.top = top_1;
this.right = right_2;
this.bottom = bottom_3;
}
public Rect2i(Rect2i r) {
left = r.left;
top = r.top;
right = r.right;
bottom = r.bottom;
}
public override bool Equals(object obj) {
Rect2i r = (Rect2i) obj;
if (r != null) {
return left == r.left && top == r.top && right == r.right
&& bottom == r.bottom;
}
return false;
}
public bool IsEmpty() {
return left >= right || top >= bottom;
}
public int Width() {
return right - left;
}
public int Height() {
return bottom - top;
}
public int CenterX() {
return (left + right) >> 1;
}
public int CenterY() {
return (top + bottom) >> 1;
}
public float ExactCenterX() {
return (left + right) * 0.5f;
}
public float ExactCenterY() {
return (top + bottom) * 0.5f;
}
public void SetEmpty() {
left = right = top = bottom = 0;
}
public void Set(int left_0, int top_1, int right_2, int bottom_3) {
this.left = left_0;
this.top = top_1;
this.right = right_2;
this.bottom = bottom_3;
}
public void Set(Rect2i src) {
this.left = src.left;
this.top = src.top;
this.right = src.right;
this.bottom = src.bottom;
}
public void Offset(int dx, int dy) {
left += dx;
top += dy;
right += dx;
bottom += dy;
}
public void OffsetTo(int newLeft, int newTop) {
right += newLeft - left;
bottom += newTop - top;
left = newLeft;
top = newTop;
}
public void Inset(int dx, int dy) {
left += dx;
top += dy;
right -= dx;
bottom -= dy;
}
public bool Contains(int x, int y) {
return left < right && top < bottom && x >= left && x < right
&& y >= top && y < bottom;
}
public bool Contains(int left_0, int top_1, int right_2, int bottom_3) {
return this.left < this.right && this.top < this.bottom
&& this.left <= left_0 && this.top <= top_1
&& this.right >= right_2 && this.bottom >= bottom_3;
}
public bool Contains(Rect2i r) {
return this.left < this.right && this.top < this.bottom
&& left <= r.left && top <= r.top && right >= r.right
&& bottom >= r.bottom;
}
public bool Intersect(int left_0, int top_1, int right_2, int bottom_3) {
if (this.left < right_2 && left_0 < this.right && this.top < bottom_3
&& top_1 < this.bottom) {
if (this.left < left_0) {
this.left = left_0;
}
if (this.top < top_1) {
this.top = top_1;
}
if (this.right > right_2) {
this.right = right_2;
}
if (this.bottom > bottom_3) {
this.bottom = bottom_3;
}
return true;
}
return false;
}
public bool Intersect(Rect2i r) {
return Intersect(r.left, r.top, r.right, r.bottom);
}
public bool SetIntersect(Rect2i a, Rect2i b) {
if (a.left < b.right && b.left < a.right && a.top < b.bottom
&& b.top < a.bottom) {
left = Math.Max(a.left,b.left);
top = Math.Max(a.top,b.top);
right = Math.Min(a.right,b.right);
bottom = Math.Min(a.bottom,b.bottom);
return true;
}
return false;
}
public bool Intersects(int left_0, int top_1, int right_2, int bottom_3) {
return this.left < right_2 && left_0 < this.right && this.top < bottom_3
&& top_1 < this.bottom;
}
public static bool Intersects(Rect2i a, Rect2i b) {
return a.left < b.right && b.left < a.right && a.top < b.bottom
&& b.top < a.bottom;
}
public void Union(int left_0, int top_1, int right_2, int bottom_3) {
if ((left_0 < right_2) && (top_1 < bottom_3)) {
if ((this.left < this.right) && (this.top < this.bottom)) {
if (this.left > left_0)
this.left = left_0;
if (this.top > top_1)
this.top = top_1;
if (this.right < right_2)
this.right = right_2;
if (this.bottom < bottom_3)
this.bottom = bottom_3;
} else {
this.left = left_0;
this.top = top_1;
this.right = right_2;
this.bottom = bottom_3;
}
}
}
public void Union(Rect2i r) {
Union(r.left, r.top, r.right, r.bottom);
}
public void Union(int x, int y) {
if (x < left) {
left = x;
} else if (x > right) {
right = x;
}
if (y < top) {
top = y;
} else if (y > bottom) {
bottom = y;
}
}
public void Sort() {
if (left > right) {
int temp = left;
left = right;
right = temp;
}
if (top > bottom) {
int temp_0 = top;
top = bottom;
bottom = temp_0;
}
}
public void Scale(float scale) {
if (scale != 1.0f) {
left = (int) (left * scale + 0.5f);
top = (int) (top * scale + 0.5f);
right = (int) (right * scale + 0.5f);
bottom = (int) (bottom * scale + 0.5f);
}
}
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public int width;
public int height;
public void Offset(Vector2f offset) {
x += offset.x;
y += offset.y;
}
public void Offset(int offsetX, int offsetY) {
x += offsetX;
y += offsetY;
}
public int Left() {
return this.X();
}
public int Right() {
return (int) (this.x + this.width);
}
public int Top() {
return this.Y();
}
public int Bottom() {
return (int) (this.y + this.height);
}
public RectBox() {
SetBounds(0, 0, 0, 0);
}
public RectBox(int x, int y, int width_0, int height_1) {
SetBounds(x, y, width_0, height_1);
}
public RectBox(float x, float y, float width_0, float height_1) {
SetBounds(x, y, width_0, height_1);
}
public RectBox(double x, double y, double width_0, double height_1) {
SetBounds(x, y, width_0, height_1);
}
public RectBox(RectBox rect) {
SetBounds(rect.x, rect.y, rect.width, rect.height);
}
public void SetBoundsFromCenter(float centerX, float centerY,
float cornerX, float cornerY)
{
float halfW = MathUtils.Abs(cornerX - centerX);
float halfH = MathUtils.Abs(cornerY - centerY);
SetBounds(centerX - halfW, centerY - halfH, halfW * 2.0, halfH * 2.0);
}
public void SetBounds(RectBox rect) {
SetBounds(rect.x, rect.y, rect.width, rect.height);
}
public void SetBounds(double x, double y, double width_0, double height_1) {
SetBounds((float) x, (float) y, (float) width_0, (float) height_1);
}
public void SetBounds(float x, float y, float width_0, float height_1) {
this.x = x;
this.y = y;
this.width = (int) width_0;
this.height = (int) height_1;
this.minX = x;
this.minY = y;
this.maxX = x + width_0;
this.maxY = y + height_1;
this.pointsDirty = true;
this.CheckPoints();
}
public void Inflate(int horizontalValue, int verticalValue) {
this.x -= horizontalValue;
this.y -= verticalValue;
this.width += horizontalValue * 2;
this.height += verticalValue * 2;
}
public void SetLocation(RectBox r) {
this.x = r.x;
this.y = r.y;
}
public void SetLocation(Point r) {
this.x = r.x;
this.y = r.y;
}
public void SetLocation(int x, int y) {
this.x = x;
this.y = y;
}
public void Grow(float h, float v) {
SetX(GetX() - h);
SetY(GetY() - v);
SetWidth(GetWidth() + (h * 2));
SetHeight(GetHeight() + (v * 2));
}
public void ScaleGrow(float h, float v) {
Grow(GetWidth() * (h - 1), GetHeight() * (v - 1));
}
public override void SetScale(float sx, float sy) {
if (scaleX != sx || scaleY != sy) {
SetSize(width * (scaleX = sx), height * (scaleY * sy));
}
}
public void SetSize(float width_0, float height_1) {
SetWidth(width_0);
SetHeight(height_1);
}
public bool Overlaps(RectBox rectangle) {
return !(x > rectangle.x + rectangle.width || x + width < rectangle.x
|| y > rectangle.y + rectangle.height || y + height < rectangle.y);
}
public int X() {
return (int) x;
}
public int Y() {
return (int) y;
}
public override float GetX() {
return x;
}
public override void SetX(float x) {
this.x = x;
}
public override float GetY() {
return y;
}
public override void SetY(float y) {
this.y = y;
}
public void Copy(RectBox other) {
this.x = other.x;
this.y = other.y;
this.width = other.width;
this.height = other.height;
}
public override float GetMinX() {
return GetX();
}
public override float GetMinY() {
return GetY();
}
public override float GetMaxX() {
return this.x + this.width;
}
public override float GetMaxY() {
return this.y + this.height;
}
public float GetRight() {
return GetMaxX();
}
public float GetBottom() {
return GetMaxY();
}
public float GetMiddleX() {
return this.x + this.width / 2;
}
public float GetMiddleY() {
return this.y + this.height / 2;
}
public override float GetCenterX() {
return x + width / 2f;
}
public override float GetCenterY() {
return y + height / 2f;
}
public static RectBox GetIntersection(RectBox a, RectBox b) {
float a_x = a.GetX();
float a_r = a.GetRight();
float a_y = a.GetY();
float a_t = a.GetBottom();
float b_x = b.GetX();
float b_r = b.GetRight();
float b_y = b.GetY();
float b_t = b.GetBottom();
float i_x = MathUtils.Max(a_x, b_x);
float i_r = MathUtils.Min(a_r, b_r);
float i_y = MathUtils.Max(a_y, b_y);
float i_t = MathUtils.Min(a_t, b_t);
return (i_x < i_r && i_y < i_t) ? new RectBox(i_x, i_y, i_r - i_x, i_t
- i_y) : null;
}
public static RectBox GetIntersection(RectBox a, RectBox b, RectBox result) {
float a_x = a.GetX();
float a_r = a.GetRight();
float a_y = a.GetY();
float a_t = a.GetBottom();
float b_x = b.GetX();
float b_r = b.GetRight();
float b_y = b.GetY();
float b_t = b.GetBottom();
float i_x = MathUtils.Max(a_x, b_x);
float i_r = MathUtils.Min(a_r, b_r);
float i_y = MathUtils.Max(a_y, b_y);
float i_t = MathUtils.Min(a_t, b_t);
if (i_x < i_r && i_y < i_t) {
result.SetBounds(i_x, i_y, i_r - i_x, i_t - i_y);
return result;
}
return null;
}
public float[] ToFloat() {
return new float[] { x, y, width, height };
}
public override RectBox GetRect() {
return this;
}
private Rectangle rectangle = new Rectangle();
public Rectangle GetRectangle2D()
{
rectangle.X = (int)x;
rectangle.Y = (int)y;
rectangle.Width = width;
rectangle.Height = height;
return rectangle;
}
public override float GetHeight() {
return height;
}
public void SetHeight(float height_0) {
this.height = (int) height_0;
}
public override float GetWidth() {
return width;
}
public void SetWidth(float width_0) {
this.width = (int) width_0;
}
public override bool Equals(object obj) {
if (obj is RectBox) {
RectBox rect = (RectBox) obj;
return Equals(rect.x, rect.y, rect.width, rect.height);
} else {
return false;
}
}
public bool Equals(float x, float y, float width_0, float height_1) {
return (this.x == x && this.y == y && this.width == width_0 && this.height == height_1);
}
public int GetArea() {
return width * height;
}
public override bool Contains(float x, float y) {
return Contains(x, y, 0, 0);
}
public bool Contains(float x, float y, float width_0, float height_1) {
return (x >= this.x && y >= this.y
&& ((x + width_0) <= (this.x + this.width)) && ((y + height_1) <= (this.y + this.height)));
}
public bool Contains(RectBox rect) {
return Contains(rect.x, rect.y, rect.width, rect.height);
}
public bool Intersects(RectBox rect) {
return Intersects(rect.x, rect.y, rect.width, rect.height);
}
public bool Intersects(int x, int y) {
return Intersects(0, 0, width, height);
}
public bool Intersects(float x, float y, float width_0, float height_1) {
return x + width_0 > this.x && x < this.x + this.width
&& y + height_1 > this.y && y < this.y + this.height;
}
public void Intersection(RectBox rect) {
Intersection(rect.x, rect.y, rect.width, rect.height);
}
public void Intersection(float x, float y, float width_0, float height_1) {
int x1 = (int) MathUtils.Max(this.x, x);
int y1 = (int) MathUtils.Max(this.y, y);
int x2 = (int) MathUtils.Min(this.x + this.width - 1, x + width_0 - 1);
int y2 = (int) MathUtils.Min(this.y + this.height - 1, y + height_1 - 1);
SetBounds(x1, y1, Math.Max(0,x2 - x1 + 1), Math.Max(0,y2 - y1 + 1));
}
public bool Inside(int x, int y) {
return (x >= this.x) && ((x - this.x) < this.width) && (y >= this.y)
&& ((y - this.y) < this.height);
}
public RectBox GetIntersection(RectBox rect) {
int x1 = (int) MathUtils.Max(x, rect.x);
int x2 = (int) MathUtils.Min(x + width, rect.x + rect.width);
int y1 = (int) MathUtils.Max(y, rect.y);
int y2 = (int) MathUtils.Min(y + height, rect.y + rect.height);
return new RectBox(x1, y1, x2 - x1, y2 - y1);
}
public void Union(RectBox rect) {
Union(rect.x, rect.y, rect.width, rect.height);
}
public void Union(float x, float y, float width_0, float height_1) {
int x1 = (int) MathUtils.Min(this.x, x);
int y1 = (int) MathUtils.Min(this.y, y);
int x2 = (int) MathUtils.Max(this.x + this.width - 1, x + width_0 - 1);
int y2 = (int) MathUtils.Max(this.y + this.height - 1, y + height_1 - 1);
SetBounds(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
}
protected internal override void CreatePoints() {
float useWidth = width;
float useHeight = height;
points = new float[8];
points[0] = x;
points[1] = y;
points[2] = x + useWidth;
points[3] = y;
points[4] = x + useWidth;
points[5] = y + useHeight;
points[6] = x;
points[7] = y + useHeight;
maxX = points[2];
maxY = points[5];
minX = points[0];
minY = points[1];
FindCenter();
CalculateRadius();
}
public override Shape Transform(Matrix transform) {
CheckPoints();
Polygon resultPolygon = new Polygon();
float[] result = new float[points.Length];
transform.Transform(points, 0, result, 0, points.Length / 2);
resultPolygon.points = result;
resultPolygon.FindCenter();
resultPolygon.CheckPoints();
return resultPolygon;
}
public void ModX(float xMod) {
x += xMod;
}
public void ModY(float yMod) {
y += yMod;
}
public void ModWidth(float w) {
this.width += (int)w;
}
public void ModHeight(float h) {
this.height += (int)h;
}
public bool IntersectsLine(float x1, float y1,
float x2, float y2) {
return Contains(x1, y1) || Contains(x2, y2);
}
public bool Inside(float x, float y) {
return (x >= this.x) && ((x - this.x) < this.width) && (y >= this.y)
&& ((y - this.y) < this.height);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/// This class is primarily used to test buffer boundary integrity of readers.
/// This class constructs a memory stream from the given buffer boundary length such that
/// the required tag completely lies exactly on the start and end of buffer boundary.
/// The class makes up the additional bytes by filling in white spaces if so.
/// The first buffer length consists of the XML Decl and the Root Start (done by PrepareStream() )
/// The next buffer length consists of the actual start and end text with the variable content stretched
/// out to end at the buffer boundary.
///
using System;
using System.Xml;
using System.Text;
using System.IO;
using OLEDB.Test.ModuleCore;
using System.Collections.Generic;
namespace XmlCoreTest.Common
{
/// <summary>
/// This class contains helper methods for Readers.
/// ConvertToBinaryStream : Converts the given xml string to the binary equivalent of the string and returns it
/// using a memory stream.
/// Common usage pattern would be something like :
/// XmlReader.Create( new MemoryStream(ReaderHelper.ConvertToBinaryStream("<elem>abc</elem>", true, false)), "baseUri", readerSettings );
/// </summary>
public static partial class ReaderHelper
{
//All possible enum strings are listed here.
//Some of them are duplicates reader types for legacy readers.
public enum ReaderType
{
COREREADER,
COREVALIDATINGREADER,
CUSTOMREADER,
CHARCHECKINGREADER,
SUBTREEREADER,
WRAPPEDREADER
}
public enum ReadOverload
{
String,
TextReader,
Stream,
URL,
XmlReader
}
public class CreateReaderParams
{
public ReaderType readerType;
public string BaseUri = null;
public ReadOverload InputType;
public object Input;
public XmlParserContext ParserContext = null;
public XmlNameTable NT = null;
public bool EnableNormalization = true;
public bool IsFragment = false;
public XmlReaderSettings Settings;
public CreateReaderParams(ReaderType type)
{
readerType = type;
}
public CreateReaderParams(
ReaderType type,
ReadOverload inputType,
object input,
string baseUri,
bool isFragment,
bool enableNormalization,
XmlReaderSettings readerSettings)
{
readerType = type;
BaseUri = baseUri;
Input = input;
InputType = inputType;
IsFragment = isFragment;
EnableNormalization = enableNormalization;
Settings = readerSettings;
}
public CreateReaderParams(
ReaderType type,
ReadOverload inputType,
object input,
XmlReaderSettings readerSettings)
{
readerType = type;
Input = input;
InputType = inputType;
Settings = readerSettings;
}
}
//Using these overloads with external entities may not work because there is no evidence or baseuri used.
public static XmlReader CreateReader(ReaderType readerType, TextReader stringReader, bool enableNormalization)
{
return CreateReader(readerType.ToString(), stringReader, enableNormalization, null, null);
}
public static XmlReader CreateReader(string readerType, TextReader stringReader, bool enableNormalization)
{
return CreateReader(readerType, stringReader, enableNormalization, null, null); //use default eventhandler
}
public static XmlReader CreateReader(string readerType, TextReader stringReader, bool enableNormalization, object eventHndlr, XmlReaderSettings settings)
{
return CreateReader(readerType, stringReader, enableNormalization, eventHndlr, settings, false);
}
public static XmlReader CreateReader(string readerType, TextReader stringReader, bool enableNormalization, object eventHndlr, XmlReaderSettings settings, bool isFragment)
{
CError.WriteLineIgnore(readerType);
ReaderType type = (ReaderType)Enum.Parse(typeof(ReaderType), readerType.ToUpperInvariant());
CreateReaderParams readerParams = new CreateReaderParams(type);
readerParams.InputType = ReadOverload.TextReader;
readerParams.Input = stringReader;
readerParams.EnableNormalization = enableNormalization;
readerParams.IsFragment = isFragment;
readerParams.Settings = settings;
return CreateReader(readerParams);
}
//This API doesn't attach a default validation event handler.
public static XmlReader CreateReader(ReaderType readerType, Stream stream, string baseUri, bool enableNormalization)
{
return CreateReader(readerType.ToString(), stream, baseUri, enableNormalization, null, null, false);
}
public static XmlReader CreateReader(string readerType, Stream stream, string baseUri, bool enableNormalization)
{
return CreateReader(readerType, stream, baseUri, enableNormalization, null, null, false); //use default eventhandler
}
public static XmlReader CreateReader(string readerType, Stream stream, string baseUri, bool enableNormalization, object eventHndlr, XmlReaderSettings settings, bool isFragment)
{
CError.WriteLineIgnore(readerType);
ReaderType type = (ReaderType)Enum.Parse(typeof(ReaderType), readerType.ToUpperInvariant());
CreateReaderParams readerParams = new CreateReaderParams(type);
readerParams.InputType = ReadOverload.Stream;
readerParams.Input = stream;
readerParams.BaseUri = baseUri;
readerParams.EnableNormalization = enableNormalization;
readerParams.IsFragment = isFragment;
readerParams.Settings = settings;
return CreateReader(readerParams);
}
//This API attaches a default validation event handler.
public static XmlReader CreateReader(ReaderType readerType, string url, bool enableNormalization)
{
return CreateReader(readerType.ToString(), url, enableNormalization, null, null);
}
public static XmlReader CreateReader(string readerType, string url, bool enableNormalization)
{
return CreateReader(readerType, url, enableNormalization, null, null); //use default eventhandler
}
public static XmlReader CreateReader(string readerType, string url, bool enableNormalization, object eventHndlr, XmlReaderSettings settings)
{
return CreateReader(readerType, url, enableNormalization, eventHndlr, settings, false);
}
public static XmlReader CreateReader(string readerType, string url, bool enableNormalization, object eventHndlr, XmlReaderSettings settings, bool isFragment)
{
CError.WriteLineIgnore(readerType);
ReaderType type = (ReaderType)Enum.Parse(typeof(ReaderType), readerType.ToUpperInvariant());
CreateReaderParams readerParams = new CreateReaderParams(type);
readerParams.InputType = ReadOverload.URL;
readerParams.Input = url;
readerParams.EnableNormalization = enableNormalization;
readerParams.IsFragment = isFragment;
readerParams.Settings = settings;
return CreateReader(readerParams);
}
public static XmlReader CreateReader(ReaderType readerType, XmlReader underlyingReader, bool enableNormalization)
{
return CreateReader(readerType.ToString(), underlyingReader, enableNormalization, null, null);
}
public static XmlReader CreateReader(string readerType, XmlReader underlyingReader, bool enableNormalization)
{
return CreateReader(readerType, underlyingReader, enableNormalization, null, null); //use default eventhandler
}
public static XmlReader CreateReader(string readerType, XmlReader underlyingReader, bool enableNormalization, object eventHndlr, XmlReaderSettings settings)
{
return CreateReader(readerType, underlyingReader, enableNormalization, eventHndlr, settings, false);
}
public static XmlReader CreateReader(string readerType, XmlReader underlyingReader, bool enableNormalization, object eventHndlr, XmlReaderSettings settings, bool isFragment)
{
CError.WriteLineIgnore(readerType);
ReaderType type = (ReaderType)Enum.Parse(typeof(ReaderType), readerType.ToUpperInvariant());
CreateReaderParams readerParams = new CreateReaderParams(type);
readerParams.InputType = ReadOverload.XmlReader;
readerParams.Input = underlyingReader;
readerParams.EnableNormalization = enableNormalization;
readerParams.IsFragment = isFragment;
readerParams.Settings = settings;
return CreateReader(readerParams);
}
public static void CreateXSLTStyleSheetWCopyTestFile(string strFileName)
{
}
public static XmlReader CreateReader(CreateReaderParams createParams)
{
switch (createParams.readerType)
{
case ReaderType.COREREADER:
case ReaderType.COREVALIDATINGREADER:
return CreateFactoryReader(createParams);
case ReaderType.CHARCHECKINGREADER:
return CreateCharCheckingReader(createParams);
case ReaderType.SUBTREEREADER:
return CreateSubtreeReader(createParams);
case ReaderType.WRAPPEDREADER:
return CreateWrappedReader(createParams);
default:
throw new CTestFailedException("Unsupported ReaderType");
}
}
public static XmlReader CreateCharCheckingReader(CreateReaderParams createParams)
{
XmlReaderSettings settings = GetSettings(createParams);
XmlParserContext parserContext = GetParserContext(createParams);
XmlReader r = null;
settings.CheckCharacters = false;
XmlReaderSettings rs = settings.Clone();
rs.CheckCharacters = true;
switch (createParams.InputType)
{
case ReadOverload.String:
r = Create(new StringReader((string)createParams.Input), settings, parserContext);
return Create(r, rs);
case ReadOverload.URL:
r = Create((string)createParams.Input, settings);
return Create(r, rs);
case ReadOverload.Stream:
r = Create((Stream)createParams.Input, settings, parserContext);
return Create(r, rs);
case ReadOverload.TextReader:
r = Create((TextReader)createParams.Input, settings, parserContext);
return Create(r, rs);
case ReadOverload.XmlReader:
r = Create((XmlReader)createParams.Input, settings);
return Create(r, rs);
default:
throw new CTestFailedException("Unknown ReadOverload");
}
}
public static XmlReader CreateSubtreeReader(CreateReaderParams createParams)
{
XmlReaderSettings settings = GetSettings(createParams);
XmlParserContext parserContext = GetParserContext(createParams);
XmlReader r = null;
switch (createParams.InputType)
{
case ReadOverload.String:
r = Create(new StringReader((string)createParams.Input), settings, parserContext);
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
break;
}
return r.ReadSubtree();
case ReadOverload.URL:
r = Create((string)createParams.Input, settings);
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
break;
}
return r.ReadSubtree();
case ReadOverload.Stream:
r = Create((Stream)createParams.Input, settings, parserContext);
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
break;
}
return r.ReadSubtree();
case ReadOverload.TextReader:
r = Create((TextReader)createParams.Input, settings, parserContext);
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
break;
}
return r.ReadSubtree();
case ReadOverload.XmlReader:
r = Create((XmlReader)createParams.Input, settings);
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
break;
}
return r.ReadSubtree();
default:
throw new CTestFailedException("Unknown ReadOverload");
}
}
public static XmlReader CreateWrappedReader(CreateReaderParams createParams)
{
XmlReaderSettings settings = GetSettings(createParams);
XmlParserContext parserContext = GetParserContext(createParams);
XmlReader r = null;
switch (createParams.InputType)
{
case ReadOverload.String:
r = Create(new StringReader((string)createParams.Input), settings, parserContext);
return Create(r, settings);
case ReadOverload.URL:
r = Create((string)createParams.Input, settings);
return Create(r, settings);
case ReadOverload.Stream:
r = Create((Stream)createParams.Input, settings, parserContext);
return Create(r, settings);
case ReadOverload.TextReader:
r = Create((TextReader)createParams.Input, settings, parserContext);
return Create(r, settings);
case ReadOverload.XmlReader:
r = Create((XmlReader)createParams.Input, settings);
return Create(r, settings);
default:
throw new CTestFailedException("Unknown ReadOverload");
}
}
public static XmlReaderSettings GetSettings(CreateReaderParams createParams)
{
XmlReaderSettings settings = new XmlReaderSettings();
if (createParams.Settings != null)
{
settings = createParams.Settings;
}
else
{
if (createParams.IsFragment)
settings.ConformanceLevel = ConformanceLevel.Fragment;
}
return settings;
}
public static XmlParserContext GetParserContext(CreateReaderParams createParams)
{
if (createParams.ParserContext != null)
return createParams.ParserContext;
else
{
if (createParams.BaseUri != null)
{
XmlParserContext parserContext = new XmlParserContext(null, null, null, null, null, null, createParams.BaseUri, null, XmlSpace.None);
return parserContext;
}
else
{
return null;
}
}
}
public static XmlReader CreateFactoryReader(CreateReaderParams createParams)
{
XmlReaderSettings settings = GetSettings(createParams);
XmlParserContext parserContext = GetParserContext(createParams);
switch (createParams.InputType)
{
case ReadOverload.String:
return Create(new StringReader((string)createParams.Input), settings, parserContext);
case ReadOverload.URL:
return Create((string)createParams.Input, settings, parserContext);
case ReadOverload.Stream:
return Create((Stream)createParams.Input, settings, parserContext);
case ReadOverload.TextReader:
return Create((TextReader)createParams.Input, settings, parserContext);
case ReadOverload.XmlReader:
return Create((XmlReader)createParams.Input, settings);
default:
throw new CTestFailedException("Unknown ReadOverload");
}
}
private static Random s_rand = new Random((int)DateTime.Now.Ticks);
public static IEnumerable<string> GenerateNames(int count, bool isValid, CharType charType)
{
Func<CharType, string> generator = isValid ? (Func<CharType, string>)UnicodeCharHelper.GetValidCharacters : (Func<CharType, string>)UnicodeCharHelper.GetInvalidCharacters;
string chars = generator(charType);
for (int i = 0; i < count; i++)
{
char c = chars[s_rand.Next(chars.Length)];
yield return GetNameWithChar(c, charType);
}
}
public static string GetNameWithChar(char c, CharType charType)
{
switch (charType)
{
case CharType.NameStartChar:
return new string(new char[] { c, 'a', 'b' });
case CharType.NameChar:
return new string(new char[] { 'a', c, 'b' });
case CharType.NameStartSurrogateHighChar:
return new string(new char[] { c, '\udc00', 'a', 'b' });
case CharType.NameStartSurrogateLowChar:
return new string(new char[] { '\udb7f', c, 'a', 'b' });
case CharType.NameSurrogateHighChar:
return new string(new char[] { 'a', 'b', c, '\udc00' });
case CharType.NameSurrogateLowChar:
return new string(new char[] { 'a', 'b', '\udb7f', c });
default:
throw new CTestFailedException("TEST ISSUE: CharType FAILURE!");
}
}
public static XmlReader Create(string inputUri)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(FilePathUtil.getStream(inputUri));
}
else
{
return XmlReader.Create(FilePathUtil.getStream(inputUri));
}
}
public static XmlReader Create(string inputUri, XmlReaderSettings settings)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(FilePathUtil.getStream(inputUri), settings);
}
else
{
return XmlReader.Create(FilePathUtil.getStream(inputUri), settings);
}
}
public static XmlReader Create(String inputUri, XmlReaderSettings settings, XmlParserContext inputContext)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(FilePathUtil.getStream(inputUri), settings, inputContext);
}
else
{
return XmlReader.Create(FilePathUtil.getStream(inputUri));//, settings, inputContext);
}
}
public static XmlReader Create(Stream input)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input);
}
else
{
return XmlReader.Create(input);
}
}
public static XmlReader Create(Stream input, XmlReaderSettings settings)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input, settings);
}
else
{
return XmlReader.Create(input, settings);
}
}
public static XmlReader Create(Stream input, XmlReaderSettings settings, String baseUri)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input, settings, baseUri);
}
else
{
return XmlReader.Create(input, settings);//, baseUri);
}
}
public static XmlReader Create(Stream input, XmlReaderSettings settings, XmlParserContext inputContext)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input, settings, inputContext);
}
else
{
return XmlReader.Create(input, settings, inputContext);
}
}
public static XmlReader Create(TextReader input)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input);
}
else
{
return XmlReader.Create(input);
}
}
public static XmlReader Create(TextReader input, XmlReaderSettings settings)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input, settings);
}
else
{
return XmlReader.Create(input, settings);
}
}
public static XmlReader Create(TextReader input, XmlReaderSettings settings, String baseUri)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input, settings, baseUri);
}
else
{
return XmlReader.Create(input, settings);//, baseUri);
}
}
public static XmlReader Create(TextReader input, XmlReaderSettings settings, XmlParserContext inputContext)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(input, settings, inputContext);
}
else
{
return XmlReader.Create(input, settings, inputContext);
}
}
public static XmlReader Create(XmlReader reader, XmlReaderSettings settings)
{
if (AsyncUtil.IsAsyncEnabled)
{
return XmlReaderAsync.Create(reader, settings);
}
else
{
return XmlReader.Create(reader, settings);
}
}
}
}
| |
using Microsoft.Xna.Framework;
namespace ConversionHelper
{
/// <summary>
/// Helps convert between XNA math types and the BEPUphysics replacement math types.
/// A version of this converter could be created for other platforms to ease the integration of the engine.
/// </summary>
public static class MathConverter
{
//Vector2
public static Vector2 Convert(BEPUutilities.Vector2 bepuVector)
{
Vector2 toReturn;
toReturn.X = bepuVector.X;
toReturn.Y = bepuVector.Y;
return toReturn;
}
public static void Convert(ref BEPUutilities.Vector2 bepuVector, out Vector2 xnaVector)
{
xnaVector.X = bepuVector.X;
xnaVector.Y = bepuVector.Y;
}
public static BEPUutilities.Vector2 Convert(Vector2 xnaVector)
{
BEPUutilities.Vector2 toReturn;
toReturn.X = xnaVector.X;
toReturn.Y = xnaVector.Y;
return toReturn;
}
public static void Convert(ref Vector2 xnaVector, out BEPUutilities.Vector2 bepuVector)
{
bepuVector.X = xnaVector.X;
bepuVector.Y = xnaVector.Y;
}
//Vector3
public static Vector3 Convert(BEPUutilities.Vector3 bepuVector)
{
Vector3 toReturn;
toReturn.X = bepuVector.X;
toReturn.Y = bepuVector.Y;
toReturn.Z = bepuVector.Z;
return toReturn;
}
public static void Convert(ref BEPUutilities.Vector3 bepuVector, out Vector3 xnaVector)
{
xnaVector.X = bepuVector.X;
xnaVector.Y = bepuVector.Y;
xnaVector.Z = bepuVector.Z;
}
public static BEPUutilities.Vector3 Convert(Vector3 xnaVector)
{
BEPUutilities.Vector3 toReturn;
toReturn.X = xnaVector.X;
toReturn.Y = xnaVector.Y;
toReturn.Z = xnaVector.Z;
return toReturn;
}
public static void Convert(ref Vector3 xnaVector, out BEPUutilities.Vector3 bepuVector)
{
bepuVector.X = xnaVector.X;
bepuVector.Y = xnaVector.Y;
bepuVector.Z = xnaVector.Z;
}
public static Vector3[] Convert(BEPUutilities.Vector3[] bepuVectors)
{
Vector3[] xnaVectors = new Vector3[bepuVectors.Length];
for (int i = 0; i < bepuVectors.Length; i++)
{
Convert(ref bepuVectors[i], out xnaVectors[i]);
}
return xnaVectors;
}
public static BEPUutilities.Vector3[] Convert(Vector3[] xnaVectors)
{
var bepuVectors = new BEPUutilities.Vector3[xnaVectors.Length];
for (int i = 0; i < xnaVectors.Length; i++)
{
Convert(ref xnaVectors[i], out bepuVectors[i]);
}
return bepuVectors;
}
//Matrix
public static Matrix Convert(BEPUutilities.Matrix matrix)
{
Matrix toReturn;
Convert(ref matrix, out toReturn);
return toReturn;
}
public static BEPUutilities.Matrix Convert(Matrix matrix)
{
BEPUutilities.Matrix toReturn;
Convert(ref matrix, out toReturn);
return toReturn;
}
public static void Convert(ref BEPUutilities.Matrix matrix, out Matrix xnaMatrix)
{
xnaMatrix.M11 = matrix.M11;
xnaMatrix.M12 = matrix.M12;
xnaMatrix.M13 = matrix.M13;
xnaMatrix.M14 = matrix.M14;
xnaMatrix.M21 = matrix.M21;
xnaMatrix.M22 = matrix.M22;
xnaMatrix.M23 = matrix.M23;
xnaMatrix.M24 = matrix.M24;
xnaMatrix.M31 = matrix.M31;
xnaMatrix.M32 = matrix.M32;
xnaMatrix.M33 = matrix.M33;
xnaMatrix.M34 = matrix.M34;
xnaMatrix.M41 = matrix.M41;
xnaMatrix.M42 = matrix.M42;
xnaMatrix.M43 = matrix.M43;
xnaMatrix.M44 = matrix.M44;
}
public static void Convert(ref Matrix matrix, out BEPUutilities.Matrix bepuMatrix)
{
bepuMatrix.M11 = matrix.M11;
bepuMatrix.M12 = matrix.M12;
bepuMatrix.M13 = matrix.M13;
bepuMatrix.M14 = matrix.M14;
bepuMatrix.M21 = matrix.M21;
bepuMatrix.M22 = matrix.M22;
bepuMatrix.M23 = matrix.M23;
bepuMatrix.M24 = matrix.M24;
bepuMatrix.M31 = matrix.M31;
bepuMatrix.M32 = matrix.M32;
bepuMatrix.M33 = matrix.M33;
bepuMatrix.M34 = matrix.M34;
bepuMatrix.M41 = matrix.M41;
bepuMatrix.M42 = matrix.M42;
bepuMatrix.M43 = matrix.M43;
bepuMatrix.M44 = matrix.M44;
}
public static Matrix Convert(BEPUutilities.Matrix3x3 matrix)
{
Matrix toReturn;
Convert(ref matrix, out toReturn);
return toReturn;
}
public static void Convert(ref BEPUutilities.Matrix3x3 matrix, out Matrix xnaMatrix)
{
xnaMatrix.M11 = matrix.M11;
xnaMatrix.M12 = matrix.M12;
xnaMatrix.M13 = matrix.M13;
xnaMatrix.M14 = 0;
xnaMatrix.M21 = matrix.M21;
xnaMatrix.M22 = matrix.M22;
xnaMatrix.M23 = matrix.M23;
xnaMatrix.M24 = 0;
xnaMatrix.M31 = matrix.M31;
xnaMatrix.M32 = matrix.M32;
xnaMatrix.M33 = matrix.M33;
xnaMatrix.M34 = 0;
xnaMatrix.M41 = 0;
xnaMatrix.M42 = 0;
xnaMatrix.M43 = 0;
xnaMatrix.M44 = 1;
}
public static void Convert(ref Matrix matrix, out BEPUutilities.Matrix3x3 bepuMatrix)
{
bepuMatrix.M11 = matrix.M11;
bepuMatrix.M12 = matrix.M12;
bepuMatrix.M13 = matrix.M13;
bepuMatrix.M21 = matrix.M21;
bepuMatrix.M22 = matrix.M22;
bepuMatrix.M23 = matrix.M23;
bepuMatrix.M31 = matrix.M31;
bepuMatrix.M32 = matrix.M32;
bepuMatrix.M33 = matrix.M33;
}
//Quaternion
public static Quaternion Convert(BEPUutilities.Quaternion quaternion)
{
Quaternion toReturn;
toReturn.X = quaternion.X;
toReturn.Y = quaternion.Y;
toReturn.Z = quaternion.Z;
toReturn.W = quaternion.W;
return toReturn;
}
public static BEPUutilities.Quaternion Convert(Quaternion quaternion)
{
BEPUutilities.Quaternion toReturn;
toReturn.X = quaternion.X;
toReturn.Y = quaternion.Y;
toReturn.Z = quaternion.Z;
toReturn.W = quaternion.W;
return toReturn;
}
public static void Convert(ref BEPUutilities.Quaternion bepuQuaternion, out Quaternion quaternion)
{
quaternion.X = bepuQuaternion.X;
quaternion.Y = bepuQuaternion.Y;
quaternion.Z = bepuQuaternion.Z;
quaternion.W = bepuQuaternion.W;
}
public static void Convert(ref Quaternion quaternion, out BEPUutilities.Quaternion bepuQuaternion)
{
bepuQuaternion.X = quaternion.X;
bepuQuaternion.Y = quaternion.Y;
bepuQuaternion.Z = quaternion.Z;
bepuQuaternion.W = quaternion.W;
}
//Ray
public static BEPUutilities.Ray Convert(Ray ray)
{
BEPUutilities.Ray toReturn;
Convert(ref ray.Position, out toReturn.Position);
Convert(ref ray.Direction, out toReturn.Direction);
return toReturn;
}
public static void Convert(ref Ray ray, out BEPUutilities.Ray bepuRay)
{
Convert(ref ray.Position, out bepuRay.Position);
Convert(ref ray.Direction, out bepuRay.Direction);
}
public static Ray Convert(BEPUutilities.Ray ray)
{
Ray toReturn;
Convert(ref ray.Position, out toReturn.Position);
Convert(ref ray.Direction, out toReturn.Direction);
return toReturn;
}
public static void Convert(ref BEPUutilities.Ray ray, out Ray xnaRay)
{
Convert(ref ray.Position, out xnaRay.Position);
Convert(ref ray.Direction, out xnaRay.Direction);
}
//BoundingBox
public static BoundingBox Convert(BEPUutilities.BoundingBox boundingBox)
{
BoundingBox toReturn;
Convert(ref boundingBox.Min, out toReturn.Min);
Convert(ref boundingBox.Max, out toReturn.Max);
return toReturn;
}
public static BEPUutilities.BoundingBox Convert(BoundingBox boundingBox)
{
BEPUutilities.BoundingBox toReturn;
Convert(ref boundingBox.Min, out toReturn.Min);
Convert(ref boundingBox.Max, out toReturn.Max);
return toReturn;
}
public static void Convert(ref BEPUutilities.BoundingBox boundingBox, out BoundingBox xnaBoundingBox)
{
Convert(ref boundingBox.Min, out xnaBoundingBox.Min);
Convert(ref boundingBox.Max, out xnaBoundingBox.Max);
}
public static void Convert(ref BoundingBox boundingBox, out BEPUutilities.BoundingBox bepuBoundingBox)
{
Convert(ref boundingBox.Min, out bepuBoundingBox.Min);
Convert(ref boundingBox.Max, out bepuBoundingBox.Max);
}
//BoundingSphere
public static BoundingSphere Convert(BEPUutilities.BoundingSphere boundingSphere)
{
BoundingSphere toReturn;
Convert(ref boundingSphere.Center, out toReturn.Center);
toReturn.Radius = boundingSphere.Radius;
return toReturn;
}
public static BEPUutilities.BoundingSphere Convert(BoundingSphere boundingSphere)
{
BEPUutilities.BoundingSphere toReturn;
Convert(ref boundingSphere.Center, out toReturn.Center);
toReturn.Radius = boundingSphere.Radius;
return toReturn;
}
public static void Convert(ref BEPUutilities.BoundingSphere boundingSphere, out BoundingSphere xnaBoundingSphere)
{
Convert(ref boundingSphere.Center, out xnaBoundingSphere.Center);
xnaBoundingSphere.Radius = boundingSphere.Radius;
}
public static void Convert(ref BoundingSphere boundingSphere, out BEPUutilities.BoundingSphere bepuBoundingSphere)
{
Convert(ref boundingSphere.Center, out bepuBoundingSphere.Center);
bepuBoundingSphere.Radius = boundingSphere.Radius;
}
//Plane
public static Plane Convert(BEPUutilities.Plane plane)
{
Plane toReturn;
Convert(ref plane.Normal, out toReturn.Normal);
toReturn.D = plane.D;
return toReturn;
}
public static BEPUutilities.Plane Convert(Plane plane)
{
BEPUutilities.Plane toReturn;
Convert(ref plane.Normal, out toReturn.Normal);
toReturn.D = plane.D;
return toReturn;
}
public static void Convert(ref BEPUutilities.Plane plane, out Plane xnaPlane)
{
Convert(ref plane.Normal, out xnaPlane.Normal);
xnaPlane.D = plane.D;
}
public static void Convert(ref Plane plane, out BEPUutilities.Plane bepuPlane)
{
Convert(ref plane.Normal, out bepuPlane.Normal);
bepuPlane.D = plane.D;
}
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira 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.
#endregion
using System.Collections;
using Boo.Lang.Compiler.TypeSystem.Internal;
using Boo.Lang.Compiler.TypeSystem.Services;
using Boo.Lang.Compiler.Util;
using Boo.Lang.Environments;
using Boo.Lang.Runtime;
namespace Boo.Lang.Compiler.Steps
{
using System;
using System.Collections.Generic;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem;
/// <summary>
/// AST semantic evaluation.
/// </summary>
public class NormalizeIterationStatements : AbstractTransformerCompilerStep
{
static System.Reflection.MethodInfo RuntimeServices_MoveNext = Methods.Of<IEnumerator, object>(RuntimeServices.MoveNext);
static System.Reflection.MethodInfo RuntimeServices_GetEnumerable = Methods.Of<object, IEnumerable>(RuntimeServices.GetEnumerable);
static System.Reflection.MethodInfo IEnumerable_GetEnumerator = Methods.InstanceFunctionOf<IEnumerable, IEnumerator>(e => e.GetEnumerator);
static System.Reflection.MethodInfo IDisposable_Dispose = Methods.InstanceActionOf<IDisposable>(d => d.Dispose);
Method _current;
override public void Run()
{
Visit(CompileUnit);
CompileUnit.Accept(new OrBlockNormalizer(Context));
}
internal class OrBlockNormalizer : DepthFirstTransformer
{
private readonly CompilerContext _context;
private Method _currentMethod;
public OrBlockNormalizer(CompilerContext context)
{
_context = context;
}
public override bool EnterMethod(Method node)
{
_currentMethod = node;
return base.EnterMethod(node);
}
public override void OnWhileStatement(WhileStatement node)
{
if (node.OrBlock == null) return;
InternalLocal enteredLoop = CodeBuilder().DeclareTempLocal(_currentMethod, BoolType());
IfStatement orPart = new IfStatement(
node.OrBlock.LexicalInfo,
CodeBuilder().CreateNotExpression(CodeBuilder().CreateReference(enteredLoop)),
node.OrBlock,
null);
node.OrBlock = orPart.ToBlock();
node.Block.Insert(0,
CodeBuilder().CreateAssignment(
CreateReference(enteredLoop),
CreateTrueLiteral()));
}
private BoolLiteralExpression CreateTrueLiteral()
{
return CodeBuilder().CreateBoolLiteral(true);
}
private ReferenceExpression CreateReference(InternalLocal enteredLoop)
{
return CodeBuilder().CreateReference(enteredLoop);
}
private IType BoolType()
{
return _typeSystemServices.Instance.BoolType;
}
private EnvironmentProvision<TypeSystemServices> _typeSystemServices;
private BooCodeBuilder CodeBuilder()
{
return _context.CodeBuilder;
}
}
override public void OnMethod(Method node)
{
_current = node;
Visit(node.Body);
}
override public void OnConstructor(Constructor node)
{
OnMethod(node);
}
override public void OnDestructor(Destructor node)
{
OnMethod(node);
}
override public void OnBlockExpression(BlockExpression node)
{
// ignore closure's body since it will be visited
// through the closure's newly created method
}
override public void LeaveUnpackStatement(UnpackStatement node)
{
Block body = new Block(node.LexicalInfo);
UnpackExpression(body, node.Expression, node.Declarations);
ReplaceCurrentNode(body);
}
override public void LeaveForStatement(ForStatement node)
{
_iteratorNode = node.Iterator;
CurrentEnumeratorType = GetExpressionType(node.Iterator);
if (null == CurrentBestEnumeratorType)
return; //error
DeclarationCollection declarations = node.Declarations;
Block body = new Block(node.LexicalInfo);
InternalLocal iterator = CodeBuilder.DeclareLocal(_current,
Context.GetUniqueName("iterator"),
CurrentBestEnumeratorType);
if (CurrentBestEnumeratorType == CurrentEnumeratorType)
{
//$iterator = <node.Iterator>
body.Add(
CodeBuilder.CreateAssignment(
node.LexicalInfo,
CodeBuilder.CreateReference(iterator),
node.Iterator));
}
else
{
//$iterator = <node.Iterator>.GetEnumerator()
body.Add(
CodeBuilder.CreateAssignment(
node.LexicalInfo,
CodeBuilder.CreateReference(iterator),
CodeBuilder.CreateMethodInvocation(node.Iterator, CurrentBestGetEnumerator)));
}
// while __iterator.MoveNext():
if (null == CurrentBestMoveNext)
return; //error
WhileStatement ws = new WhileStatement(node.LexicalInfo);
ws.Condition = CodeBuilder.CreateMethodInvocation(
CodeBuilder.CreateReference(iterator),
CurrentBestMoveNext);
if (null == CurrentBestGetCurrent)
return; //error
Expression current = CodeBuilder.CreateMethodInvocation(
CodeBuilder.CreateReference(iterator),
CurrentBestGetCurrent);
if (1 == declarations.Count)
{
// item = __iterator.Current
ws.Block.Add(
CodeBuilder.CreateAssignment(
node.LexicalInfo,
CodeBuilder.CreateReference((InternalLocal)declarations[0].Entity),
current));
}
else
{
UnpackExpression(ws.Block,
CodeBuilder.CreateCast(
CurrentEnumeratorItemType,
current),
node.Declarations);
}
ws.Block.Add(node.Block);
ws.OrBlock = node.OrBlock;
ws.ThenBlock = node.ThenBlock;
// try:
// while...
// ensure:
// d = iterator as IDisposable
// d.Dispose() unless d is null
if (IsAssignableFrom(TypeSystemServices.IDisposableType, CurrentBestEnumeratorType))
{
TryStatement tryStatement = new TryStatement();
tryStatement.ProtectedBlock.Add(ws);
tryStatement.EnsureBlock = new Block();
CastExpression castExpression = new CastExpression();
castExpression.Type = CodeBuilder.CreateTypeReference(TypeSystemServices.IDisposableType);
castExpression.Target = CodeBuilder.CreateReference(iterator);
castExpression.ExpressionType = TypeSystemServices.IDisposableType;
tryStatement.EnsureBlock.Add(
CodeBuilder.CreateMethodInvocation(castExpression, IDisposable_Dispose));
body.Add(tryStatement);
}
else
{
body.Add(ws);
}
ReplaceCurrentNode(body);
}
private bool IsAssignableFrom(IType expectedType, IType actualType)
{
return TypeCompatibilityRules.IsAssignableFrom(expectedType, actualType);
}
void UnpackExpression(Block block, Expression expression, DeclarationCollection declarations)
{
UnpackExpression(CodeBuilder, _current, block, expression, declarations);
}
public static void UnpackExpression(BooCodeBuilder codeBuilder, Method method, Block block, Expression expression, DeclarationCollection declarations)
{
if (expression.ExpressionType.IsArray)
{
UnpackArray(codeBuilder, method, block, expression, declarations);
}
else
{
UnpackEnumerable(codeBuilder, method, block, expression, declarations);
}
}
public static void UnpackEnumerable(BooCodeBuilder codeBuilder, Method method, Block block, Expression expression, DeclarationCollection declarations)
{
TypeSystemServices tss = codeBuilder.TypeSystemServices;
InternalLocal local = codeBuilder.DeclareTempLocal(method,
tss.IEnumeratorType);
IType expressionType = expression.ExpressionType;
if (expressionType.IsSubclassOf(codeBuilder.TypeSystemServices.IEnumeratorType))
{
block.Add(
codeBuilder.CreateAssignment(
codeBuilder.CreateReference(local),
expression));
}
else
{
if (!expressionType.IsSubclassOf(codeBuilder.TypeSystemServices.IEnumerableType))
{
expression = codeBuilder.CreateMethodInvocation(
RuntimeServices_GetEnumerable, expression);
}
block.Add(
codeBuilder.CreateAssignment(
block.LexicalInfo,
codeBuilder.CreateReference(local),
codeBuilder.CreateMethodInvocation(
expression, IEnumerable_GetEnumerator)));
}
for (int i=0; i<declarations.Count; ++i)
{
Declaration declaration = declarations[i];
block.Add(
codeBuilder.CreateAssignment(
codeBuilder.CreateReference(declaration.Entity),
codeBuilder.CreateMethodInvocation(RuntimeServices_MoveNext,
codeBuilder.CreateReference(local))));
}
}
public static void UnpackArray(BooCodeBuilder codeBuilder, Method method, Block block, Expression expression, DeclarationCollection declarations)
{
ILocalEntity local = expression.Entity as ILocalEntity;
if (null == local)
{
local = codeBuilder.DeclareTempLocal(method,
expression.ExpressionType);
block.Add(
codeBuilder.CreateAssignment(
codeBuilder.CreateReference(local),
expression));
}
for (int i=0; i<declarations.Count; ++i)
{
Declaration declaration = declarations[i];
block.Add(
codeBuilder.CreateAssignment(
codeBuilder.CreateReference(
declaration.Entity),
codeBuilder.CreateSlicing(
codeBuilder.CreateReference(local),
i)));
}
}
Node _iteratorNode;
IType _enumeratorType;
IType _enumeratorItemType;
IType _bestEnumeratorType;
IMethod _bestGetEnumerator;
IMethod _bestMoveNext;
IMethod _bestGetCurrent;
IType CurrentEnumeratorType
{
get { return _enumeratorType; }
set
{
if (_enumeratorType != value) //if same type reuse cache
{
_enumeratorItemType = null;
_bestEnumeratorType = null;
_bestGetEnumerator = null;
_bestMoveNext = null;
_bestGetCurrent = null;
_enumeratorType = value;
}
}
}
IType CurrentEnumeratorItemType
{
get
{
if (null == _enumeratorItemType)
_enumeratorItemType = TypeSystemServices.GetEnumeratorItemType(CurrentEnumeratorType);
return _enumeratorItemType;
}
}
IType CurrentBestEnumeratorType
{
get
{
if (null == _bestEnumeratorType)
_bestEnumeratorType = FindBestEnumeratorType();
return _bestEnumeratorType;
}
}
IMethod CurrentBestGetEnumerator
{
get {
if (null == _bestGetEnumerator)
_bestGetEnumerator = FindBestEnumeratorMethod("GetEnumerator");
return _bestGetEnumerator;
}
}
IMethod CurrentBestMoveNext
{
get {
if (null == _bestMoveNext)
_bestMoveNext = FindBestEnumeratorMethod("MoveNext");
return _bestMoveNext;
}
}
IMethod CurrentBestGetCurrent
{
get {
if (null == _bestGetCurrent)
_bestGetCurrent = FindBestEnumeratorMethod("Current");
return _bestGetCurrent;
}
}
List<IEntity> _candidates = new List<IEntity>();
IType FindBestEnumeratorType()
{
//type is already an IEnumerator, use it
if (IsAssignableFrom(TypeSystemServices.IEnumeratorType, CurrentEnumeratorType))
return CurrentEnumeratorType;
IType bestEnumeratorType = null;
_candidates.Clear();
//resolution order:
//1) type contains an applicable GetEnumerator() [whether or not type implements IEnumerator (as C# does)]
CurrentEnumeratorType.Resolve(_candidates, "GetEnumerator", EntityType.Method);
foreach (IEntity candidate in _candidates)
{
IMethod m = (IMethod) candidate;
if (null != m.GenericInfo || 0 != m.GetParameters().Length || !m.IsPublic)
continue; //only check public non-generic GetEnumerator with no argument
if (!IsAssignableFrom(TypeSystemServices.IEnumeratorGenericType, m.ReturnType)
&& !IsAssignableFrom(TypeSystemServices.IEnumeratorType, m.ReturnType))
continue; //GetEnumerator does not return an IEnumerator or IEnumerator[of T]
bestEnumeratorType = m.ReturnType;
_bestGetEnumerator = m;
break;
}
//2) type explicitly implements IEnumerable[of T]
if (null == bestEnumeratorType)
{
if (IsAssignableFrom(TypeSystemServices.IEnumerableGenericType, CurrentEnumeratorType))
{
bestEnumeratorType = TypeSystemServices.IEnumeratorGenericType;
_bestGetEnumerator = TypeSystemServices.Map(Types.IEnumerableGeneric.GetMethod("GetEnumerator"));
}
}
//3) type explicitly implements IEnumerable
if (null == bestEnumeratorType)
{
if (IsAssignableFrom(TypeSystemServices.IEnumerableType, CurrentEnumeratorType))
{
bestEnumeratorType = TypeSystemServices.IEnumeratorType;
_bestGetEnumerator = TypeSystemServices.Map(Types.IEnumerable.GetMethod("GetEnumerator"));
}
}
//4) error
if (null == bestEnumeratorType)
Errors.Add(CompilerErrorFactory.InvalidIteratorType(_iteratorNode, CurrentEnumeratorType));
return bestEnumeratorType;
}
IMethod FindBestEnumeratorMethod(string name)
{
_candidates.Clear();
CurrentBestEnumeratorType.Resolve(_candidates, name, EntityType.Method | EntityType.Property);
foreach (IEntity candidate in _candidates)
{
if (candidate is IMethod)
{
IMethod m = (IMethod) candidate;
if (null != m.GenericInfo || 0 != m.GetParameters().Length)
continue; //only check non-generic void methods with no argument
return m;
}
else
{
IProperty p = (IProperty) candidate;
return p.GetGetMethod();
}
}
Errors.Add(CompilerErrorFactory.InvalidIteratorType(_iteratorNode, CurrentEnumeratorType));
return null;
}
}
}
| |
using System;
namespace SharpVectors.Scripting
{
///
/// IScriptableDomTimeStamp
///
public interface IScriptableDomTimeStamp
{
}
/// <summary>
/// IScriptableDomImplementation
/// </summary>
public interface IScriptableDomImplementation
{
bool hasFeature(string feature, string version);
IScriptableDocumentType createDocumentType(string qualifiedName, string publicId, string systemId);
IScriptableDocument createDocument(string namespaceURI, string qualifiedName, IScriptableDocumentType doctype);
}
/// <summary>
/// IScriptableNode
/// </summary>
public interface IScriptableNode
{
IScriptableNode insertBefore(IScriptableNode newChild, IScriptableNode refChild);
IScriptableNode replaceChild(IScriptableNode newChild, IScriptableNode oldChild);
IScriptableNode removeChild(IScriptableNode oldChild);
IScriptableNode appendChild(IScriptableNode newChild);
bool hasChildNodes();
IScriptableNode cloneNode(bool deep);
void normalize();
bool isSupported(string feature, string version);
bool hasAttributes();
string nodeName { get; }
string nodeValue { get; set; }
ushort nodeType { get; }
IScriptableNode parentNode { get; }
IScriptableNodeList childNodes { get; }
IScriptableNode firstChild { get; }
IScriptableNode lastChild { get; }
IScriptableNode previousSibling { get; }
IScriptableNode nextSibling { get; }
IScriptableNamedNodeMap attributes { get; }
IScriptableDocument ownerDocument { get; }
string namespaceURI { get; }
string prefix { get; set; }
string localName { get; }
}
/// <summary>
/// IScriptableNodeList
/// </summary>
public interface IScriptableNodeList
{
IScriptableNode item(ulong index);
ulong length { get; }
}
/// <summary>
/// IScriptableNamedNodeMap
/// </summary>
public interface IScriptableNamedNodeMap
{
IScriptableNode getNamedItem(string name);
IScriptableNode setNamedItem(IScriptableNode arg);
IScriptableNode removeNamedItem(string name);
IScriptableNode item(ulong index);
IScriptableNode getNamedItemNS(string namespaceURI, string localName);
IScriptableNode setNamedItemNS(IScriptableNode arg);
IScriptableNode removeNamedItemNS(string namespaceURI, string localName);
ulong length { get; }
}
/// <summary>
/// IScriptableCharacterData
/// </summary>
public interface IScriptableCharacterData : IScriptableNode
{
string substringData(ulong offset, ulong count);
void appendData(string arg);
void insertData(ulong offset, string arg);
void deleteData(ulong offset, ulong count);
void replaceData(ulong offset, ulong count, string arg);
string data { get; set; }
ulong length { get; }
}
/// <summary>
/// IScriptableAttr
/// </summary>
public interface IScriptableAttr : IScriptableNode
{
string name { get; }
bool specified { get; }
string value { get; set; }
IScriptableElement ownerElement { get; }
}
/// <summary>
/// IScriptableElement
/// </summary>
public interface IScriptableElement : IScriptableNode
{
string getAttribute(string name);
void setAttribute(string name, string value);
void removeAttribute(string name);
IScriptableAttr getAttributeNode(string name);
IScriptableAttr setAttributeNode(IScriptableAttr newAttr);
IScriptableAttr removeAttributeNode(IScriptableAttr oldAttr);
IScriptableNodeList getElementsByTagName(string name);
string getAttributeNS(string namespaceURI, string localName);
void setAttributeNS(string namespaceURI, string qualifiedName, string value);
void removeAttributeNS(string namespaceURI, string localName);
IScriptableAttr getAttributeNodeNS(string namespaceURI, string localName);
IScriptableAttr setAttributeNodeNS(IScriptableAttr newAttr);
IScriptableNodeList getElementsByTagNameNS(string namespaceURI, string localName);
bool hasAttribute(string name);
bool hasAttributeNS(string namespaceURI, string localName);
string tagName { get; }
}
/// <summary>
/// IScriptableText
/// </summary>
public interface IScriptableText : IScriptableCharacterData
{
IScriptableText splitText(ulong offset);
}
/// <summary>
/// IScriptableComment
/// </summary>
public interface IScriptableComment : IScriptableCharacterData
{
}
/// <summary>
/// IScriptableCDataSection
/// </summary>
public interface IScriptableCDataSection : IScriptableText
{
}
/// <summary>
/// IScriptableDocumentType
/// </summary>
public interface IScriptableDocumentType : IScriptableNode
{
string name { get; }
IScriptableNamedNodeMap entities { get; }
IScriptableNamedNodeMap notations { get; }
string publicId { get; }
string systemId { get; }
string internalSubset { get; }
}
/// <summary>
/// IScriptableNotation
/// </summary>
public interface IScriptableNotation : IScriptableNode
{
string publicId { get; }
string systemId { get; }
}
/// <summary>
/// IScriptableEntity
/// </summary>
public interface IScriptableEntity : IScriptableNode
{
string publicId { get; }
string systemId { get; }
string notationName { get; }
}
/// <summary>
/// IScriptableEntityReference
/// </summary>
public interface IScriptableEntityReference : IScriptableNode
{
}
/// <summary>
/// IScriptableProcessingInstruction
/// </summary>
public interface IScriptableProcessingInstruction : IScriptableNode
{
string target { get; }
string data { get; set; }
}
/// <summary>
/// IScriptableDocumentFragment
/// </summary>
public interface IScriptableDocumentFragment : IScriptableNode
{
}
/// <summary>
/// IScriptableDocument
/// </summary>
public interface IScriptableDocument : IScriptableNode
{
IScriptableElement createElement(string tagName);
IScriptableDocumentFragment createDocumentFragment();
IScriptableText createTextNode(string data);
IScriptableComment createComment(string data);
IScriptableCDataSection createCDATASection(string data);
IScriptableProcessingInstruction createProcessingInstruction(string target, string data);
IScriptableAttr createAttribute(string name);
IScriptableEntityReference createEntityReference(string name);
IScriptableNodeList getElementsByTagName(string tagname);
IScriptableNode importNode(IScriptableNode importedNode, bool deep);
IScriptableElement createElementNS(string namespaceURI, string qualifiedName);
IScriptableAttr createAttributeNS(string namespaceURI, string qualifiedName);
IScriptableNodeList getElementsByTagNameNS(string namespaceURI, string localName);
IScriptableElement getElementById(string elementId);
IScriptableDocumentType doctype { get; }
IScriptableDomImplementation implementation { get; }
IScriptableElement documentElement { get; }
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.Cci.Contracts;
using System.Windows.Media;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using UtilitiesNamespace;
using System.Diagnostics.Contracts;
namespace Adornments {
public class MetadataContractAdornment : ContractAdornment {
public override LineTransformBehavior LineTransformBehavior {
get {
return _lineTransformBehavior;//TODO: REMOVE
}
}
LineTransformBehavior _lineTransformBehavior = LineTransformBehavior.Below;
public override bool IsPure {
get {
return base.IsPure;
}
set {
base.IsPure = value;
if (value && !IsCollapsedByUser)
_lineTransformBehavior = Adornments.LineTransformBehavior.BelowWithOneLineAbove;
}
}
public override bool IsClosedByUser {
get {
return base.IsClosedByUser;
}
set {
base.IsClosedByUser = value;
if (value)
_lineTransformBehavior = Adornments.LineTransformBehavior.None;
else if (IsPure)
_lineTransformBehavior = Adornments.LineTransformBehavior.BelowWithOneLineAbove;
else
_lineTransformBehavior = Adornments.LineTransformBehavior.Below;
}
}
public override int CollapsedRegionDepth {
get {
if ((this._options & AdornmentOptions.CollapseWithRegion) != 0)
{
return base.CollapsedRegionDepth;
}
else
{
return 0;
}
}
set {
if ((this._options & AdornmentOptions.CollapseWithRegion) != 0)
{
base.CollapsedRegionDepth = value;
}
else
{
base.CollapsedRegionDepth = 0;
}
}
}
public MetadataContractAdornment(ITrackingSpan span, VSTextProperties vsTextProperties, Logger logger, Action queueRefreshLineTransfomer, AdornmentOptions options = AdornmentOptions.None)
: base(span, vsTextProperties, logger, queueRefreshLineTransfomer, options)
{
Contract.Requires(span != null);
Contract.Requires(logger != null);
SizeChanged += OnSizeChanged;
}
void OnSizeChanged(object sender, SizeChangedEventArgs e) {
_logger.PublicEntry(() => {
RenderTransform = new TranslateTransform(0d, _vsTextProperties.LineHeight + e.NewSize.Height);
}, "OnSizeChanged");
}
//Plain Visual
protected override void SetVisual() {
base.SetVisual();
collapseButton.Visibility = Visibility.Collapsed;
Opacity = 0.5d;
//root.Margin = new Thickness(0, 0, 0, 8);
}
//Box Visual:
//protected override void SetVisual(Border root) {
// base.SetVisual(root);
// var backgroundBrush = new LinearGradientBrush();
// backgroundBrush.StartPoint = new Point(0.5, 0);
// backgroundBrush.EndPoint = new Point(0.5, 1);
// backgroundBrush.GradientStops.Add(new GradientStop(Color.FromArgb(125, 251, 251, 253), 0.134));
// backgroundBrush.GradientStops.Add(new GradientStop(Color.FromArgb(125, 228, 229, 240), 0.99));
// root.Background = backgroundBrush;
// root.Padding = new Thickness(2);
// root.Margin = new Thickness(0, 1, 0, 1);
// root.BorderBrush = Brushes.Gray;
// root.BorderThickness = new Thickness(1);
// Opacity = 0.5d;
// collapseButton.Visibility = System.Windows.Visibility.Collapsed;
//}
protected override void StartFormatContracts() {
if (IsPure) {
_purityElement.Visibility = System.Windows.Visibility.Visible;
}
if (true /*|| _hasNonPurityContracts*/) {//TODO: SOmething very fishy is happening here..
//Set first open curly brace
contractsGrid.RowDefinitions.Add(new RowDefinition());
var openCurly = new TextBlock(new Run("{"));
if (!_hasNonPurityContracts) openCurly.Visibility = System.Windows.Visibility.Collapsed;
openCurly.Foreground = _vsTextProperties.TextColor;
contractsGrid.Children.Add(openCurly);
Grid.SetColumn(openCurly, 0);
Grid.SetRow(openCurly, contractsGrid.RowDefinitions.Count - 1);
}
//if (IsPure) {
// contractsGrid.RowDefinitions.Add(new RowDefinition());
// var purityBlock = new TextBlock(new Run(_tabsAsSpaces + "Pure"));
// contractsGrid.Children.Add(purityBlock);
// Grid.SetRow(purityBlock, contractsGrid.RowDefinitions.Count - 1);
//}
base.StartFormatContracts();
}
protected override void EndFormatContracts() {
base.EndFormatContracts();
if (true /*|| _hasNonPurityContracts*/) {
//Set second open curly braces
contractsGrid.RowDefinitions.Add(new RowDefinition());
var closeCurly = new TextBlock(new Run("}"));
if (!_hasNonPurityContracts) closeCurly.Visibility = System.Windows.Visibility.Collapsed;
closeCurly.Foreground = _vsTextProperties.TextColor;
contractsGrid.Children.Add(closeCurly);
Grid.SetColumn(closeCurly, 0);
Grid.SetRow(closeCurly, contractsGrid.RowDefinitions.Count - 1);
}
}
protected override void FormatContract(string header, string content) {
content = SmartFormat(content);
//New Row
contractsGrid.RowDefinitions.Add(new RowDefinition());
//Stack Panel
var stackPanel = new StackPanel() { Orientation = System.Windows.Controls.Orientation.Horizontal };
contractsGrid.Children.Add(stackPanel);
Grid.SetRow(stackPanel, contractsGrid.RowDefinitions.Count - 1);
//Header
var headerBlock = new TextBlock(new Run(_tabsAsSpaces + header + " "));
headerBlock.Foreground = _vsTextProperties.KeywordColor;
//headerBlock.FontWeight = headerWeight;
//contractsgrid.children.add(headerblock);
//grid.setcolumn(headerblock, 0);
//grid.setRow(headerBlock, contractsGrid.RowDefinitions.Count - 1);
stackPanel.Children.Add(headerBlock);
//Content
var contentBlock = new TextBlock(new Run(content));
contentBlock.Foreground = _vsTextProperties.TextColor;
//contentBlock.FontWeight = runWeight;
//contractsGrid.Children.Add(contentBlock);
//Grid.SetColumn(contentBlock, 1);
//Grid.SetRow(contentBlock, contractsGrid.RowDefinitions.Count - 1);
stackPanel.Children.Add(contentBlock);
}
protected override void OnExpanded() {
base.OnExpanded();
if (IsPure) {
_purityElement.Visibility = Visibility.Visible;
_lineTransformBehavior = Adornments.LineTransformBehavior.BelowWithOneLineAbove;
}
Opacity = 1.0;//0.8;
//root.Effect = dropShadowEffect;
}
protected override void OnCollapsed() {
base.OnCollapsed();
if (IsPure) {
_purityElement.Visibility = Visibility.Collapsed;
_lineTransformBehavior = Adornments.LineTransformBehavior.Below;
}
if (!IsFocusedOnAdornment)
Opacity = 0.5d;
//root.Effect = null;
}
protected override void OnFocused() {
base.OnFocused();
Opacity = 1.0d;
//if(IsCollapsedByUser)
// Collapse_Click(null, null);
}
protected override void OnUnfocused() {
base.OnUnfocused();
//if(IsCollapsedByUser)
Opacity = 0.5d;
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Security;
using Xunit;
namespace System.Tests
{
public class SetEnvironmentVariable
{
private const string NullString = "\u0000";
internal static bool IsSupportedTarget(EnvironmentVariableTarget target)
{
return target == EnvironmentVariableTarget.Process || (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !PlatformDetection.IsUap);
}
[Fact]
public void NullVariableThrowsArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => Environment.SetEnvironmentVariable(null, "test"));
}
[Fact]
public void IncorrectVariableThrowsArgument()
{
AssertExtensions.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable(string.Empty, "test"));
AssertExtensions.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable(NullString, "test"));
AssertExtensions.Throws<ArgumentException>("variable", null, () => Environment.SetEnvironmentVariable("Variable=Something", "test"));
}
private static void ExecuteAgainstTarget(
EnvironmentVariableTarget target,
Action action,
Action cleanUp = null)
{
bool shouldCleanUp = cleanUp != null;
try
{
action();
}
catch (SecurityException)
{
shouldCleanUp = false;
Assert.True(target == EnvironmentVariableTarget.Machine || (target == EnvironmentVariableTarget.User && PlatformDetection.IsUap),
"only machine target, or user when in uap, should have access issues");
Assert.True(PlatformDetection.IsWindows, "and it should be Windows");
Assert.False(PlatformDetection.IsWindowsAndElevated, "and we shouldn't be elevated");
}
finally
{
if (shouldCleanUp)
cleanUp();
}
}
[Theory]
[MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))]
public void Default(EnvironmentVariableTarget target)
{
string varName = $"Test_SetEnvironmentVariable_Default ({target})";
const string value = "true";
ExecuteAgainstTarget(target,
() =>
{
Environment.SetEnvironmentVariable(varName, value, target);
Assert.Equal(IsSupportedTarget(target) ? value : null,
Environment.GetEnvironmentVariable(varName, target));
},
() =>
{
// Clear the test variable
Environment.SetEnvironmentVariable(varName, null, target);
});
}
[Theory]
[MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))]
public void ModifyEnvironmentVariable(EnvironmentVariableTarget target)
{
string varName = $"Test_ModifyEnvironmentVariable ({target})";
const string value = "false";
ExecuteAgainstTarget(target,
() =>
{
// First set the value to something and then change it and ensure that it gets modified.
Environment.SetEnvironmentVariable(varName, "true", target);
Environment.SetEnvironmentVariable(varName, value, target);
// Check whether the variable exists.
Assert.Equal(IsSupportedTarget(target) ? value : null, Environment.GetEnvironmentVariable(varName, target));
},
() =>
{
// Clear the test variable
Environment.SetEnvironmentVariable(varName, null, target);
});
}
[Theory]
[MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))]
public void ModifyEnvironmentVariable_AndEnumerate(EnvironmentVariableTarget target)
{
string varName = $"Test_ModifyEnvironmentVariable_AndEnumerate ({target})";
const string value = "false";
ExecuteAgainstTarget(target,
() =>
{
// First set the value to something and then change it and ensure that it gets modified.
Environment.SetEnvironmentVariable(varName, "true", target);
// Enumerate to validate our first value to ensure we can still set after enumerating
IDictionary variables = Environment.GetEnvironmentVariables(target);
if (IsSupportedTarget(target))
{
Assert.True(variables.Contains(varName), "has the key we entered");
Assert.Equal("true", variables[varName]);
}
Environment.SetEnvironmentVariable(varName, value, target);
// Check whether the variable exists.
Assert.Equal(IsSupportedTarget(target) ? value : null, Environment.GetEnvironmentVariable(varName, target));
},
() =>
{
// Clear the test variable
Environment.SetEnvironmentVariable(varName, null, target);
});
}
[Theory]
[MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))]
public void DeleteEnvironmentVariable(EnvironmentVariableTarget target)
{
string varName = $"Test_DeleteEnvironmentVariable ({target})";
const string value = "false";
ExecuteAgainstTarget(target,
() =>
{
// First set the value to something and then ensure that it can be deleted.
Environment.SetEnvironmentVariable(varName, value);
Environment.SetEnvironmentVariable(varName, string.Empty);
Assert.Equal(null, Environment.GetEnvironmentVariable(varName));
Environment.SetEnvironmentVariable(varName, value);
Environment.SetEnvironmentVariable(varName, null);
Assert.Equal(null, Environment.GetEnvironmentVariable(varName));
Environment.SetEnvironmentVariable(varName, value);
Environment.SetEnvironmentVariable(varName, NullString);
Assert.Equal(null, Environment.GetEnvironmentVariable(varName));
});
}
[Fact]
public void DeleteEnvironmentVariableNonInitialNullInName()
{
const string varNamePrefix = "Begin_DeleteEnvironmentVariableNonInitialNullInName";
const string varNameSuffix = "End_DeleteEnvironmentVariableNonInitialNullInName";
const string varName = varNamePrefix + NullString + varNameSuffix;
const string value = "false";
try
{
Environment.SetEnvironmentVariable(varName, value);
Environment.SetEnvironmentVariable(varName, null);
Assert.Equal(Environment.GetEnvironmentVariable(varName), null);
Assert.Equal(Environment.GetEnvironmentVariable(varNamePrefix), null);
}
finally
{
// Clear the test variable
Environment.SetEnvironmentVariable(varName, null);
}
}
[Fact]
public void DeleteEnvironmentVariableInitialNullInValue()
{
const string value = NullString + "test";
const string varName = "DeleteEnvironmentVariableInitialNullInValue";
try
{
Environment.SetEnvironmentVariable(varName, value);
Assert.Equal(null, Environment.GetEnvironmentVariable(varName));
}
finally
{
Environment.SetEnvironmentVariable(varName, String.Empty);
}
}
[Fact]
public void NonInitialNullCharacterInVariableName()
{
const string varNamePrefix = "NonInitialNullCharacterInVariableName_Begin";
const string varNameSuffix = "NonInitialNullCharacterInVariableName_End";
const string varName = varNamePrefix + NullString + varNameSuffix;
const string value = "true";
try
{
Environment.SetEnvironmentVariable(varName, value);
Assert.Equal(value, Environment.GetEnvironmentVariable(varName));
Assert.Equal(value, Environment.GetEnvironmentVariable(varNamePrefix));
}
finally
{
Environment.SetEnvironmentVariable(varName, String.Empty);
Environment.SetEnvironmentVariable(varNamePrefix, String.Empty);
}
}
[Fact]
public void NonInitialNullCharacterInValue()
{
const string varName = "Test_TestNonInitialZeroCharacterInValue";
const string valuePrefix = "Begin";
const string valueSuffix = "End";
const string value = valuePrefix + NullString + valueSuffix;
try
{
Environment.SetEnvironmentVariable(varName, value);
Assert.Equal(valuePrefix, Environment.GetEnvironmentVariable(varName));
}
finally
{
Environment.SetEnvironmentVariable(varName, String.Empty);
}
}
[Fact]
public void DeleteNonExistentEnvironmentVariable()
{
const string varName = "Test_TestDeletingNonExistingEnvironmentVariable";
if (Environment.GetEnvironmentVariable(varName) != null)
{
Environment.SetEnvironmentVariable(varName, null);
}
Environment.SetEnvironmentVariable("TestDeletingNonExistingEnvironmentVariable", String.Empty);
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetAzureTargetReadPreferencesSpectraS3Request : Ds3Request
{
private string _bucketId;
public string BucketId
{
get { return _bucketId; }
set { WithBucketId(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private TargetReadPreferenceType? _readPreference;
public TargetReadPreferenceType? ReadPreference
{
get { return _readPreference; }
set { WithReadPreference(value); }
}
private string _targetId;
public string TargetId
{
get { return _targetId; }
set { WithTargetId(value); }
}
public GetAzureTargetReadPreferencesSpectraS3Request WithBucketId(Guid? bucketId)
{
this._bucketId = bucketId.ToString();
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId.ToString());
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetAzureTargetReadPreferencesSpectraS3Request WithBucketId(string bucketId)
{
this._bucketId = bucketId;
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId);
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetAzureTargetReadPreferencesSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetAzureTargetReadPreferencesSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetAzureTargetReadPreferencesSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetAzureTargetReadPreferencesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetAzureTargetReadPreferencesSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetAzureTargetReadPreferencesSpectraS3Request WithReadPreference(TargetReadPreferenceType? readPreference)
{
this._readPreference = readPreference;
if (readPreference != null)
{
this.QueryParams.Add("read_preference", readPreference.ToString());
}
else
{
this.QueryParams.Remove("read_preference");
}
return this;
}
public GetAzureTargetReadPreferencesSpectraS3Request WithTargetId(Guid? targetId)
{
this._targetId = targetId.ToString();
if (targetId != null)
{
this.QueryParams.Add("target_id", targetId.ToString());
}
else
{
this.QueryParams.Remove("target_id");
}
return this;
}
public GetAzureTargetReadPreferencesSpectraS3Request WithTargetId(string targetId)
{
this._targetId = targetId;
if (targetId != null)
{
this.QueryParams.Add("target_id", targetId);
}
else
{
this.QueryParams.Remove("target_id");
}
return this;
}
public GetAzureTargetReadPreferencesSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/azure_target_read_preference";
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: The core libraries for the DotSpatial project.
//
// ********************************************************************************************************
// 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 2/25/2008 8:49:44 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace DotSpatial.Symbology
{
/// <summary>
/// Global has some basic methods that may be useful in lots of places.
/// </summary>
public static class SymbologyGlobal
{
/// <summary>
/// An instance of Random that is created when needed and sits around so we don't keep creating new ones.
/// </summary>
private static readonly Random _defaultRandom = new Random();
/// <summary>
/// Gets a cool Highlight brush for highlighting things
/// </summary>
/// <param name="box">The rectangle in the box</param>
/// <param name="selectionHighlight">The color to use for the higlight</param>
/// <returns></returns>
public static Brush HighlightBrush(Rectangle box, Color selectionHighlight)
{
float med = selectionHighlight.GetBrightness();
float bright = med + 0.05f;
if (bright > 1f) bright = 1f;
float dark = med - 0.05f;
if (dark < 0f) dark = 0f;
Color brtCol = ColorFromHsl(selectionHighlight.GetHue(), selectionHighlight.GetSaturation(), bright);
Color drkCol = ColorFromHsl(selectionHighlight.GetHue(), selectionHighlight.GetSaturation(), dark);
return new LinearGradientBrush(box, brtCol, drkCol, LinearGradientMode.Vertical);
}
/// <summary>
/// Draws a rectangle with ever so slightly rounded edges. Good for selection borders.
/// </summary>
/// <param name="g">The Graphics object</param>
/// <param name="pen">The pen to draw with</param>
/// <param name="rect">The rectangle to draw to.</param>
public static void DrawRoundedRectangle(Graphics g, Pen pen, Rectangle rect)
{
int l = rect.Left;
int r = rect.Right;
int t = rect.Top;
int b = rect.Bottom;
g.DrawLine(pen, l + 1, t, r - 1, t);
g.DrawLine(pen, l + 1, b, r - 1, b);
g.DrawLine(pen, l, t + 1, l, b - 1);
g.DrawLine(pen, r, t + 1, r, b - 1);
g.DrawLine(pen, l, t + 2, l + 2, t);
g.DrawLine(pen, r - 2, t, r, t + 2);
g.DrawLine(pen, l, b - 2, l + 2, b);
g.DrawLine(pen, r, b - 2, r - 2, b);
}
/// <summary>
/// Obtains a system.Drawing.Rectangle based on the two points, using them as
/// opposite extremes for the rectangle.
/// </summary>
/// <param name="a">one corner point of the rectangle.</param>
/// <param name="b">The opposing corner of the rectangle.</param>
/// <returns>A System.Draing.Rectangle</returns>
public static Rectangle GetRectangle(Point a, Point b)
{
int x = Math.Min(a.X, b.X);
int y = Math.Min(a.Y, b.Y);
int w = Math.Abs(a.X - b.X);
int h = Math.Abs(a.Y - b.Y);
return new Rectangle(x, y, w, h);
}
/// <summary>
/// Returns a completely random opaque color.
/// </summary>
/// <returns>A random color.</returns>
public static Color RandomColor()
{
return Color.FromArgb(_defaultRandom.Next(0, 255), _defaultRandom.Next(0, 255), _defaultRandom.Next(0, 255));
}
/// <summary>
/// This allows the creation of a transparent color with the specified opacity.
/// </summary>
/// <param name="opacity">A float ranging from 0 for transparent to 1 for opaque</param>
/// <returns>A Color</returns>
public static Color RandomTranslucent(float opacity)
{
int alpha = Convert.ToInt32(opacity * 255);
if (alpha > 255) alpha = 255;
if (alpha < 0) alpha = 0;
return Color.FromArgb(alpha, _defaultRandom.Next(0, 255), _defaultRandom.Next(0, 255), _defaultRandom.Next(0, 255));
}
/// <summary>
/// This allows the creation of a transparent color with the specified opacity.
/// </summary>
/// <param name="opacity">A float ranging from 0 for transparent to 1 for opaque</param>
/// <returns>A Color</returns>
public static Color RandomLightColor(float opacity)
{
int alpha = Convert.ToInt32(opacity * 255);
if (alpha > 255) alpha = 255;
if (alpha < 0) alpha = 0;
return Color.FromArgb(alpha, ColorFromHsl(_defaultRandom.Next(0, 360), ((double)_defaultRandom.Next(0, 255) / 256), ((double)_defaultRandom.Next(123, 255) / 256)));
}
/// <summary>
/// This allows the creation of a transparent color with the specified opacity.
/// </summary>
/// <param name="opacity">A float ranging from 0 for transparent to 1 for opaque</param>
/// <returns>A Color</returns>
public static Color RandomDarkColor(float opacity)
{
int alpha = Convert.ToInt32(opacity * 255);
if (alpha > 255) alpha = 255;
if (alpha < 0) alpha = 0;
return Color.FromArgb(alpha, ColorFromHsl(_defaultRandom.Next(0, 360), ((double)_defaultRandom.Next(0, 255) / 256), ((double)_defaultRandom.Next(0, 123) / 256)));
}
/// <summary>
/// Converts a colour from HSL to RGB
/// </summary>
/// <remarks>Adapted from the algoritm in Foley and Van-Dam</remarks>
/// <param name="hue">A double representing degrees ranging from 0 to 360 and is equal to the GetHue() on a Color structure.</param>
/// <param name="saturation">A double value ranging from 0 to 1, where 0 is gray and 1 is fully saturated with color.</param>
/// <param name="brightness">A double value ranging from 0 to 1, where 0 is black and 1 is white.</param>
/// <returns>A Color structure with the equivalent hue saturation and brightness</returns>
public static Color ColorFromHsl(double hue, double saturation, double brightness)
{
double normalizedHue = hue / 360;
double red, green, blue;
if (brightness == 0)
{
red = green = blue = 0;
}
else
{
if (saturation == 0)
{
red = green = blue = brightness;
}
else
{
double temp2;
if (brightness <= 0.5)
{
temp2 = brightness * (1.0 + saturation);
}
else
{
temp2 = brightness + saturation - (brightness * saturation);
}
double temp1 = 2.0 * brightness - temp2;
double[] temp3 = new[] { normalizedHue + 1.0 / 3.0, normalizedHue, normalizedHue - 1.0 / 3.0 };
double[] color = new double[] { 0, 0, 0 };
for (int i = 0; i < 3; i++)
{
if (temp3[i] < 0) temp3[i] += 1.0;
if (temp3[i] > 1) temp3[i] -= 1.0;
if (6.0 * temp3[i] < 1.0)
{
color[i] = temp1 + (temp2 - temp1) * temp3[i] * 6.0;
}
else if (2.0 * temp3[i] < 1.0)
{
color[i] = temp2;
}
else if (3.0 * temp3[i] < 2.0)
{
color[i] = (temp1 + (temp2 - temp1) * ((2.0 / 3.0) - temp3[i]) * 6.0);
}
else
{
color[i] = temp1;
}
}
red = color[0];
green = color[1];
blue = color[2];
}
}
if (red > 1) red = 1;
if (red < 0) red = 0;
if (green > 1) green = 1;
if (green < 0) green = 0;
if (blue > 1) blue = 1;
if (blue < 0) blue = 0;
return Color.FromArgb((int)(255 * red), (int)(255 * green), (int)(255 * blue));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using RestfullService.Areas.HelpPage.ModelDescriptions;
using RestfullService.Areas.HelpPage.Models;
namespace RestfullService.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using UnityEditor;
namespace Pathfinding {
/** Simple GUI utility functions */
public static class GUIUtilityx {
private static Color prevCol;
public static void SetColor (Color col) {
prevCol = GUI.color;
GUI.color = col;
}
public static void ResetColor () {
GUI.color = prevCol;
}
}
/** Handles fading effects and also some custom GUI functions such as LayerMaskField.
* \warning The code is not pretty.
*/
public class EditorGUILayoutx {
Dictionary<string, FadeArea> fadeAreas;
/** Global info about which editor is currently active.
* \todo Ugly, rewrite this class at some point...
*/
public static Editor editor;
public static GUIStyle defaultAreaStyle;
public static GUIStyle defaultLabelStyle;
const float speed = 8;
readonly bool fade = true;
public static bool fancyEffects = true;
Stack<FadeArea> fadeAreaStack;
static Dictionary<int, string[]> layerNames = new Dictionary<int, string[]>();
static long lastUpdateTick;
/** Tag names and an additional 'Edit Tags...' entry.
* Used for SingleTagField
*/
static string[] tagNamesAndEditTagsButton;
/** Last tiem tagNamesAndEditTagsButton was updated.
* Uses EditorApplication.timeSinceStartup
*/
static double timeLastUpdatedTagNames;
public void RemoveID (string id) {
if (fadeAreas == null) {
return;
}
fadeAreas.Remove(id);
}
public bool DrawID (string id) {
return fadeAreas != null && fadeAreas[id].Show();
}
public class FadeArea {
public Rect currentRect;
public Rect lastRect;
public float value;
public float lastUpdate;
/** Is this area open.
* This is not the same as if any contents are visible, use #Show for that.
*/
public bool open;
public Color preFadeColor;
/** Update the visibility in Layout to avoid complications with different events not drawing the same thing */
private bool visibleInLayout;
public void Switch () {
lastRect = currentRect;
}
public FadeArea (bool open) {
value = open ? 1 : 0;
}
/** Should anything inside this FadeArea be drawn.
* Should be called every frame ( in all events ) for best results.
*/
public bool Show () {
if (Event.current.type == EventType.Layout) {
visibleInLayout = open || value > 0F;
}
return visibleInLayout;
}
public static implicit operator bool (FadeArea o) {
return o.open;
}
}
/** Make sure the stack is cleared at the start of a frame */
public void ClearFadeAreaStack () {
if (fadeAreaStack != null) fadeAreaStack.Clear();
}
public FadeArea BeginFadeArea (bool open, string label, string id) {
return BeginFadeArea(open, label, id, defaultAreaStyle);
}
public FadeArea BeginFadeArea (bool open, string label, string id, GUIStyle areaStyle) {
return BeginFadeArea(open, label, id, areaStyle, defaultLabelStyle);
}
public FadeArea BeginFadeArea (bool open, string label, string id, GUIStyle areaStyle, GUIStyle labelStyle) {
Color tmp1 = GUI.color;
FadeArea fadeArea = BeginFadeArea(open, id, 20, areaStyle);
Color tmp2 = GUI.color;
GUI.color = tmp1;
if (label != "") {
if (GUILayout.Button(label, labelStyle)) {
fadeArea.open = !fadeArea.open;
editor.Repaint();
}
}
GUI.color = tmp2;
return fadeArea;
}
public FadeArea BeginFadeArea (bool open, string id) {
return BeginFadeArea(open, id, 0);
}
public FadeArea BeginFadeArea (bool open, string id, float minHeight) {
return BeginFadeArea(open, id, minHeight, GUIStyle.none);
}
public FadeArea BeginFadeArea (bool open, string id, float minHeight, GUIStyle areaStyle) {
if (editor == null) {
Debug.LogError("You need to set the 'EditorGUIx.editor' variable before calling this function");
return null;
}
if (fadeAreaStack == null) {
fadeAreaStack = new Stack<FadeArea>();
}
if (fadeAreas == null) {
fadeAreas = new Dictionary<string, FadeArea>();
}
FadeArea fadeArea;
if (!fadeAreas.TryGetValue(id, out fadeArea)) {
fadeArea = new FadeArea(open);
fadeAreas.Add(id, fadeArea);
}
fadeAreaStack.Push(fadeArea);
fadeArea.open = open;
// Make sure the area fills the full width
areaStyle.stretchWidth = true;
Rect lastRect = fadeArea.lastRect;
if (!fancyEffects) {
fadeArea.value = open ? 1F : 0F;
lastRect.height -= minHeight;
lastRect.height = open ? lastRect.height : 0;
lastRect.height += minHeight;
} else {
lastRect.height = lastRect.height < minHeight ? minHeight : lastRect.height;
lastRect.height -= minHeight;
float faded = Hermite(0F, 1F, fadeArea.value);
lastRect.height *= faded;
lastRect.height += minHeight;
lastRect.height = Mathf.Round(lastRect.height);
}
Rect gotLastRect = GUILayoutUtility.GetRect(new GUIContent(), areaStyle, GUILayout.Height(lastRect.height));
//The clipping area, also drawing background
GUILayout.BeginArea(lastRect, areaStyle);
Rect newRect = EditorGUILayout.BeginVertical();
if (Event.current.type == EventType.Repaint || Event.current.type == EventType.ScrollWheel) {
newRect.x = gotLastRect.x;
newRect.y = gotLastRect.y;
newRect.width = gotLastRect.width;
newRect.height += areaStyle.padding.top+ areaStyle.padding.bottom;
fadeArea.currentRect = newRect;
if (fadeArea.lastRect != newRect) {
//@Fix - duplicate
//fadeArea.lastUpdate = Time.realtimeSinceStartup;
editor.Repaint();
}
fadeArea.Switch();
}
if (Event.current.type == EventType.Repaint) {
float value = fadeArea.value;
float targetValue = open ? 1F : 0F;
float newRectHeight = fadeArea.lastRect.height;
float deltaHeight = 400F / newRectHeight;
float deltaTime = Mathf.Clamp(Time.realtimeSinceStartup-fadeAreas[id].lastUpdate, 0.00001F, 0.05F);
deltaTime *= Mathf.Lerp(deltaHeight*deltaHeight*0.01F, 0.8F, 0.9F);
fadeAreas[id].lastUpdate = Time.realtimeSinceStartup;
if (Mathf.Abs(targetValue-value) > 0.001F) {
float time = Mathf.Clamp01(deltaTime*speed);
value += time*Mathf.Sign(targetValue-value);
editor.Repaint();
} else {
value = Mathf.Round(value);
}
fadeArea.value = Mathf.Clamp01(value);
}
if (fade) {
Color c = GUI.color;
fadeArea.preFadeColor = c;
c.a *= fadeArea.value;
GUI.color = c;
}
fadeArea.open = open;
return fadeArea;
}
public void EndFadeArea () {
if (fadeAreaStack.Count <= 0) {
Debug.LogError("You are popping more Fade Areas than you are pushing, make sure they are balanced");
return;
}
FadeArea fadeArea = fadeAreaStack.Pop();
EditorGUILayout.EndVertical();
GUILayout.EndArea();
if (fade) {
GUI.color = fadeArea.preFadeColor;
}
}
/** Returns width of current editor indent.
* Unity seems to use 13+6*EditorGUI.indentLevel in U3
* and 15*indent - (indent > 1 ? 2 : 0) or something like that in U4
*/
static int IndentWidth () {
//Works well for indent levels 0,1,2 at least
return 15*EditorGUI.indentLevel - (EditorGUI.indentLevel > 1 ? 2 : 0);
}
/** Begin horizontal indent for the next control.
* Fake "real" indent when using EditorGUIUtility.LookLikeControls.\n
* Forumula used is 13+6*EditorGUI.indentLevel
*/
public static void BeginIndent () {
GUILayout.BeginHorizontal();
GUILayout.Space(IndentWidth());
}
/** End indent.
* Actually just a EndHorizontal call.
* \see BeginIndent
*/
public static void EndIndent () {
GUILayout.EndHorizontal();
}
public static int TagField (string label, int value) {
// Make sure the tagNamesAndEditTagsButton is relatively up to date
if (tagNamesAndEditTagsButton == null || EditorApplication.timeSinceStartup - timeLastUpdatedTagNames > 1) {
timeLastUpdatedTagNames = EditorApplication.timeSinceStartup;
var tagNames = AstarPath.FindTagNames();
tagNamesAndEditTagsButton = new string[tagNames.Length+1];
tagNames.CopyTo(tagNamesAndEditTagsButton, 0);
tagNamesAndEditTagsButton[tagNamesAndEditTagsButton.Length-1] = "Edit Tags...";
}
// Tags are between 0 and 31
value = Mathf.Clamp(value, 0, 31);
var newValue = EditorGUILayout.IntPopup(label, value, tagNamesAndEditTagsButton, new [] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, -1 });
// Last element corresponds to the 'Edit Tags...' entry. Open the tag editor
if (newValue == -1) {
AstarPathEditor.EditTags();
} else {
value = newValue;
}
return value;
}
public static void TagMaskField (GUIContent label, int value, System.Action<int> callback) {
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(label, EditorStyles.layerMaskField);
string[] tagNames = AstarPath.FindTagNames();
string text;
if (value == 0) {
text = "Nothing";
} else if (value == ~0) {
text = "Everything";
} else {
text = "";
for (int i = 0; i < 32; i++) {
if (((value >> i) & 0x1) != 0) {
// Add spacing between words
if (text.Length > 0) text += ", ";
text += tagNames[i];
// Too long, just give up
if (text.Length > 40) {
text = "Mixed...";
break;
}
}
}
}
if (GUILayout.Button(text, EditorStyles.layerMaskField, GUILayout.ExpandWidth(true))) {
GenericMenu.MenuFunction2 wrappedCallback = obj => callback((int)obj);
var menu = new GenericMenu();
menu.AddItem(new GUIContent("Everything"), value == ~0, wrappedCallback, ~0);
menu.AddItem(new GUIContent("Nothing"), value == 0, wrappedCallback, 0);
for (int i = 0; i < tagNames.Length; i++) {
bool on = (value >> i & 1) != 0;
int result = on ? value & ~(1 << i) : value | 1<<i;
menu.AddItem(new GUIContent(tagNames[i]), on, wrappedCallback, result);
}
// Shortcut to open the tag editor
menu.AddItem(new GUIContent("Edit Tag Names..."), false, AstarPathEditor.EditTags);
menu.ShowAsContext();
Event.current.Use();
}
GUILayout.EndHorizontal();
}
public static int UpDownArrows (GUIContent label, int value, GUIStyle labelStyle, GUIStyle upArrow, GUIStyle downArrow) {
GUILayout.BeginHorizontal();
GUILayout.Space(EditorGUI.indentLevel*10);
GUILayout.Label(label, labelStyle, GUILayout.Width(170));
if (downArrow == null || upArrow == null) {
upArrow = GUI.skin.FindStyle("Button");
downArrow = upArrow;
}
if (GUILayout.Button("", upArrow, GUILayout.Width(16), GUILayout.Height(12))) {
value++;
}
if (GUILayout.Button("", downArrow, GUILayout.Width(16), GUILayout.Height(12))) {
value--;
}
GUILayout.Space(100);
GUILayout.EndHorizontal();
return value;
}
public static bool UnityTagMaskList (GUIContent label, bool foldout, List<string> tagMask) {
if (tagMask == null) throw new System.ArgumentNullException("tagMask");
if (EditorGUILayout.Foldout(foldout, label)) {
EditorGUI.indentLevel++;
GUILayout.BeginVertical();
for (int i = 0; i < tagMask.Count; i++) {
tagMask[i] = EditorGUILayout.TagField(tagMask[i]);
}
GUILayout.BeginHorizontal();
if (GUILayout.Button("Add Tag")) tagMask.Add("Untagged");
EditorGUI.BeginDisabledGroup(tagMask.Count == 0);
if (GUILayout.Button("Remove Last")) tagMask.RemoveAt(tagMask.Count-1);
EditorGUI.EndDisabledGroup();
GUILayout.EndHorizontal();
GUILayout.EndVertical();
EditorGUI.indentLevel--;
return true;
}
return false;
}
/** Displays a LayerMask field.
* \param label Label to display
* \param selected Current LayerMask
* \note Unity 3.5 and up will use the EditorGUILayout.MaskField instead of a custom written one.
*/
public static LayerMask LayerMaskField (string label, LayerMask selected) {
if (Event.current.type == EventType.Layout && System.DateTime.UtcNow.Ticks - lastUpdateTick > 10000000L) {
layerNames.Clear();
lastUpdateTick = System.DateTime.UtcNow.Ticks;
}
string[] currentLayerNames;
if (!layerNames.TryGetValue(selected.value, out currentLayerNames)) {
var layers = Pathfinding.Util.ListPool<string>.Claim();
int emptyLayers = 0;
for (int i = 0; i < 32; i++) {
string layerName = LayerMask.LayerToName(i);
if (layerName != "") {
for (; emptyLayers > 0; emptyLayers--) layers.Add("Layer "+(i-emptyLayers));
layers.Add(layerName);
} else {
emptyLayers++;
if (((selected.value >> i) & 1) != 0 && selected.value != -1) {
for (; emptyLayers > 0; emptyLayers--) layers.Add("Layer "+(i+1-emptyLayers));
}
}
}
currentLayerNames = layerNames[selected.value] = layers.ToArray();
Pathfinding.Util.ListPool<string>.Release(layers);
}
selected.value = EditorGUILayout.MaskField(label, selected.value, currentLayerNames);
return selected;
}
public static float Hermite (float start, float end, float value) {
return Mathf.Lerp(start, end, value * value * (3.0f - 2.0f * value));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace DataStoreService.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// --------------------------------------------------------------------------------------------
// <copyright from='2011' to='2011' company='SIL International'>
// Copyright (c) 2011, SIL International. All Rights Reserved.
//
// Distributable under the terms of either the Common Public License or the
// GNU Lesser General Public License, as specified in the LICENSING.txt file.
// </copyright>
// --------------------------------------------------------------------------------------------
#if __MonoCS__
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using X11.XKlavier;
using Palaso.Reporting;
using Palaso.UI.WindowsForms.Keyboarding.Interfaces;
using Palaso.UI.WindowsForms.Keyboarding.InternalInterfaces;
using Palaso.UI.WindowsForms.Keyboarding.Types;
using Palaso.WritingSystems;
namespace Palaso.UI.WindowsForms.Keyboarding.Linux
{
/// <summary>
/// Class for handling xkb keyboards on Linux
/// </summary>
public class XkbKeyboardAdaptor: IKeyboardAdaptor
{
protected List<IKeyboardErrorDescription> m_BadLocales;
private IXklEngine m_engine;
public XkbKeyboardAdaptor(): this(new XklEngine())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Palaso.UI.WindowsForms.Keyboarding.Linux.XkbKeyboardAdaptor"/> class.
/// This overload is used in unit tests.
/// </summary>
public XkbKeyboardAdaptor(IXklEngine engine)
{
m_engine = engine;
}
private string GetLanguageCountry(Icu.Locale locale)
{
if (string.IsNullOrEmpty(locale.Country) && string.IsNullOrEmpty(locale.Language))
return string.Empty;
return locale.Language + "_" + locale.Country;
}
/// <summary>
/// Gets the IcuLocales by language and country. The 3-letter language and country codes
/// are concatenated with an underscore in between, e.g. fra_BEL
/// </summary>
private Dictionary<string, Icu.Locale> IcuLocalesByLanguageCountry
{
get
{
var localesByLanguageCountry = new Dictionary<string, Icu.Locale>();
foreach (var locale in Icu.Locale.AvailableLocales)
{
var languageCountry = GetLanguageCountry(locale);
if (string.IsNullOrEmpty(languageCountry) ||
localesByLanguageCountry.ContainsKey(languageCountry))
{
continue;
}
localesByLanguageCountry[languageCountry] = locale;
}
return localesByLanguageCountry;
}
}
private static string GetDescription(XklConfigRegistry.LayoutDescription layout)
{
return string.Format("{0} - {1} ({2})", layout.Description, layout.Language, layout.Country);
}
protected virtual void InitLocales()
{
if (m_BadLocales != null)
return;
ReinitLocales();
}
private void ReinitLocales()
{
m_BadLocales = new List<IKeyboardErrorDescription>();
var configRegistry = XklConfigRegistry.Create(m_engine);
var layouts = configRegistry.Layouts;
for (int iGroup = 0; iGroup < m_engine.GroupNames.Length; iGroup++)
{
// a group in a xkb keyboard is a keyboard layout. This can be used with
// multiple languages - which language is ambigious. Here we just add all
// of them.
// m_engine.GroupNames are not localized, but the layouts are. Before we try
// to compare them we better localize the group name as well, or we won't find
// much (FWNX-1388)
var groupName = m_engine.LocalizedGroupNames[iGroup];
List<XklConfigRegistry.LayoutDescription> layoutList;
if (!layouts.TryGetValue(groupName, out layoutList))
{
// No language in layouts uses the groupName keyboard layout.
m_BadLocales.Add(new KeyboardErrorDescription(groupName));
Console.WriteLine("WARNING: Couldn't find layout for {0}.", groupName);
Logger.WriteEvent("WARNING: Couldn't find layout for {0}.", groupName);
continue;
}
for (int iLayout = 0; iLayout < layoutList.Count; iLayout++)
{
var layout = layoutList[iLayout];
AddKeyboardForLayout(layout, iGroup);
}
}
}
private void AddKeyboardForLayout(XklConfigRegistry.LayoutDescription layout, int iGroup)
{
AddKeyboardForLayout(layout, iGroup, this);
}
internal void AddKeyboardForLayout(XklConfigRegistry.LayoutDescription layout, int iGroup, IKeyboardAdaptor engine)
{
var description = GetDescription(layout);
CultureInfo culture = null;
try
{
culture = new CultureInfo(layout.LocaleId);
}
catch (ArgumentException)
{
// This can happen if the locale is not supported.
// TODO: fix mono's list of supported locales. Doesn't support e.g. de-BE.
// See mono/tools/locale-builder.
}
var inputLanguage = new InputLanguageWrapper(culture, IntPtr.Zero, layout.Language);
var keyboard = new XkbKeyboardDescription(description, layout.LayoutId, layout.LocaleId,
inputLanguage, engine, iGroup);
KeyboardController.Manager.RegisterKeyboard(keyboard);
}
internal IXklEngine XklEngine
{
get { return m_engine; }
}
public List<IKeyboardErrorDescription> ErrorKeyboards
{
get
{
InitLocales();
return m_BadLocales;
}
}
public void Initialize()
{
InitLocales();
}
public void UpdateAvailableKeyboards()
{
ReinitLocales();
}
public void Close()
{
m_engine.Close();
m_engine = null;
}
public bool ActivateKeyboard(IKeyboardDefinition keyboard)
{
Debug.Assert(keyboard is KeyboardDescription);
Debug.Assert(((KeyboardDescription)keyboard).Engine == this);
Debug.Assert(keyboard is XkbKeyboardDescription);
var xkbKeyboard = keyboard as XkbKeyboardDescription;
if (xkbKeyboard == null)
throw new ArgumentException();
if (xkbKeyboard.GroupIndex >= 0)
{
m_engine.SetGroup(xkbKeyboard.GroupIndex);
}
return true;
}
public void DeactivateKeyboard(IKeyboardDefinition keyboard)
{
}
public IKeyboardDefinition GetKeyboardForInputLanguage(IInputLanguage inputLanguage)
{
throw new NotImplementedException();
}
/// <summary>
/// The type of keyboards this adaptor handles: system or other (like Keyman, ibus...)
/// </summary>
public KeyboardType Type
{
get { return KeyboardType.System; }
}
/// <summary>
/// Gets the default keyboard of the system.
/// </summary>
/// <remarks>
/// For Xkb the default keyboard has GroupIndex set to zero.
/// Wasta/Cinnamon keyboarding doesn't always have the system keyboard at index 0.
/// It may have an IBus keyboard at that position.
/// </remarks>
public IKeyboardDefinition DefaultKeyboard
{
get
{
int minGroup = Int32.MaxValue;
IKeyboardDefinition retval = null;
foreach (var kbd in Keyboard.Controller.AllAvailableKeyboards)
{
if (kbd is XkbKeyboardDescription && kbd.Type == KeyboardType.System &&
((XkbKeyboardDescription)kbd).GroupIndex < minGroup)
{
retval = kbd;
minGroup = ((XkbKeyboardDescription)kbd).GroupIndex;
}
}
return retval;
}
}
private string _missingKeyboardFmt;
/// <summary>
/// Creates and returns a keyboard definition object based on the layout and locale.
/// Note that this method is used when we do NOT have a matching available keyboard.
/// Therefore we can presume that the created one is NOT available.
/// </summary>
public IKeyboardDefinition CreateKeyboardDefinition(string layout, string locale)
{
var realLocale = locale;
if (locale == "zh")
{
realLocale = "zh-CN"; // Mono doesn't support bare "zh" until version 3 sometime
}
else if (locale == "x040F")
{
realLocale = "is"; // 0x040F is the numeric code for Icelandic.
}
// Don't crash if the locale is unknown to the system. (It may be that ibus is not running and
// this particular locale and layout refer to an ibus keyboard.) Mark the keyboard description
// as missing, but create an English (US) keyboard underneath.
if (IsLocaleKnown(realLocale))
return new XkbKeyboardDescription(string.Format("{0} ({1})", locale, layout), layout, locale,
new InputLanguageWrapper(realLocale, IntPtr.Zero, layout), this, -1) {IsAvailable = false};
if (_missingKeyboardFmt == null)
_missingKeyboardFmt = L10NSharp.LocalizationManager.GetString("XkbKeyboardAdaptor.MissingKeyboard", "[Missing] {0} ({1})");
return new XkbKeyboardDescription(String.Format(_missingKeyboardFmt, locale, layout), layout, locale,
new InputLanguageWrapper("en", IntPtr.Zero, "US"), this, -1) {IsAvailable = false};
}
private static HashSet<string> _knownCultures;
/// <summary>
/// Check whether the locale is known to the system.
/// </summary>
private static bool IsLocaleKnown(string locale)
{
if (_knownCultures == null)
{
_knownCultures = new HashSet<string>();
foreach (var ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
_knownCultures.Add(ci.Name);
}
return _knownCultures.Contains(locale);
}
}
}
#endif
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2014 lambdalice
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using CoreTweet.Core;
/// <summary>
/// The twitter library.
/// </summary>
namespace CoreTweet
{
/// <summary>
/// The type of the HTTP method.
/// </summary>
public enum MethodType
{
Get,
Post,
Put
}
/// <summary>
/// Sends a request to Twitter and some other web services.
/// A simple change
/// Another
/// </summary>
internal static partial class Request
{
private static string CreateQueryString(IEnumerable<KeyValuePair<string, object>> prm)
{
return prm.Select(x => UrlEncode(x.Key) + "=" + UrlEncode(x.Value.ToString())).JoinToString("&");
}
private static void WriteMultipartFormData(Stream stream, string boundary, IEnumerable<KeyValuePair<string, object>> prm)
{
prm.ForEach(x =>
{
var valueStream = x.Value as Stream;
var valueBytes = x.Value as IEnumerable<byte>;
#if !PCL
var valueFile = x.Value as FileInfo;
#endif
var valueString = x.Value.ToString();
stream.WriteString("--" + boundary + "\r\n");
if(valueStream != null || valueBytes != null
#if !PCL
|| valueFile != null
#endif
)
{
stream.WriteString("Content-Type: application/octet-stream\r\n");
}
stream.WriteString(String.Format(@"Content-Disposition: form-data; name=""{0}""", x.Key));
#if !PCL
if(valueFile != null)
stream.WriteString(String.Format(@"; filename=""{0}""", valueFile.Name));
else
#endif
if(valueStream != null || valueBytes != null)
stream.WriteString(@"; filename=""file""");
stream.WriteString("\r\n\r\n");
#if !PCL
if(valueFile != null)
valueStream = valueFile.OpenRead();
#endif
if(valueStream != null)
{
while (true)
{
var buffer = new byte[4096];
var count = valueStream.Read(buffer, 0, buffer.Length);
if (count == 0) break;
stream.Write(buffer, 0, count);
}
}
else if(valueBytes != null)
valueBytes.ForEach(b => stream.WriteByte(b));
else
stream.WriteString(valueString);
#if !PCL
if(valueFile != null)
valueStream.Close();
#endif
stream.WriteString("\r\n");
});
stream.WriteString("--" + boundary + "--");
}
#if !PCL
/// <summary>
/// Sends a GET request.
/// </summary>
/// <returns>The response.</returns>
/// <param name="url">URL.</param>
/// <param name="prm">Parameters.</param>
/// <param name="authorizationHeader">String of OAuth header.</param>
/// <param name="userAgent">User-Agent header.</param>
/// <param name="proxy">Proxy information for the request.</param>
internal static HttpWebResponse HttpGet(string url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options)
{
if(prm == null) prm = new Dictionary<string,object>();
if(options == null) options = new ConnectionOptions();
var req = (HttpWebRequest)WebRequest.Create(url + '?' + CreateQueryString(prm));
req.Timeout = options.Timeout;
req.ReadWriteTimeout = options.ReadWriteTimeout;
req.UserAgent = options.UserAgent;
req.Proxy = options.Proxy;
req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader);
// Add special header needed for XYZ
if(options.BeforeRequestAction != null) options.BeforeRequestAction(req);
return (HttpWebResponse)req.GetResponse();
}
/// <summary>
/// Sends a POST request.
/// </summary>
/// <returns>The response.</returns>
/// <param name="url">URL.</param>
/// <param name="prm">Parameters.</param>
/// <param name="authorizationHeader">String of OAuth header.</param>
/// <param name="userAgent">User-Agent header.</param>
/// <param name="proxy">Proxy information for the request.</param>
internal static HttpWebResponse HttpPost(string url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options)
{
if(prm == null) prm = new Dictionary<string,object>();
if(options == null) options = new ConnectionOptions();
var data = Encoding.UTF8.GetBytes(CreateQueryString(prm));
var req = (HttpWebRequest)WebRequest.Create(url);
req.ServicePoint.Expect100Continue = false;
req.Method = "POST";
req.Timeout = options.Timeout;
req.ReadWriteTimeout = options.ReadWriteTimeout;
req.UserAgent = options.UserAgent;
//req.Proxy = options.Proxy;
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader);
if(options.BeforeRequestAction != null) options.BeforeRequestAction(req);
using(var reqstr = req.GetRequestStream())
reqstr.Write(data, 0, data.Length);
return (HttpWebResponse)req.GetResponse();
}
/// <summary>
/// Sends a POST request with multipart/form-data.
/// </summary>
/// <returns>The response.</returns>
/// <param name="url">URL.</param>
/// <param name="prm">Parameters.</param>
/// <param name="authorizationHeader">String of OAuth header.</param>
/// <param name="userAgent">User-Agent header.</param>
/// <param name="proxy">Proxy information for the request.</param>
internal static HttpWebResponse HttpPostWithMultipartFormData(string url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options)
{
if(options == null) options = new ConnectionOptions();
var boundary = Guid.NewGuid().ToString();
var req = (HttpWebRequest)WebRequest.Create(url);
req.ServicePoint.Expect100Continue = false;
req.Method = "POST";
req.Timeout = options.Timeout;
req.ReadWriteTimeout = options.ReadWriteTimeout;
req.UserAgent = options.UserAgent;
req.Proxy = options.Proxy;
req.ContentType = "multipart/form-data;boundary=" + boundary;
req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader);
if(options.BeforeRequestAction != null) options.BeforeRequestAction(req);
using (var reqstr = req.GetRequestStream())
WriteMultipartFormData(reqstr, boundary, prm);
return (HttpWebResponse)req.GetResponse();
}
#endif
/// <summary>
/// Generates the signature.
/// </summary>
/// <returns>The signature.</returns>
/// <param name="t">Tokens.</param>
/// <param name="httpMethod">The http method.</param>
/// <param name="url">the URL.</param>
/// <param name="prm">Parameters.</param>
internal static string GenerateSignature(Tokens t, string httpMethod, string url, IEnumerable<KeyValuePair<string, string>> prm)
{
var key = Encoding.UTF8.GetBytes(
string.Format("{0}&{1}", UrlEncode(t.ConsumerSecret),
UrlEncode(t.AccessTokenSecret) ?? ""));
var uri = new Uri(url);
var msg = System.Text.Encoding.UTF8.GetBytes(
string.Format("{0}&{1}&{2}", httpMethod,
UrlEncode(string.Format("{0}://{1}{2}", uri.Scheme, uri.Host, uri.AbsolutePath)),
UrlEncode(prm.OrderBy(x => x.Key)
.ThenBy(x => x.Value)
.Select(x => string.Format("{0}={1}", UrlEncode(x.Key), UrlEncode(x.Value)))
.JoinToString("&")
)
));
return Convert.ToBase64String(SecurityUtils.HmacSha1(key, msg));
}
/// <summary>
/// Generates the parameters.
/// </summary>
/// <returns>The parameters.</returns>
/// <param name="consumerKey">Consumer key.</param>
/// <param name="token">Token.</param>
internal static Dictionary<string, string> GenerateParameters(string consumerKey, string token)
{
var ret = new Dictionary<string, string>() {
{"oauth_consumer_key", consumerKey},
{"oauth_signature_method", "HMAC-SHA1"},
{"oauth_timestamp", ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).Ticks
/ 10000000L).ToString("D")},
{"oauth_nonce", new Random().Next(int.MinValue, int.MaxValue).ToString("X")},
{"oauth_version", "1.0"}
};
if(!string.IsNullOrEmpty(token))
ret.Add("oauth_token", token);
return ret;
}
/// <summary>
/// Encodes the specified text.
/// </summary>
/// <returns>The encoded text.</returns>
/// <param name="text">Text.</param>
internal static string UrlEncode(string text)
{
if(string.IsNullOrEmpty(text))
return "";
return Encoding.UTF8.GetBytes(text)
.Select(x => x < 0x80 && "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"
.Contains(((char)x).ToString()) ? ((char)x).ToString() : ('%' + x.ToString("X2")))
.JoinToString();
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V10.Services
{
/// <summary>Settings for <see cref="CustomerExtensionSettingServiceClient"/> instances.</summary>
public sealed partial class CustomerExtensionSettingServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CustomerExtensionSettingServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CustomerExtensionSettingServiceSettings"/>.</returns>
public static CustomerExtensionSettingServiceSettings GetDefault() => new CustomerExtensionSettingServiceSettings();
/// <summary>
/// Constructs a new <see cref="CustomerExtensionSettingServiceSettings"/> object with default settings.
/// </summary>
public CustomerExtensionSettingServiceSettings()
{
}
private CustomerExtensionSettingServiceSettings(CustomerExtensionSettingServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateCustomerExtensionSettingsSettings = existing.MutateCustomerExtensionSettingsSettings;
OnCopy(existing);
}
partial void OnCopy(CustomerExtensionSettingServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerExtensionSettingServiceClient.MutateCustomerExtensionSettings</c> and
/// <c>CustomerExtensionSettingServiceClient.MutateCustomerExtensionSettingsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateCustomerExtensionSettingsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CustomerExtensionSettingServiceSettings"/> object.</returns>
public CustomerExtensionSettingServiceSettings Clone() => new CustomerExtensionSettingServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CustomerExtensionSettingServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class CustomerExtensionSettingServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerExtensionSettingServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CustomerExtensionSettingServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CustomerExtensionSettingServiceClientBuilder()
{
UseJwtAccessWithScopes = CustomerExtensionSettingServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CustomerExtensionSettingServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerExtensionSettingServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CustomerExtensionSettingServiceClient Build()
{
CustomerExtensionSettingServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CustomerExtensionSettingServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CustomerExtensionSettingServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CustomerExtensionSettingServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CustomerExtensionSettingServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CustomerExtensionSettingServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CustomerExtensionSettingServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CustomerExtensionSettingServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
CustomerExtensionSettingServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerExtensionSettingServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CustomerExtensionSettingService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage customer extension settings.
/// </remarks>
public abstract partial class CustomerExtensionSettingServiceClient
{
/// <summary>
/// The default endpoint for the CustomerExtensionSettingService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CustomerExtensionSettingService scopes.</summary>
/// <remarks>
/// The default CustomerExtensionSettingService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CustomerExtensionSettingServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CustomerExtensionSettingServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CustomerExtensionSettingServiceClient"/>.</returns>
public static stt::Task<CustomerExtensionSettingServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CustomerExtensionSettingServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CustomerExtensionSettingServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CustomerExtensionSettingServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CustomerExtensionSettingServiceClient"/>.</returns>
public static CustomerExtensionSettingServiceClient Create() =>
new CustomerExtensionSettingServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CustomerExtensionSettingServiceClient"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CustomerExtensionSettingServiceSettings"/>.</param>
/// <returns>The created <see cref="CustomerExtensionSettingServiceClient"/>.</returns>
internal static CustomerExtensionSettingServiceClient Create(grpccore::CallInvoker callInvoker, CustomerExtensionSettingServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CustomerExtensionSettingService.CustomerExtensionSettingServiceClient grpcClient = new CustomerExtensionSettingService.CustomerExtensionSettingServiceClient(callInvoker);
return new CustomerExtensionSettingServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CustomerExtensionSettingService client</summary>
public virtual CustomerExtensionSettingService.CustomerExtensionSettingServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes customer extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerExtensionSettingsResponse MutateCustomerExtensionSettings(MutateCustomerExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes customer extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerExtensionSettingsResponse> MutateCustomerExtensionSettingsAsync(MutateCustomerExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes customer extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerExtensionSettingsResponse> MutateCustomerExtensionSettingsAsync(MutateCustomerExtensionSettingsRequest request, st::CancellationToken cancellationToken) =>
MutateCustomerExtensionSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes customer extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose customer extension settings are being
/// modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual customer extension
/// settings.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerExtensionSettingsResponse MutateCustomerExtensionSettings(string customerId, scg::IEnumerable<CustomerExtensionSettingOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerExtensionSettings(new MutateCustomerExtensionSettingsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes customer extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose customer extension settings are being
/// modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual customer extension
/// settings.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerExtensionSettingsResponse> MutateCustomerExtensionSettingsAsync(string customerId, scg::IEnumerable<CustomerExtensionSettingOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerExtensionSettingsAsync(new MutateCustomerExtensionSettingsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes customer extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose customer extension settings are being
/// modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual customer extension
/// settings.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerExtensionSettingsResponse> MutateCustomerExtensionSettingsAsync(string customerId, scg::IEnumerable<CustomerExtensionSettingOperation> operations, st::CancellationToken cancellationToken) =>
MutateCustomerExtensionSettingsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CustomerExtensionSettingService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage customer extension settings.
/// </remarks>
public sealed partial class CustomerExtensionSettingServiceClientImpl : CustomerExtensionSettingServiceClient
{
private readonly gaxgrpc::ApiCall<MutateCustomerExtensionSettingsRequest, MutateCustomerExtensionSettingsResponse> _callMutateCustomerExtensionSettings;
/// <summary>
/// Constructs a client wrapper for the CustomerExtensionSettingService service, with the specified gRPC client
/// and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="CustomerExtensionSettingServiceSettings"/> used within this client.
/// </param>
public CustomerExtensionSettingServiceClientImpl(CustomerExtensionSettingService.CustomerExtensionSettingServiceClient grpcClient, CustomerExtensionSettingServiceSettings settings)
{
GrpcClient = grpcClient;
CustomerExtensionSettingServiceSettings effectiveSettings = settings ?? CustomerExtensionSettingServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateCustomerExtensionSettings = clientHelper.BuildApiCall<MutateCustomerExtensionSettingsRequest, MutateCustomerExtensionSettingsResponse>(grpcClient.MutateCustomerExtensionSettingsAsync, grpcClient.MutateCustomerExtensionSettings, effectiveSettings.MutateCustomerExtensionSettingsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCustomerExtensionSettings);
Modify_MutateCustomerExtensionSettingsApiCall(ref _callMutateCustomerExtensionSettings);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_MutateCustomerExtensionSettingsApiCall(ref gaxgrpc::ApiCall<MutateCustomerExtensionSettingsRequest, MutateCustomerExtensionSettingsResponse> call);
partial void OnConstruction(CustomerExtensionSettingService.CustomerExtensionSettingServiceClient grpcClient, CustomerExtensionSettingServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CustomerExtensionSettingService client</summary>
public override CustomerExtensionSettingService.CustomerExtensionSettingServiceClient GrpcClient { get; }
partial void Modify_MutateCustomerExtensionSettingsRequest(ref MutateCustomerExtensionSettingsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates, updates, or removes customer extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateCustomerExtensionSettingsResponse MutateCustomerExtensionSettings(MutateCustomerExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerExtensionSettingsRequest(ref request, ref callSettings);
return _callMutateCustomerExtensionSettings.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes customer extension settings. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DateError]()
/// [DistinctError]()
/// [ExtensionSettingError]()
/// [FieldError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [ListOperationError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UrlFieldError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateCustomerExtensionSettingsResponse> MutateCustomerExtensionSettingsAsync(MutateCustomerExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerExtensionSettingsRequest(ref request, ref callSettings);
return _callMutateCustomerExtensionSettings.Async(request, callSettings);
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
// 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 8/14/2009 4:46:07 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
#pragma warning disable 1591
namespace DotSpatial.Projections.ProjectedCategories
{
/// <summary>
/// NatGridsAustralia
/// </summary>
public class NationalGridsAustralia : CoordinateSystemCategory
{
#region Private Variables
public readonly ProjectionInfo AGD1966ACTGridAGCZone;
public readonly ProjectionInfo AGD1966AMGZone48;
public readonly ProjectionInfo AGD1966AMGZone49;
public readonly ProjectionInfo AGD1966AMGZone50;
public readonly ProjectionInfo AGD1966AMGZone51;
public readonly ProjectionInfo AGD1966AMGZone52;
public readonly ProjectionInfo AGD1966AMGZone53;
public readonly ProjectionInfo AGD1966AMGZone54;
public readonly ProjectionInfo AGD1966AMGZone55;
public readonly ProjectionInfo AGD1966AMGZone56;
public readonly ProjectionInfo AGD1966AMGZone57;
public readonly ProjectionInfo AGD1966AMGZone58;
public readonly ProjectionInfo AGD1966ISG542;
public readonly ProjectionInfo AGD1966ISG543;
public readonly ProjectionInfo AGD1966ISG551;
public readonly ProjectionInfo AGD1966ISG552;
public readonly ProjectionInfo AGD1966ISG553;
public readonly ProjectionInfo AGD1966ISG561;
public readonly ProjectionInfo AGD1966ISG562;
public readonly ProjectionInfo AGD1966ISG563;
public readonly ProjectionInfo AGD1966VICGRID;
public readonly ProjectionInfo AGD1984AMGZone48;
public readonly ProjectionInfo AGD1984AMGZone49;
public readonly ProjectionInfo AGD1984AMGZone50;
public readonly ProjectionInfo AGD1984AMGZone51;
public readonly ProjectionInfo AGD1984AMGZone52;
public readonly ProjectionInfo AGD1984AMGZone53;
public readonly ProjectionInfo AGD1984AMGZone54;
public readonly ProjectionInfo AGD1984AMGZone55;
public readonly ProjectionInfo AGD1984AMGZone56;
public readonly ProjectionInfo AGD1984AMGZone57;
public readonly ProjectionInfo AGD1984AMGZone58;
public readonly ProjectionInfo GDA1994MGAZone48;
public readonly ProjectionInfo GDA1994MGAZone49;
public readonly ProjectionInfo GDA1994MGAZone50;
public readonly ProjectionInfo GDA1994MGAZone51;
public readonly ProjectionInfo GDA1994MGAZone52;
public readonly ProjectionInfo GDA1994MGAZone53;
public readonly ProjectionInfo GDA1994MGAZone54;
public readonly ProjectionInfo GDA1994MGAZone55;
public readonly ProjectionInfo GDA1994MGAZone56;
public readonly ProjectionInfo GDA1994MGAZone57;
public readonly ProjectionInfo GDA1994MGAZone58;
public readonly ProjectionInfo GDA1994SouthAustraliaLambert;
public readonly ProjectionInfo GDA1994VICGRID94;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of NatGridsAustralia
/// </summary>
public NationalGridsAustralia()
{
AGD1966ACTGridAGCZone = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=149.0092948333333 +k=1.000086 +x_0=200000 +y_0=4510193.4939 +ellps=aust_SA +units=m +no_defs ");
AGD1966AMGZone48 = ProjectionInfo.FromProj4String("+proj=utm +zone=48 +south +ellps=aust_SA +units=m +no_defs ");
AGD1966AMGZone49 = ProjectionInfo.FromProj4String("+proj=utm +zone=49 +south +ellps=aust_SA +units=m +no_defs ");
AGD1966AMGZone50 = ProjectionInfo.FromProj4String("+proj=utm +zone=50 +south +ellps=aust_SA +units=m +no_defs ");
AGD1966AMGZone51 = ProjectionInfo.FromProj4String("+proj=utm +zone=51 +south +ellps=aust_SA +units=m +no_defs ");
AGD1966AMGZone52 = ProjectionInfo.FromProj4String("+proj=utm +zone=52 +south +ellps=aust_SA +units=m +no_defs ");
AGD1966AMGZone53 = ProjectionInfo.FromProj4String("+proj=utm +zone=53 +south +ellps=aust_SA +units=m +no_defs ");
AGD1966AMGZone54 = ProjectionInfo.FromProj4String("+proj=utm +zone=54 +south +ellps=aust_SA +units=m +no_defs ");
AGD1966AMGZone55 = ProjectionInfo.FromProj4String("+proj=utm +zone=55 +south +ellps=aust_SA +units=m +no_defs ");
AGD1966AMGZone56 = ProjectionInfo.FromProj4String("+proj=utm +zone=56 +south +ellps=aust_SA +units=m +no_defs ");
AGD1966AMGZone57 = ProjectionInfo.FromProj4String("+proj=utm +zone=57 +south +ellps=aust_SA +units=m +no_defs ");
AGD1966AMGZone58 = ProjectionInfo.FromProj4String("+proj=utm +zone=58 +south +ellps=aust_SA +units=m +no_defs ");
AGD1966ISG542 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=141 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs ");
AGD1966ISG543 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=143 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs ");
AGD1966ISG551 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=145 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs ");
AGD1966ISG552 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=147 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs ");
AGD1966ISG553 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=149 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs ");
AGD1966ISG561 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=151 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs ");
AGD1966ISG562 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=153 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs ");
AGD1966ISG563 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=155 +k=0.999940 +x_0=300000 +y_0=5000000 +ellps=aust_SA +units=m +no_defs ");
AGD1966VICGRID = ProjectionInfo.FromProj4String("+proj=lcc +lat_1=-36 +lat_2=-38 +lat_0=-37 +lon_0=145 +x_0=2500000 +y_0=4500000 +ellps=aust_SA +units=m +no_defs ");
AGD1984AMGZone48 = ProjectionInfo.FromProj4String("+proj=utm +zone=48 +south +ellps=aust_SA +units=m +no_defs ");
AGD1984AMGZone49 = ProjectionInfo.FromProj4String("+proj=utm +zone=49 +south +ellps=aust_SA +units=m +no_defs ");
AGD1984AMGZone50 = ProjectionInfo.FromProj4String("+proj=utm +zone=50 +south +ellps=aust_SA +units=m +no_defs ");
AGD1984AMGZone51 = ProjectionInfo.FromProj4String("+proj=utm +zone=51 +south +ellps=aust_SA +units=m +no_defs ");
AGD1984AMGZone52 = ProjectionInfo.FromProj4String("+proj=utm +zone=52 +south +ellps=aust_SA +units=m +no_defs ");
AGD1984AMGZone53 = ProjectionInfo.FromProj4String("+proj=utm +zone=53 +south +ellps=aust_SA +units=m +no_defs ");
AGD1984AMGZone54 = ProjectionInfo.FromProj4String("+proj=utm +zone=54 +south +ellps=aust_SA +units=m +no_defs ");
AGD1984AMGZone55 = ProjectionInfo.FromProj4String("+proj=utm +zone=55 +south +ellps=aust_SA +units=m +no_defs ");
AGD1984AMGZone56 = ProjectionInfo.FromProj4String("+proj=utm +zone=56 +south +ellps=aust_SA +units=m +no_defs ");
AGD1984AMGZone57 = ProjectionInfo.FromProj4String("+proj=utm +zone=57 +south +ellps=aust_SA +units=m +no_defs ");
AGD1984AMGZone58 = ProjectionInfo.FromProj4String("+proj=utm +zone=58 +south +ellps=aust_SA +units=m +no_defs ");
GDA1994MGAZone48 = ProjectionInfo.FromProj4String("+proj=utm +zone=48 +south +ellps=GRS80 +units=m +no_defs ");
GDA1994MGAZone49 = ProjectionInfo.FromProj4String("+proj=utm +zone=49 +south +ellps=GRS80 +units=m +no_defs ");
GDA1994MGAZone50 = ProjectionInfo.FromProj4String("+proj=utm +zone=50 +south +ellps=GRS80 +units=m +no_defs ");
GDA1994MGAZone51 = ProjectionInfo.FromProj4String("+proj=utm +zone=51 +south +ellps=GRS80 +units=m +no_defs ");
GDA1994MGAZone52 = ProjectionInfo.FromProj4String("+proj=utm +zone=52 +south +ellps=GRS80 +units=m +no_defs ");
GDA1994MGAZone53 = ProjectionInfo.FromProj4String("+proj=utm +zone=53 +south +ellps=GRS80 +units=m +no_defs ");
GDA1994MGAZone54 = ProjectionInfo.FromProj4String("+proj=utm +zone=54 +south +ellps=GRS80 +units=m +no_defs ");
GDA1994MGAZone55 = ProjectionInfo.FromProj4String("+proj=utm +zone=55 +south +ellps=GRS80 +units=m +no_defs ");
GDA1994MGAZone56 = ProjectionInfo.FromProj4String("+proj=utm +zone=56 +south +ellps=GRS80 +units=m +no_defs ");
GDA1994MGAZone57 = ProjectionInfo.FromProj4String("+proj=utm +zone=57 +south +ellps=GRS80 +units=m +no_defs ");
GDA1994MGAZone58 = ProjectionInfo.FromProj4String("+proj=utm +zone=58 +south +ellps=GRS80 +units=m +no_defs ");
GDA1994SouthAustraliaLambert = ProjectionInfo.FromProj4String("+proj=lcc +lat_1=-28 +lat_2=-36 +lat_0=-32 +lon_0=135 +x_0=1000000 +y_0=2000000 +ellps=GRS80 +units=m +no_defs ");
GDA1994VICGRID94 = ProjectionInfo.FromProj4String("+proj=lcc +lat_1=-36 +lat_2=-38 +lat_0=-37 +lon_0=145 +x_0=2500000 +y_0=2500000 +ellps=GRS80 +units=m +no_defs ");
AGD1966ACTGridAGCZone.Name = "AGD_1966_ACT_Grid_AGC_Zone";
AGD1966AMGZone48.Name = "AGD_1966_AMG_Zone_48";
AGD1966AMGZone49.Name = "AGD_1966_AMG_Zone_49";
AGD1966AMGZone50.Name = "AGD_1966_AMG_Zone_50";
AGD1966AMGZone51.Name = "AGD_1966_AMG_Zone_51";
AGD1966AMGZone52.Name = "AGD_1966_AMG_Zone_52";
AGD1966AMGZone53.Name = "AGD_1966_AMG_Zone_53";
AGD1966AMGZone54.Name = "AGD_1966_AMG_Zone_54";
AGD1966AMGZone55.Name = "AGD_1966_AMG_Zone_55";
AGD1966AMGZone56.Name = "AGD_1966_AMG_Zone_56";
AGD1966AMGZone57.Name = "AGD_1966_AMG_Zone_57";
AGD1966AMGZone58.Name = "AGD_1966_AMG_Zone_58";
AGD1966ISG542.Name = "AGD_1966_ISG_54_2";
AGD1966ISG543.Name = "AGD_1966_ISG_54_3";
AGD1966ISG551.Name = "AGD_1966_ISG_55_1";
AGD1966ISG552.Name = "AGD_1966_ISG_55_2";
AGD1966ISG553.Name = "AGD_1966_ISG_55_3";
AGD1966ISG561.Name = "AGD_1966_ISG_56_1";
AGD1966ISG562.Name = "AGD_1966_ISG_56_2";
AGD1966ISG563.Name = "AGD_1966_ISG_56_3";
AGD1966VICGRID.Name = "AGD_1966_VICGRID";
AGD1984AMGZone48.Name = "AGD_1984_AMG_Zone_48";
AGD1984AMGZone49.Name = "AGD_1984_AMG_Zone_49";
AGD1984AMGZone50.Name = "AGD_1984_AMG_Zone_50";
AGD1984AMGZone51.Name = "AGD_1984_AMG_Zone_51";
AGD1984AMGZone52.Name = "AGD_1984_AMG_Zone_52";
AGD1984AMGZone53.Name = "AGD_1984_AMG_Zone_53";
AGD1984AMGZone54.Name = "AGD_1984_AMG_Zone_54";
AGD1984AMGZone55.Name = "AGD_1984_AMG_Zone_55";
AGD1984AMGZone56.Name = "AGD_1984_AMG_Zone_56";
AGD1984AMGZone57.Name = "AGD_1984_AMG_Zone_57";
AGD1984AMGZone58.Name = "AGD_1984_AMG_Zone_58";
GDA1994MGAZone48.Name = "GDA_1994_MGA_Zone_48";
GDA1994MGAZone49.Name = "GDA_1994_MGA_Zone_49";
GDA1994MGAZone50.Name = "GDA_1994_MGA_Zone_50";
GDA1994MGAZone51.Name = "GDA_1994_MGA_Zone_51";
GDA1994MGAZone52.Name = "GDA_1994_MGA_Zone_52";
GDA1994MGAZone53.Name = "GDA_1994_MGA_Zone_53";
GDA1994MGAZone54.Name = "GDA_1994_MGA_Zone_54";
GDA1994MGAZone55.Name = "GDA_1994_MGA_Zone_55";
GDA1994MGAZone56.Name = "GDA_1994_MGA_Zone_56";
GDA1994MGAZone57.Name = "GDA_1994_MGA_Zone_57";
GDA1994MGAZone58.Name = "GDA_1994_MGA_Zone_58";
GDA1994SouthAustraliaLambert.Name = "GDA_1994_South_Australia_Lambert";
GDA1994VICGRID94.Name = "GDA_1994_VICGRID94";
AGD1966ACTGridAGCZone.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966AMGZone48.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966AMGZone49.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966AMGZone50.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966AMGZone51.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966AMGZone52.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966AMGZone53.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966AMGZone54.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966AMGZone55.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966AMGZone56.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966AMGZone57.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966AMGZone58.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966ISG542.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966ISG543.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966ISG551.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966ISG552.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966ISG553.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966ISG561.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966ISG562.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966ISG563.GeographicInfo.Name = "GCS_Australian_1966";
AGD1966VICGRID.GeographicInfo.Name = "GCS_Australian_1966";
AGD1984AMGZone48.GeographicInfo.Name = "GCS_Australian_1984";
AGD1984AMGZone49.GeographicInfo.Name = "GCS_Australian_1984";
AGD1984AMGZone50.GeographicInfo.Name = "GCS_Australian_1984";
AGD1984AMGZone51.GeographicInfo.Name = "GCS_Australian_1984";
AGD1984AMGZone52.GeographicInfo.Name = "GCS_Australian_1984";
AGD1984AMGZone53.GeographicInfo.Name = "GCS_Australian_1984";
AGD1984AMGZone54.GeographicInfo.Name = "GCS_Australian_1984";
AGD1984AMGZone55.GeographicInfo.Name = "GCS_Australian_1984";
AGD1984AMGZone56.GeographicInfo.Name = "GCS_Australian_1984";
AGD1984AMGZone57.GeographicInfo.Name = "GCS_Australian_1984";
AGD1984AMGZone58.GeographicInfo.Name = "GCS_Australian_1984";
GDA1994MGAZone48.GeographicInfo.Name = "GCS_GDA_1994";
GDA1994MGAZone49.GeographicInfo.Name = "GCS_GDA_1994";
GDA1994MGAZone50.GeographicInfo.Name = "GCS_GDA_1994";
GDA1994MGAZone51.GeographicInfo.Name = "GCS_GDA_1994";
GDA1994MGAZone52.GeographicInfo.Name = "GCS_GDA_1994";
GDA1994MGAZone53.GeographicInfo.Name = "GCS_GDA_1994";
GDA1994MGAZone54.GeographicInfo.Name = "GCS_GDA_1994";
GDA1994MGAZone55.GeographicInfo.Name = "GCS_GDA_1994";
GDA1994MGAZone56.GeographicInfo.Name = "GCS_GDA_1994";
GDA1994MGAZone57.GeographicInfo.Name = "GCS_GDA_1994";
GDA1994MGAZone58.GeographicInfo.Name = "GCS_GDA_1994";
GDA1994SouthAustraliaLambert.GeographicInfo.Name = "GCS_GDA_1994";
GDA1994VICGRID94.GeographicInfo.Name = "GCS_GDA_1994";
AGD1966ACTGridAGCZone.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966AMGZone48.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966AMGZone49.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966AMGZone50.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966AMGZone51.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966AMGZone52.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966AMGZone53.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966AMGZone54.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966AMGZone55.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966AMGZone56.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966AMGZone57.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966AMGZone58.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966ISG542.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966ISG543.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966ISG551.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966ISG552.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966ISG553.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966ISG561.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966ISG562.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966ISG563.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1966VICGRID.GeographicInfo.Datum.Name = "D_Australian_1966";
AGD1984AMGZone48.GeographicInfo.Datum.Name = "D_Australian_1984";
AGD1984AMGZone49.GeographicInfo.Datum.Name = "D_Australian_1984";
AGD1984AMGZone50.GeographicInfo.Datum.Name = "D_Australian_1984";
AGD1984AMGZone51.GeographicInfo.Datum.Name = "D_Australian_1984";
AGD1984AMGZone52.GeographicInfo.Datum.Name = "D_Australian_1984";
AGD1984AMGZone53.GeographicInfo.Datum.Name = "D_Australian_1984";
AGD1984AMGZone54.GeographicInfo.Datum.Name = "D_Australian_1984";
AGD1984AMGZone55.GeographicInfo.Datum.Name = "D_Australian_1984";
AGD1984AMGZone56.GeographicInfo.Datum.Name = "D_Australian_1984";
AGD1984AMGZone57.GeographicInfo.Datum.Name = "D_Australian_1984";
AGD1984AMGZone58.GeographicInfo.Datum.Name = "D_Australian_1984";
GDA1994MGAZone48.GeographicInfo.Datum.Name = "D_GDA_1994";
GDA1994MGAZone49.GeographicInfo.Datum.Name = "D_GDA_1994";
GDA1994MGAZone50.GeographicInfo.Datum.Name = "D_GDA_1994";
GDA1994MGAZone51.GeographicInfo.Datum.Name = "D_GDA_1994";
GDA1994MGAZone52.GeographicInfo.Datum.Name = "D_GDA_1994";
GDA1994MGAZone53.GeographicInfo.Datum.Name = "D_GDA_1994";
GDA1994MGAZone54.GeographicInfo.Datum.Name = "D_GDA_1994";
GDA1994MGAZone55.GeographicInfo.Datum.Name = "D_GDA_1994";
GDA1994MGAZone56.GeographicInfo.Datum.Name = "D_GDA_1994";
GDA1994MGAZone57.GeographicInfo.Datum.Name = "D_GDA_1994";
GDA1994MGAZone58.GeographicInfo.Datum.Name = "D_GDA_1994";
GDA1994SouthAustraliaLambert.GeographicInfo.Datum.Name = "D_GDA_1994";
GDA1994VICGRID94.GeographicInfo.Datum.Name = "D_GDA_1994";
}
#endregion
}
}
#pragma warning restore 1591
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NuGet;
using Squirrel.SimpleSplat;
using Squirrel;
using Squirrel.Tests.TestHelpers;
using Xunit;
namespace Squirrel.Tests
{
public class FakeUrlDownloader : IFileDownloader
{
public Task<byte[]> DownloadUrl(string url)
{
return Task.FromResult(new byte[0]);
}
public async Task DownloadFile(string url, string targetFile, Action<int> progress)
{
}
}
public class ApplyReleasesTests : IEnableLogger
{
[Fact]
public async Task CleanInstallRunsSquirrelAwareAppsWithInstallFlag()
{
string tempDir;
string remotePkgDir;
using (Utility.WithTempDirectory(out tempDir))
using (Utility.WithTempDirectory(out remotePkgDir)) {
IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir);
var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.FullInstall();
// NB: We execute the Squirrel-aware apps, so we need to give
// them a minute to settle or else the using statement will
// try to blow away a running process
await Task.Delay(1000);
Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args2.txt")));
Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt")));
var text = File.ReadAllText(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt"), Encoding.UTF8);
Assert.Contains("firstrun", text);
}
}
}
[Fact]
public async Task UpgradeRunsSquirrelAwareAppsWithUpgradeFlag()
{
string tempDir;
string remotePkgDir;
using (Utility.WithTempDirectory(out tempDir))
using (Utility.WithTempDirectory(out remotePkgDir)) {
IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir);
var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.FullInstall();
}
await Task.Delay(1000);
IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir);
pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.UpdateApp();
}
await Task.Delay(1000);
Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args2.txt")));
Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt")));
var text = File.ReadAllText(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt"), Encoding.UTF8);
Assert.Contains("updated|0.2.0", text);
}
}
[Fact]
public async Task RunningUpgradeAppTwiceDoesntCrash()
{
string tempDir;
string remotePkgDir;
using (Utility.WithTempDirectory(out tempDir))
using (Utility.WithTempDirectory(out remotePkgDir)) {
IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir);
var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.FullInstall();
}
await Task.Delay(1000);
IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir);
pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.UpdateApp();
}
await Task.Delay(1000);
// NB: The 2nd time we won't have any updates to apply. We should just do nothing!
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.UpdateApp();
}
await Task.Delay(1000);
}
}
[Fact]
public async Task FullUninstallRemovesAllVersions()
{
string tempDir;
string remotePkgDir;
using (Utility.WithTempDirectory(out tempDir))
using (Utility.WithTempDirectory(out remotePkgDir)) {
IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir);
var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.FullInstall();
}
await Task.Delay(1000);
IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir);
pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir);
ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES"));
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.UpdateApp();
}
await Task.Delay(1000);
using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) {
await fixture.FullUninstall();
}
Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt")));
Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt")));
Assert.True(File.Exists(Path.Combine(tempDir, "theApp", ".dead")));
}
}
[Fact]
public void WhenNoNewReleasesAreAvailableTheListIsEmpty()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir)) {
var appDir = Directory.CreateDirectory(Path.Combine(tempDir, "theApp"));
var packages = Path.Combine(appDir.FullName, "packages");
Directory.CreateDirectory(packages);
var package = "Squirrel.Core.1.0.0.0-full.nupkg";
File.Copy(IntegrationTestHelper.GetPath("fixtures", package), Path.Combine(packages, package));
var aGivenPackage = Path.Combine(packages, package);
var baseEntry = ReleaseEntry.GenerateFromFile(aGivenPackage);
var updateInfo = UpdateInfo.Create(baseEntry, new[] { baseEntry }, "dontcare");
Assert.Empty(updateInfo.ReleasesToApply);
}
}
[Fact]
public void ThrowsWhenOnlyDeltaReleasesAreAvailable()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir))
{
var appDir = Directory.CreateDirectory(Path.Combine(tempDir, "theApp"));
var packages = Path.Combine(appDir.FullName, "packages");
Directory.CreateDirectory(packages);
var baseFile = "Squirrel.Core.1.0.0.0-full.nupkg";
File.Copy(IntegrationTestHelper.GetPath("fixtures", baseFile),
Path.Combine(packages, baseFile));
var basePackage = Path.Combine(packages, baseFile);
var baseEntry = ReleaseEntry.GenerateFromFile(basePackage);
var deltaFile = "Squirrel.Core.1.1.0.0-delta.nupkg";
File.Copy(IntegrationTestHelper.GetPath("fixtures", deltaFile),
Path.Combine(packages, deltaFile));
var deltaPackage = Path.Combine(packages, deltaFile);
var deltaEntry = ReleaseEntry.GenerateFromFile(deltaPackage);
Assert.Throws<Exception>(
() => UpdateInfo.Create(baseEntry, new[] { deltaEntry }, "dontcare"));
}
}
[Fact]
public async Task ApplyReleasesWithOneReleaseFile()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir)) {
string appDir = Path.Combine(tempDir, "theApp");
string packagesDir = Path.Combine(appDir, "packages");
Directory.CreateDirectory(packagesDir);
new[] {
"Squirrel.Core.1.0.0.0-full.nupkg",
"Squirrel.Core.1.1.0.0-full.nupkg",
}.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x)));
var fixture = new UpdateManager.ApplyReleasesImpl(appDir);
var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.0.0.0-full.nupkg"));
var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg"));
var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir);
updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue();
var progress = new List<int>();
await fixture.ApplyReleases(updateInfo, false, false, progress.Add);
this.Log().Info("Progress: [{0}]", String.Join(",", progress));
progress
.Aggregate(0, (acc, x) => { (x >= acc).ShouldBeTrue(); return x; })
.ShouldEqual(100);
var filesToFind = new[] {
new {Name = "NLog.dll", Version = new Version("2.0.0.0")},
new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")},
};
filesToFind.ForEach(x => {
var path = Path.Combine(tempDir, "theApp", "app-1.1.0.0", x.Name);
this.Log().Info("Looking for {0}", path);
File.Exists(path).ShouldBeTrue();
var vi = FileVersionInfo.GetVersionInfo(path);
var verInfo = new Version(vi.FileVersion ?? "1.0.0.0");
x.Version.ShouldEqual(verInfo);
});
}
}
[Fact]
public async Task ApplyReleaseWhichRemovesAFile()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir)) {
string appDir = Path.Combine(tempDir, "theApp");
string packagesDir = Path.Combine(appDir, "packages");
Directory.CreateDirectory(packagesDir);
new[] {
"Squirrel.Core.1.1.0.0-full.nupkg",
"Squirrel.Core.1.2.0.0-full.nupkg",
}.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x)));
var fixture = new UpdateManager.ApplyReleasesImpl(appDir);
var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg"));
var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.2.0.0-full.nupkg"));
var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir);
updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue();
var progress = new List<int>();
await fixture.ApplyReleases(updateInfo, false, false, progress.Add);
this.Log().Info("Progress: [{0}]", String.Join(",", progress));
progress
.Aggregate(0, (acc, x) => { (x >= acc).ShouldBeTrue(); return x; })
.ShouldEqual(100);
var rootDirectory = Path.Combine(tempDir, "theApp", "app-1.2.0.0");
new[] {
new {Name = "NLog.dll", Version = new Version("2.0.0.0")},
new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")},
}.ForEach(x => {
var path = Path.Combine(rootDirectory, x.Name);
this.Log().Info("Looking for {0}", path);
File.Exists(path).ShouldBeTrue();
});
var removedFile = Path.Combine("sub", "Ionic.Zip.dll");
var deployedPath = Path.Combine(rootDirectory, removedFile);
File.Exists(deployedPath).ShouldBeFalse();
}
}
[Fact]
public async Task ApplyReleaseWhichMovesAFileToADifferentDirectory()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir))
{
string appDir = Path.Combine(tempDir, "theApp");
string packagesDir = Path.Combine(appDir, "packages");
Directory.CreateDirectory(packagesDir);
new[] {
"Squirrel.Core.1.1.0.0-full.nupkg",
"Squirrel.Core.1.3.0.0-full.nupkg",
}.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x)));
var fixture = new UpdateManager.ApplyReleasesImpl(appDir);
var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg"));
var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.3.0.0-full.nupkg"));
var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir);
updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue();
var progress = new List<int>();
await fixture.ApplyReleases(updateInfo, false, false, progress.Add);
this.Log().Info("Progress: [{0}]", String.Join(",", progress));
progress
.Aggregate(0, (acc, x) => { (x >= acc).ShouldBeTrue(); return x; })
.ShouldEqual(100);
var rootDirectory = Path.Combine(tempDir, "theApp", "app-1.3.0.0");
new[] {
new {Name = "NLog.dll", Version = new Version("2.0.0.0")},
new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")},
}.ForEach(x => {
var path = Path.Combine(rootDirectory, x.Name);
this.Log().Info("Looking for {0}", path);
File.Exists(path).ShouldBeTrue();
});
var oldFile = Path.Combine(rootDirectory, "sub", "Ionic.Zip.dll");
File.Exists(oldFile).ShouldBeFalse();
var newFile = Path.Combine(rootDirectory, "other", "Ionic.Zip.dll");
File.Exists(newFile).ShouldBeTrue();
}
}
[Fact]
public async Task ApplyReleasesWithDeltaReleases()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir)) {
string appDir = Path.Combine(tempDir, "theApp");
string packagesDir = Path.Combine(appDir, "packages");
Directory.CreateDirectory(packagesDir);
new[] {
"Squirrel.Core.1.0.0.0-full.nupkg",
"Squirrel.Core.1.1.0.0-delta.nupkg",
"Squirrel.Core.1.1.0.0-full.nupkg",
}.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x)));
var fixture = new UpdateManager.ApplyReleasesImpl(appDir);
var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.0.0.0-full.nupkg"));
var deltaEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-delta.nupkg"));
var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg"));
var updateInfo = UpdateInfo.Create(baseEntry, new[] { deltaEntry, latestFullEntry }, packagesDir);
updateInfo.ReleasesToApply.Contains(deltaEntry).ShouldBeTrue();
var progress = new List<int>();
await fixture.ApplyReleases(updateInfo, false, false, progress.Add);
this.Log().Info("Progress: [{0}]", String.Join(",", progress));
progress
.Aggregate(0, (acc, x) => { (x >= acc).ShouldBeTrue(); return x; })
.ShouldEqual(100);
var filesToFind = new[] {
new {Name = "NLog.dll", Version = new Version("2.0.0.0")},
new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")},
};
filesToFind.ForEach(x => {
var path = Path.Combine(tempDir, "theApp", "app-1.1.0.0", x.Name);
this.Log().Info("Looking for {0}", path);
File.Exists(path).ShouldBeTrue();
var vi = FileVersionInfo.GetVersionInfo(path);
var verInfo = new Version(vi.FileVersion ?? "1.0.0.0");
x.Version.ShouldEqual(verInfo);
});
}
}
[Fact]
public async Task CreateFullPackagesFromDeltaSmokeTest()
{
string tempDir;
using (Utility.WithTempDirectory(out tempDir)) {
string appDir = Path.Combine(tempDir, "theApp");
string packagesDir = Path.Combine(appDir, "packages");
Directory.CreateDirectory(packagesDir);
new[] {
"Squirrel.Core.1.0.0.0-full.nupkg",
"Squirrel.Core.1.1.0.0-delta.nupkg"
}.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(tempDir, "theApp", "packages", x)));
var urlDownloader = new FakeUrlDownloader();
var fixture = new UpdateManager.ApplyReleasesImpl(appDir);
var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(tempDir, "theApp", "packages", "Squirrel.Core.1.0.0.0-full.nupkg"));
var deltaEntry = ReleaseEntry.GenerateFromFile(Path.Combine(tempDir, "theApp", "packages", "Squirrel.Core.1.1.0.0-delta.nupkg"));
var resultObs = (Task<ReleaseEntry>)fixture.GetType().GetMethod("createFullPackagesFromDeltas", BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(fixture, new object[] { new[] {deltaEntry}, baseEntry, null });
var result = await resultObs;
var zp = new ZipPackage(Path.Combine(tempDir, "theApp", "packages", result.Filename));
zp.Version.ToString().ShouldEqual("1.1.0.0");
}
}
[Fact]
public async Task CreateShortcutsRoundTrip()
{
string remotePkgPath;
string path;
using (Utility.WithTempDirectory(out path)) {
using (Utility.WithTempDirectory(out remotePkgPath))
using (var mgr = new UpdateManager(remotePkgPath, "theApp", path)) {
IntegrationTestHelper.CreateFakeInstalledApp("1.0.0.1", remotePkgPath);
await mgr.FullInstall();
}
var fixture = new UpdateManager.ApplyReleasesImpl(Path.Combine(path, "theApp"));
fixture.CreateShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup | ShortcutLocation.AppRoot, false, null, null);
// NB: COM is Weird.
Thread.Sleep(1000);
fixture.RemoveShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup | ShortcutLocation.AppRoot);
// NB: Squirrel-Aware first-run might still be running, slow
// our roll before blowing away the temp path
Thread.Sleep(1000);
}
}
[Fact]
public void UnshimOurselvesSmokeTest()
{
// NB: This smoke test is really more of a manual test - try it
// by shimming Slack, then verifying the shim goes away
var appDir = Environment.ExpandEnvironmentVariables(@"%LocalAppData%\Slack");
var fixture = new UpdateManager.ApplyReleasesImpl(appDir);
fixture.unshimOurselves();
}
[Fact(Skip = "This test is currently failing in CI")]
public async Task GetShortcutsSmokeTest()
{
string remotePkgPath;
string path;
using (Utility.WithTempDirectory(out path)) {
using (Utility.WithTempDirectory(out remotePkgPath))
using (var mgr = new UpdateManager(remotePkgPath, "theApp", path)) {
IntegrationTestHelper.CreateFakeInstalledApp("1.0.0.1", remotePkgPath);
await mgr.FullInstall();
}
var fixture = new UpdateManager.ApplyReleasesImpl(Path.Combine(path, "theApp"));
var result = fixture.GetShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup, null);
Assert.Equal(3, result.Keys.Count);
// NB: Squirrel-Aware first-run might still be running, slow
// our roll before blowing away the temp path
Thread.Sleep(1000);
}
}
}
}
| |
/*
* Copyright 2010 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.Collections.Generic;
using ZXing.Common;
namespace ZXing.OneD
{
/// <summary>
/// This object renders a CODE128 code as a <see cref="BitMatrix" />.
///
/// <author>[email protected] (Erik Barbara)</author>
/// </summary>
public sealed class Code128Writer : OneDimensionalCodeWriter
{
private const int CODE_START_A = 103;
private const int CODE_START_B = 104;
private const int CODE_START_C = 105;
private const int CODE_CODE_A = 101;
private const int CODE_CODE_B = 100;
private const int CODE_CODE_C = 99;
private const int CODE_STOP = 106;
// Dummy characters used to specify control characters in input
private const char ESCAPE_FNC_1 = '\u00f1';
private const char ESCAPE_FNC_2 = '\u00f2';
private const char ESCAPE_FNC_3 = '\u00f3';
private const char ESCAPE_FNC_4 = '\u00f4';
private const int CODE_FNC_1 = 102; // Code A, Code B, Code C
private const int CODE_FNC_2 = 97; // Code A, Code B
private const int CODE_FNC_3 = 96; // Code A, Code B
private const int CODE_FNC_4_A = 101; // Code A
private const int CODE_FNC_4_B = 100; // Code B
// Results of minimal lookahead for code C
private enum CType
{
UNCODABLE,
ONE_DIGIT,
TWO_DIGITS,
FNC_1
}
private bool forceCodesetB;
private static readonly IList<BarcodeFormat> supportedWriteFormats = new List<BarcodeFormat> { BarcodeFormat.CODE_128 };
/// <summary>
/// returns supported formats
/// </summary>
protected override IList<BarcodeFormat> SupportedWriteFormats
{
get { return supportedWriteFormats; }
}
/// <summary>
/// Encode the contents following specified format.
/// </summary>
public override bool[] encode(String contents)
{
return encode(contents, null);
}
/// <summary>
/// starts encoding
/// </summary>
/// <param name="contents"></param>
/// <param name="hints"></param>
/// <returns></returns>
protected override bool[] encode(String contents, IDictionary<EncodeHintType, object> hints)
{
int forcedCodeSet = -1;
if (hints != null)
{
forceCodesetB = (hints.ContainsKey(EncodeHintType.CODE128_FORCE_CODESET_B) &&
hints[EncodeHintType.CODE128_FORCE_CODESET_B] != null &&
Convert.ToBoolean(hints[EncodeHintType.CODE128_FORCE_CODESET_B].ToString()));
// Check for forced code set hint.
if (hints != null && hints.ContainsKey(EncodeHintType.FORCE_CODE_SET))
{
var hintCodeset = hints[EncodeHintType.FORCE_CODE_SET];
if (hintCodeset != null)
{
String codeSetHint = hintCodeset.ToString();
switch (codeSetHint)
{
case "A":
forcedCodeSet = CODE_CODE_A;
break;
case "B":
forcedCodeSet = CODE_CODE_B;
break;
case "C":
forcedCodeSet = CODE_CODE_C;
break;
default:
throw new ArgumentException("Unsupported code set hint: " + codeSetHint);
}
}
}
if (hints != null &&
hints.ContainsKey(EncodeHintType.GS1_FORMAT) &&
hints[EncodeHintType.GS1_FORMAT] != null &&
Convert.ToBoolean(hints[EncodeHintType.GS1_FORMAT].ToString()))
{
// append the FNC1 character at the first position if not already present
if (!string.IsNullOrEmpty(contents) && contents[0] != ESCAPE_FNC_1)
contents = ESCAPE_FNC_1 + contents;
}
}
int length = contents.Length;
// Check content
for (int i = 0; i < length; i++)
{
char c = contents[i];
// check for non ascii characters that are not special GS1 characters
switch (c)
{
case ESCAPE_FNC_1:
case ESCAPE_FNC_2:
case ESCAPE_FNC_3:
case ESCAPE_FNC_4:
break;
// non ascii characters
default:
if (c > 127)
// no full Latin-1 character set available at the moment
// shift and manual code change are not supported
throw new ArgumentException("Bad character in input: ASCII value=" + (int)c);
break;
}
// check characters for compatibility with forced code set
switch (forcedCodeSet)
{
case CODE_CODE_A:
// allows no ascii above 95 (no lower caps, no special symbols)
if (c > 95 && c <= 127)
{
throw new ArgumentException("Bad character in input for forced code set A: ASCII value=" + (int)c);
}
break;
case CODE_CODE_B:
// allows no ascii below 32 (terminal symbols)
if (c <= 32)
{
throw new ArgumentException("Bad character in input for forced code set B: ASCII value=" + (int)c);
}
break;
case CODE_CODE_C:
// allows only numbers and no FNC 2/3/4
if (c < 48 || (c > 57 && c <= 127) || c == ESCAPE_FNC_2 || c == ESCAPE_FNC_3 || c == ESCAPE_FNC_4)
{
throw new ArgumentException("Bad character in input for forced code set C: ASCII value=" + (int)c);
}
break;
}
}
var patterns = new List<int[]>(); // temporary storage for patterns
int checkSum = 0;
int checkWeight = 1;
int codeSet = 0; // selected code (CODE_CODE_B or CODE_CODE_C)
int position = 0; // position in contents
while (position < length)
{
//Select code to use
int newCodeSet;
if (forcedCodeSet == -1)
{
newCodeSet = chooseCode(contents, position, codeSet);
}
else
{
newCodeSet = forcedCodeSet;
}
//Get the pattern index
int patternIndex;
if (newCodeSet == codeSet)
{
// Encode the current character
// First handle escapes
switch (contents[position])
{
case ESCAPE_FNC_1:
patternIndex = CODE_FNC_1;
break;
case ESCAPE_FNC_2:
patternIndex = CODE_FNC_2;
break;
case ESCAPE_FNC_3:
patternIndex = CODE_FNC_3;
break;
case ESCAPE_FNC_4:
if (newCodeSet == CODE_CODE_A)
patternIndex = CODE_FNC_4_A;
else
patternIndex = CODE_FNC_4_B;
break;
default:
// Then handle normal characters otherwise
switch (codeSet)
{
case CODE_CODE_A:
patternIndex = contents[position] - ' ';
if (patternIndex < 0)
{
// everything below a space character comes behind the underscore in the code patterns table
patternIndex += '`';
}
break;
case CODE_CODE_B:
patternIndex = contents[position] - ' ';
break;
default:
// CODE_CODE_C
if (position + 1 == length)
{
// this is the last character, but the encoding is C, which always encodes two characers
throw new ArgumentException("Bad number of characters for digit only encoding.");
}
patternIndex = Int32.Parse(contents.Substring(position, 2));
position++; // Also incremented below
break;
}
break;
}
position++;
}
else
{
// Should we change the current code?
// Do we have a code set?
if (codeSet == 0)
{
// No, we don't have a code set
switch (newCodeSet)
{
case CODE_CODE_A:
patternIndex = CODE_START_A;
break;
case CODE_CODE_B:
patternIndex = CODE_START_B;
break;
default:
patternIndex = CODE_START_C;
break;
}
}
else
{
// Yes, we have a code set
patternIndex = newCodeSet;
}
codeSet = newCodeSet;
}
// Get the pattern
patterns.Add(Code128Reader.CODE_PATTERNS[patternIndex]);
// Compute checksum
checkSum += patternIndex * checkWeight;
if (position != 0)
{
checkWeight++;
}
}
// Compute and append checksum
checkSum %= 103;
patterns.Add(Code128Reader.CODE_PATTERNS[checkSum]);
// Append stop code
patterns.Add(Code128Reader.CODE_PATTERNS[CODE_STOP]);
// Compute code width
int codeWidth = 0;
foreach (int[] pattern in patterns)
{
foreach (int width in pattern)
{
codeWidth += width;
}
}
// Compute result
var result = new bool[codeWidth];
int pos = 0;
foreach (int[] pattern in patterns)
{
pos += appendPattern(result, pos, pattern, true);
}
return result;
}
private static CType findCType(String value, int start)
{
int last = value.Length;
if (start >= last)
{
return CType.UNCODABLE;
}
char c = value[start];
if (c == ESCAPE_FNC_1)
{
return CType.FNC_1;
}
if (c < '0' || c > '9')
{
return CType.UNCODABLE;
}
if (start + 1 >= last)
{
return CType.ONE_DIGIT;
}
c = value[start + 1];
if (c < '0' || c > '9')
{
return CType.ONE_DIGIT;
}
return CType.TWO_DIGITS;
}
private int chooseCode(String value, int start, int oldCode)
{
CType lookahead = findCType(value, start);
if (lookahead == CType.ONE_DIGIT)
{
if (oldCode == CODE_CODE_A)
{
return CODE_CODE_A;
}
return CODE_CODE_B;
}
if (lookahead == CType.UNCODABLE)
{
if (start < value.Length)
{
var c = value[start];
if (c < ' ' || (oldCode == CODE_CODE_A && (c < '`' || (c >= ESCAPE_FNC_1 && c <= ESCAPE_FNC_4))))
{
// can continue in code A, encodes ASCII 0 to 95 or FNC1 to FNC4
return CODE_CODE_A;
}
}
return CODE_CODE_B; // no choice
}
if (oldCode == CODE_CODE_A && lookahead == CType.FNC_1)
{
return CODE_CODE_A;
}
if (oldCode == CODE_CODE_C)
{
// can continue in code C
return CODE_CODE_C;
}
if (oldCode == CODE_CODE_B)
{
if (lookahead == CType.FNC_1)
{
return CODE_CODE_B; // can continue in code B
}
// Seen two consecutive digits, see what follows
lookahead = findCType(value, start + 2);
if (lookahead == CType.UNCODABLE || lookahead == CType.ONE_DIGIT)
{
return CODE_CODE_B; // not worth switching now
}
if (lookahead == CType.FNC_1)
{
// two digits, then FNC_1...
lookahead = findCType(value, start + 3);
if (lookahead == CType.TWO_DIGITS)
{
// then two more digits, switch
return forceCodesetB ? CODE_CODE_B : CODE_CODE_C;
}
else
{
return CODE_CODE_B; // otherwise not worth switching
}
}
// At this point, there are at least 4 consecutive digits.
// Look ahead to choose whether to switch now or on the next round.
int index = start + 4;
while ((lookahead = findCType(value, index)) == CType.TWO_DIGITS)
{
index += 2;
}
if (lookahead == CType.ONE_DIGIT)
{
// odd number of digits, switch later
return CODE_CODE_B;
}
return forceCodesetB ? CODE_CODE_B : CODE_CODE_C; // even number of digits, switch now
}
// Here oldCode == 0, which means we are choosing the initial code
if (lookahead == CType.FNC_1)
{
// ignore FNC_1
lookahead = findCType(value, start + 1);
}
if (lookahead == CType.TWO_DIGITS)
{
// at least two digits, start in code C
return forceCodesetB ? CODE_CODE_B : CODE_CODE_C;
}
return CODE_CODE_B;
}
}
}
| |
using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using Orleans.Core;
using Orleans.Serialization;
namespace Orleans.Runtime
{
[Serializable]
internal class GrainId : UniqueIdentifier, IEquatable<GrainId>, IGrainIdentity
{
private static readonly object lockable = new object();
private const int INTERN_CACHE_INITIAL_SIZE = InternerConstants.SIZE_LARGE;
private static readonly TimeSpan internCacheCleanupInterval = InternerConstants.DefaultCacheCleanupFreq;
private static Interner<UniqueKey, GrainId> grainIdInternCache;
public UniqueKey.Category Category { get { return Key.IdCategory; } }
public bool IsSystemTarget { get { return Key.IsSystemTargetKey; } }
public bool IsGrain { get { return Category == UniqueKey.Category.Grain || Category == UniqueKey.Category.KeyExtGrain; } }
public bool IsClient { get { return Category == UniqueKey.Category.Client; } }
private GrainId(UniqueKey key)
: base(key)
{
}
public static GrainId NewId()
{
return FindOrCreateGrainId(UniqueKey.NewKey(Guid.NewGuid(), UniqueKey.Category.Grain));
}
public static GrainId NewClientId()
{
return FindOrCreateGrainId(UniqueKey.NewKey(Guid.NewGuid(), UniqueKey.Category.Client));
}
internal static GrainId GetGrainId(UniqueKey key)
{
return FindOrCreateGrainId(key);
}
internal static GrainId GetSystemGrainId(Guid guid)
{
return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.SystemGrain));
}
// For testing only.
internal static GrainId GetGrainIdForTesting(Guid guid)
{
return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.None));
}
internal static GrainId NewSystemTargetGrainIdByTypeCode(int typeData)
{
return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(Guid.NewGuid(), typeData));
}
internal static GrainId GetSystemTargetGrainId(short systemGrainId)
{
return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(systemGrainId));
}
internal static GrainId GetGrainId(long typeCode, long primaryKey, string keyExt=null)
{
return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey,
keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain,
typeCode, keyExt));
}
internal static GrainId GetGrainId(long typeCode, Guid primaryKey, string keyExt=null)
{
return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey,
keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain,
typeCode, keyExt));
}
internal static GrainId GetGrainId(long typeCode, string primaryKey)
{
return FindOrCreateGrainId(UniqueKey.NewKey(0L,
UniqueKey.Category.KeyExtGrain,
typeCode, primaryKey));
}
public Guid PrimaryKey
{
get { return GetPrimaryKey(); }
}
public long PrimaryKeyLong
{
get { return GetPrimaryKeyLong(); }
}
public string PrimaryKeyString
{
get { return GetPrimaryKeyString(); }
}
public string IdentityString
{
get { return ToDetailedString(); }
}
public long GetPrimaryKeyLong(out string keyExt)
{
return Key.PrimaryKeyToLong(out keyExt);
}
[Pure]
internal long GetPrimaryKeyLong()
{
return Key.PrimaryKeyToLong();
}
public Guid GetPrimaryKey(out string keyExt)
{
return Key.PrimaryKeyToGuid(out keyExt);
}
internal Guid GetPrimaryKey()
{
return Key.PrimaryKeyToGuid();
}
internal string GetPrimaryKeyString()
{
string key;
var tmp = GetPrimaryKey(out key);
return key;
}
internal int GetTypeCode()
{
return Key.BaseTypeCode;
}
private static GrainId FindOrCreateGrainId(UniqueKey key)
{
// Note: This is done here to avoid a wierd cyclic dependency / static initialization ordering problem involving the GrainId, Constants & Interner classes
if (grainIdInternCache != null) return grainIdInternCache.FindOrCreate(key, () => new GrainId(key));
lock (lockable)
{
if (grainIdInternCache == null)
{
grainIdInternCache = new Interner<UniqueKey, GrainId>(INTERN_CACHE_INITIAL_SIZE, internCacheCleanupInterval);
}
}
return grainIdInternCache.FindOrCreate(key, () => new GrainId(key));
}
#region IEquatable<GrainId> Members
public bool Equals(GrainId other)
{
return other != null && Key.Equals(other.Key);
}
#endregion
public override bool Equals(UniqueIdentifier obj)
{
var o = obj as GrainId;
return o != null && Key.Equals(o.Key);
}
public override bool Equals(object obj)
{
var o = obj as GrainId;
return o != null && Key.Equals(o.Key);
}
// Keep compiler happy -- it does not like classes to have Equals(...) without GetHashCode() methods
public override int GetHashCode()
{
return Key.GetHashCode();
}
/// <summary>
/// Get a uniformly distributed hash code value for this grain, based on Jenkins Hash function.
/// NOTE: Hash code value may be positive or NEGATIVE.
/// </summary>
/// <returns>Hash code for this GrainId</returns>
public uint GetUniformHashCode()
{
return Key.GetUniformHashCode();
}
public override string ToString()
{
return ToStringImpl(false);
}
// same as ToString, just full primary key and type code
internal string ToDetailedString()
{
return ToStringImpl(true);
}
// same as ToString, just full primary key and type code
private string ToStringImpl(bool detailed)
{
string name = string.Empty;
if (Constants.TryGetSystemGrainName(this, out name))
{
return name;
}
var keyString = Key.ToString();
// this should grab the least-significant half of n1, suffixing it with the key extension.
string idString = keyString;
if (!detailed)
{
if (keyString.Length >= 48)
idString = keyString.Substring(24, 8) + keyString.Substring(48);
else
idString = keyString.Substring(24, 8);
}
string fullString = null;
switch (Category)
{
case UniqueKey.Category.Grain:
case UniqueKey.Category.KeyExtGrain:
var typeString = GetTypeCode().ToString("X");
if (!detailed) typeString = typeString.Tail(8);
fullString = String.Format("*grn/{0}/{1}", typeString, idString);
break;
case UniqueKey.Category.Client:
fullString = "*cli/" + idString;
break;
case UniqueKey.Category.SystemTarget:
string explicitName = Constants.SystemTargetName(this);
if (GetTypeCode() != 0)
{
var typeStr = GetTypeCode().ToString("X");
return String.Format("{0}/{1}/{2}", explicitName, typeStr, idString);
}
fullString = explicitName;
break;
default:
fullString = "???/" + idString;
break;
}
return detailed ? String.Format("{0}-0x{1, 8:X8}", fullString, GetUniformHashCode()) : fullString;
}
internal string ToFullString()
{
string kx;
string pks =
Key.IsLongKey ?
GetPrimaryKeyLong(out kx).ToString(CultureInfo.InvariantCulture) :
GetPrimaryKey(out kx).ToString();
string pksHex =
Key.IsLongKey ?
GetPrimaryKeyLong(out kx).ToString("X") :
GetPrimaryKey(out kx).ToString("X");
return
String.Format(
"[GrainId: {0}, IdCategory: {1}, BaseTypeCode: {2} (x{3}), PrimaryKey: {4} (x{5}), UniformHashCode: {6} (0x{7, 8:X8}){8}]",
ToDetailedString(), // 0
Category, // 1
GetTypeCode(), // 2
GetTypeCode().ToString("X"), // 3
pks, // 4
pksHex, // 5
GetUniformHashCode(), // 6
GetUniformHashCode(), // 7
Key.HasKeyExt ? String.Format(", KeyExtension: {0}", kx) : ""); // 8
}
internal string ToStringWithHashCode()
{
return String.Format("{0}-0x{1, 8:X8}", this.ToString(), this.GetUniformHashCode());
}
/// <summary>
/// Return this GrainId in a standard string form, suitable for later use with the <c>FromParsableString</c> method.
/// </summary>
/// <returns>GrainId in a standard string format.</returns>
internal string ToParsableString()
{
// NOTE: This function must be the "inverse" of FromParsableString, and data must round-trip reliably.
return Key.ToHexString();
}
/// <summary>
/// Create a new GrainId object by parsing string in a standard form returned from <c>ToParsableString</c> method.
/// </summary>
/// <param name="addr">String containing the GrainId info to be parsed.</param>
/// <returns>New GrainId object created from the input data.</returns>
internal static GrainId FromParsableString(string str)
{
// NOTE: This function must be the "inverse" of ToParsableString, and data must round-trip reliably.
var key = UniqueKey.Parse(str);
return FindOrCreateGrainId(key);
}
internal byte[] ToByteArray()
{
var writer = new BinaryTokenStreamWriter();
writer.Write(this);
return writer.ToByteArray();
}
internal static GrainId FromByteArray(byte[] byteArray)
{
var reader = new BinaryTokenStreamReader(byteArray);
return reader.ReadGrainId();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Vevo.Domain;
using Vevo.Domain.Users;
using Vevo.WebUI;
public partial class Components_CountryAndStateList : Vevo.WebUI.International.BaseLanguageUserControl
{
private string _currentCountry;
private string _currentState;
private const string _otherValue = "OT";
private bool _isRequireCountry = false;
private bool _isRequireState = false;
private bool _isCountryWithOther = false;
private bool _isStateWithOther = false;
private string _cssPanel;
private string _cssLabel;
private string _cssInputText;
private string _cssInputDrop;
private string _cssValidate;
private HiddenField _countryHidden = new HiddenField();
private HiddenField _stateHidden = new HiddenField();
private string _countryHiddenID = "uxCountryHidden";
private string _stateHiddenID = "uxStateHidden";
private string GetCountryFormat( string code, string name )
{
return String.Format( "{0}:{1}|", code, name.Replace( "'", "\\'" ) );
}
private string GenerateCountryList()
{
IList<Country> countryList = DataAccessContext.CountryRepository.GetAll( BoolFilter.ShowTrue, "CommonName" );
string result = String.Empty;
for (int index = 0; index < countryList.Count; index++)
{
result += GetCountryFormat( countryList[index].CountryCode, countryList[index].CommonName );
}
return result;
}
private string GetStateFormat( string countryCode, string stateCode, string stateName )
{
return String.Format( "{0}:{1}:{2}|", countryCode, stateCode, stateName.Replace( "'", "\\'" ) );
}
private string GenerateStateList()
{
string result = String.Empty;
IList<Country> countryList = DataAccessContext.CountryRepository.GetAll( BoolFilter.ShowTrue, "CommonName" );
for (int index = 0; index < countryList.Count; index++)
{
IList<State> stateList = DataAccessContext.StateRepository.GetAllByCountryCode(
countryList[index].CountryCode, "StateName", BoolFilter.ShowTrue );
for (int stateIndex = 0; stateIndex < stateList.Count; stateIndex++)
{
result += GetStateFormat( countryList[index].CountryCode, stateList[stateIndex].StateCode, stateList[stateIndex].StateName );
}
}
return result;
}
private void RegisterJavascriptCountryState()
{
string selectCountryText = GetLanguageText( "SelectCountry" );
string selectStateText = GetLanguageText( "SelectState" );
string selectOtherText = GetLanguageText( "SelectOther" );
string script = "<script type=\"text/javascript\">" +
"var defaultValue = document.getElementById( '" + CountryHidden.ClientID + "' );" +
"populateCountry('" + CurrentCountry + "', '" + GenerateCountryList() + "', '" +
uxCountryDrop.ClientID + "', '" + uxCountryText.ClientID + "', '" + selectCountryText +
"', '" + selectOtherText + "' );" +
"populateState('" + CurrentState + "', '" + GenerateStateList() + "', '" + uxStateDrop.ClientID + "', '" +
uxStateText.ClientID + "', '" + CurrentCountry + "', '" + selectStateText + "', '" + selectOtherText + "', '" + uxValidationStatePanel.ClientID + "' );" +
"</script>";
ScriptManager.RegisterStartupScript( Page, GetType(), this.ClientID + "_CountryList", script, false );
script = "var countryText = document.getElementById( '" + uxCountryText.ClientID + "' );" +
"var countryHidden = document.getElementById( '" + CountryHidden.ClientID + "' );" +
"if(this.value == 'OT'){countryText.style.display = '';countryHidden.value = '';countryText.value = '';}" +
"else{countryText.style.display = 'none';countryHidden.value = this.value;}" +
"populateState('" + CurrentState + "', '" + GenerateStateList() + "', '" + uxStateDrop.ClientID + "', '" +
uxStateText.ClientID + "', this.value, '" + selectStateText + "', '" + selectOtherText + "', '" + uxValidationStatePanel.ClientID + "' );";
uxCountryDrop.Attributes.Add( "onchange", script );
script = "var stateText = document.getElementById('" + uxStateText.ClientID + "');" +
"var stateHidden = document.getElementById('" + StateHidden.ClientID + "');" +
"if(this.value == 'OT'){stateText.style.display = '';stateHidden.value = '';stateText.value = '';}" +
"else{stateText.style.display = 'none';stateHidden.value = this.value;}";
uxStateDrop.Attributes.Add( "onchange", script );
script = "var countryHidden = document.getElementById( '" + CountryHidden.ClientID + "' );" +
"countryHidden.value = this.value;";
uxCountryText.Attributes.Add( "onchange", script );
uxCountryText.Attributes.Add( "onBlur", script );
script = "var stateHidden = document.getElementById('" + StateHidden.ClientID + "');" +
"stateHidden.value = this.value;";
uxStateText.Attributes.Add( "onchange", script );
uxStateText.Attributes.Add( "onBlur", script );
}
protected void Page_Load( object sender, EventArgs e )
{
_countryHidden.ID = _countryHiddenID;
uxContryStatePanel.Controls.Add( _countryHidden );
_stateHidden.ID = _stateHiddenID;
uxContryStatePanel.Controls.Add( _stateHidden );
if (IsRequiredCountry)
uxValidationCountryPanel.Style["display"] = "block";
else
uxValidationCountryPanel.Style["display"] = "none";
if (IsRequiredState)
uxStatesAsteriskDiv.Style["display"] = "block";
else
uxStatesAsteriskDiv.Style["display"] = "none";
if (!String.IsNullOrEmpty( CssPanel ))
{
uxContryStatePanel.CssClass = CssPanel;
}
if (!String.IsNullOrEmpty( CssLabel ))
{
uxCountryLabel.CssClass = CssLabel;
uxStateLabel.CssClass = CssLabel;
}
if (!String.IsNullOrEmpty( CssInputText ))
{
uxCountryText.CssClass = CssInputText;
uxStateText.CssClass = CssInputText;
}
if (!String.IsNullOrEmpty( CssInputDrop ))
{
uxCountryDrop.CssClass = CssInputDrop;
uxStateDrop.CssClass = CssInputDrop;
}
if (!String.IsNullOrEmpty( CssValidate ))
{
uxValidationCountryPanel.CssClass = CssValidate;
uxValidationStatePanel.CssClass = CssValidate;
}
}
protected void Page_PreRender( object sender, EventArgs e )
{
if (String.IsNullOrEmpty( _currentCountry ) && !Page.IsPostBack)
{
CurrentCountry = DataAccessContext.Configurations.GetValue( "StoreDefaultCountry", StoreContext.CurrentStore ).ToString();
}
RegisterJavascriptCountryState();
}
private bool CheckItemIfExist( ArrayList arrayList, string item )
{
foreach (string items in arrayList)
{
if (items == item)
return true;
}
return false;
}
protected override void Render( HtmlTextWriter writer )
{
IList<Country> countryList = DataAccessContext.CountryRepository.GetAll( BoolFilter.ShowTrue, "CommonName" );
Page.ClientScript.RegisterForEventValidation( uxCountryDrop.UniqueID, "" );
Page.ClientScript.RegisterForEventValidation( uxCountryDrop.UniqueID, "OT" );
Page.ClientScript.RegisterForEventValidation( uxStateDrop.UniqueID, "" );
Page.ClientScript.RegisterForEventValidation( uxStateDrop.UniqueID, "OT" );
ArrayList stateArrayList = new ArrayList();
for (int index = 0; index < countryList.Count; index++)
{
Page.ClientScript.RegisterForEventValidation( uxCountryDrop.UniqueID, countryList[index].CountryCode );
IList<State> stateList = DataAccessContext.StateRepository.GetAllByCountryCode(
countryList[index].CountryCode, "StateName", BoolFilter.ShowTrue );
for (int stateIndex = 0; stateIndex < stateList.Count; stateIndex++)
{
if (!CheckItemIfExist( stateArrayList, stateList[stateIndex].StateCode ))
Page.ClientScript.RegisterForEventValidation( uxStateDrop.UniqueID, stateList[stateIndex].StateCode );
//result += GetStateFormat( countryList[index].CountryCode, stateList[stateIndex].StateCode, stateList[stateIndex].StateName );
}
}
//Page.ClientScript.RegisterForEventValidation( uxCountryDrop.UniqueID, "AA" );
//Page.ClientScript.RegisterForEventValidation( uxCountryDrop.UniqueID, "Anaconda" );
//ClientScript.RegisterForEventValidation( "DropDownList1", "This is Option 1" );
//ClientScript.RegisterForEventValidation( "DropDownList1", "This is Option 2" );
//ClientScript.RegisterForEventValidation( "DropDownList1", "This is Option 3" );
// Uncomment the line below when you want to specifically register the option for event validation.
// ClientScript.RegisterForEventValidation("DropDownList1", "Is this option registered for event validation?");
base.Render( writer );
}
public string CurrentCountry
{
get
{
return CountryHidden.Value;
}
set
{
_currentCountry = value;
//if (CountryHidden != null)
CountryHidden.Value = _currentCountry;
}
}
public void SetCountryByName( string countryName )
{
Country country = DataAccessContext.CountryRepository.GetOneByName( countryName );
if (country != null)
{
CurrentCountry = country.CountryCode;
}
}
public string CurrentState
{
get
{
return StateHidden.Value;
}
set
{
_currentState = value;
StateHidden.Value = _currentState;
}
}
public bool IsRequiredCountry
{
get { return _isRequireCountry; }
set { _isRequireCountry = value; }
}
public bool IsRequiredState
{
get { return _isRequireState; }
set { _isRequireState = value; }
}
public bool IsCountryWithOther
{
get { return _isCountryWithOther; }
set { _isCountryWithOther = value; }
}
public bool IsStateWithOther
{
get { return _isStateWithOther; }
set { _isStateWithOther = value; }
}
public bool VerifyCountryIsValid
{
get
{
if (String.IsNullOrEmpty( CurrentCountry ))
{
return false;
}
else
{
return true;
}
}
}
public bool VerifyStateIsValid
{
get
{
IList<State> stateList = DataAccessContext.StateRepository.GetAllByCountryCode( CurrentCountry, "StateName", BoolFilter.ShowTrue );
if (stateList.Count != 0)
{
if (String.IsNullOrEmpty( CurrentState ) || CurrentState == "0")
return false;
else
return true;
}
return true;
}
}
public string CssPanel
{
get { return _cssPanel; }
set { _cssPanel = value; }
}
public string CssLabel
{
get { return _cssLabel; }
set { _cssLabel = value; }
}
public string CssInputText
{
get { return _cssInputText; }
set { _cssInputText = value; }
}
public string CssInputDrop
{
get { return _cssInputDrop; }
set { _cssInputDrop = value; }
}
public string CssValidate
{
get { return _cssValidate; }
set { _cssValidate = value; }
}
public bool Validate( out bool validateCountry, out bool validateState )
{
validateCountry = true;
validateState = true;
if (IsRequiredCountry)
{
if (!VerifyCountryIsValid)
{
validateCountry = false;
}
}
if (IsRequiredState)
{
if (!VerifyStateIsValid)
{
validateState = false;
}
}
return validateCountry && validateState;
}
public String FormatErrorHtml( string headerMessage, bool validateCountry, bool validateState )
{
String errorMessage = String.Empty;
if (!validateCountry)
errorMessage += "<li>Required Country</li>";
if (!validateState)
errorMessage += "<li>Required State</li>";
return String.Format( "{0}<ul>{1}</ul>", headerMessage, errorMessage );
}
public String FormatErrorHtml( string headerMessage, bool validateBillingCountry, bool validateBillingState, bool validateShippingCountry, bool validateShippingState )
{
String errorMessage = String.Empty;
if (!validateBillingCountry)
errorMessage += "<li>Required Billing Country</li>";
if (!validateBillingState)
errorMessage += "<li>Required Billing State</li>";
if (!validateShippingCountry)
errorMessage += "<li>Required Shipping Country</li>";
if (!validateShippingState)
errorMessage += "<li>Required Shipping State</li>";
return String.Format( "{0}<ul>{1}</ul>", headerMessage, errorMessage );
}
private HiddenField CountryHidden
{
get { return _countryHidden; }
}
public string CountryHiddenID
{
get { return _countryHiddenID; }
set { _countryHiddenID = value; }
}
private HiddenField StateHidden
{
get { return _stateHidden; }
}
public string StateHiddenID
{
get { return _stateHiddenID; }
set { _stateHiddenID = value; }
}
}
| |
// <copyright file="SafariDriverServer.cs" company="WebDriver Committers">
// Copyright 2015 Software Freedom Conservancy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Safari.Internal;
namespace OpenQA.Selenium.Safari
{
/// <summary>
/// Provides the WebSockets server for communicating with the Safari extension.
/// </summary>
public class SafariDriverServer : ICommandServer
{
private WebSocketServer webSocketServer;
private Queue<SafariDriverConnection> connections = new Queue<SafariDriverConnection>();
private Uri serverUri;
private string temporaryDirectoryPath;
private string safariExecutableLocation;
private Process safariProcess;
private SafariDriverConnection connection;
/// <summary>
/// Initializes a new instance of the <see cref="SafariDriverServer"/> class using the specified options.
/// </summary>
/// <param name="options">The <see cref="SafariOptions"/> defining the browser settings.</param>
public SafariDriverServer(SafariOptions options)
{
int webSocketPort = options.Port;
if (webSocketPort == 0)
{
webSocketPort = PortUtilities.FindFreePort();
}
this.webSocketServer = new WebSocketServer(webSocketPort, "ws://localhost/wd");
this.webSocketServer.Opened += new EventHandler<ConnectionEventArgs>(this.ServerOpenedEventHandler);
this.webSocketServer.Closed += new EventHandler<ConnectionEventArgs>(this.ServerClosedEventHandler);
this.webSocketServer.StandardHttpRequestReceived += new EventHandler<StandardHttpRequestReceivedEventArgs>(this.ServerStandardHttpRequestReceivedEventHandler);
this.serverUri = new Uri(string.Format(CultureInfo.InvariantCulture, "http://localhost:{0}/", webSocketPort.ToString(CultureInfo.InvariantCulture)));
if (string.IsNullOrEmpty(options.SafariLocation))
{
this.safariExecutableLocation = GetDefaultSafariLocation();
}
else
{
this.safariExecutableLocation = options.SafariLocation;
}
}
/// <summary>
/// Starts the server.
/// </summary>
public void Start()
{
this.webSocketServer.Start();
string connectFileName = this.PrepareConnectFile();
this.LaunchSafariProcess(connectFileName);
this.connection = this.WaitForConnection(TimeSpan.FromSeconds(45));
this.DeleteConnectFile();
if (this.connection == null)
{
throw new WebDriverException("Did not receive a connection from the Safari extension. Please verify that it is properly installed and is the proper version.");
}
}
/// <summary>
/// Sends a command to the server.
/// </summary>
/// <param name="commandToSend">The <see cref="Command"/> to send.</param>
/// <returns>The command <see cref="Response"/>.</returns>
public Response SendCommand(Command commandToSend)
{
return this.connection.Send(commandToSend);
}
/// <summary>
/// Waits for a connection to be established with the server by the Safari browser extension.
/// </summary>
/// <param name="timeout">A <see cref="TimeSpan"/> containing the amount of time to wait for the connection.</param>
/// <returns>A <see cref="SafariDriverConnection"/> representing the connection to the browser.</returns>
public SafariDriverConnection WaitForConnection(TimeSpan timeout)
{
SafariDriverConnection foundConnection = null;
DateTime end = DateTime.Now.Add(timeout);
while (this.connections.Count == 0 && DateTime.Now < end)
{
Thread.Sleep(250);
}
if (this.connections.Count > 0)
{
foundConnection = this.connections.Dequeue();
}
return foundConnection;
}
/// <summary>
/// Releases all resources used by the <see cref="SafariDriverServer"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="SafariDriverServer"/> and optionally
/// releases the managed resources.
/// </summary>
/// <param name="disposing"><see langword="true"/> to release managed and resources;
/// <see langword="false"/> to only release unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.webSocketServer.Dispose();
if (this.safariProcess != null)
{
this.CloseSafariProcess();
this.safariProcess.Dispose();
}
}
}
private static string GetDefaultSafariLocation()
{
string safariPath = string.Empty;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
// Safari remains a 32-bit application. Use a hack to look for it
// in the 32-bit program files directory. If a 64-bit version of
// Safari for Windows is released, this needs to be revisited.
string programFilesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
if (Directory.Exists(programFilesDirectory + " (x86)"))
{
programFilesDirectory += " (x86)";
}
safariPath = Path.Combine(programFilesDirectory, Path.Combine("Safari", "safari.exe"));
}
else
{
safariPath = "/Applications/Safari.app/Contents/MacOS/Safari";
}
return safariPath;
}
[SecurityPermission(SecurityAction.Demand)]
private void LaunchSafariProcess(string initialPage)
{
this.safariProcess = new Process();
this.safariProcess.StartInfo.FileName = this.safariExecutableLocation;
this.safariProcess.StartInfo.Arguments = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", initialPage);
this.safariProcess.Start();
}
[SecurityPermission(SecurityAction.Demand)]
private void CloseSafariProcess()
{
if (this.safariProcess != null && !this.safariProcess.HasExited)
{
this.safariProcess.Kill();
while (!this.safariProcess.HasExited)
{
Thread.Sleep(250);
}
}
}
private string PrepareConnectFile()
{
string directoryName = FileUtilities.GenerateRandomTempDirectoryName("SafariDriverConnect.{0}");
this.temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), directoryName);
string tempFileName = Path.Combine(this.temporaryDirectoryPath, "connect.html");
string contents = string.Format(CultureInfo.InvariantCulture, "<!DOCTYPE html><script>window.location = '{0}';</script>", this.serverUri.ToString());
Directory.CreateDirectory(this.temporaryDirectoryPath);
using (FileStream stream = File.Create(tempFileName))
{
stream.Write(Encoding.UTF8.GetBytes(contents), 0, Encoding.UTF8.GetByteCount(contents));
}
return tempFileName;
}
private void DeleteConnectFile()
{
Directory.Delete(this.temporaryDirectoryPath, true);
}
private void ServerOpenedEventHandler(object sender, ConnectionEventArgs e)
{
this.connections.Enqueue(new SafariDriverConnection(e.Connection));
}
private void ServerClosedEventHandler(object sender, ConnectionEventArgs e)
{
}
private void ServerStandardHttpRequestReceivedEventHandler(object sender, StandardHttpRequestReceivedEventArgs e)
{
const string PageSource = @"<!DOCTYPE html>
<script>
window.onload = function() {{
window.postMessage({{
'type': 'connect',
'origin': 'webdriver',
'url': 'ws://localhost:{0}/wd'
}}, '*');
}};
</script>";
string redirectPage = string.Format(CultureInfo.InvariantCulture, PageSource, this.webSocketServer.Port.ToString(CultureInfo.InvariantCulture));
StringBuilder builder = new StringBuilder();
builder.AppendLine("HTTP/1.1 200");
builder.AppendLine("Content-Length: " + redirectPage.Length.ToString(CultureInfo.InvariantCulture));
builder.AppendLine("Connection:close");
builder.AppendLine();
builder.AppendLine(redirectPage);
e.Connection.SendRaw(builder.ToString());
}
}
}
| |
//
// SubSonic - http://subsonicproject.com
//
// The contents of this file are subject to the New BSD
// License (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.opensource.org/licenses/bsd-license.php
//
// Software distributed under the License is distributed on an
// "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
// implied. See the License for the specific language governing
// rights and limitations under the License.
//
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace SubSonic.Extensions
{
/// <summary>
/// Summary for the Validation class
/// </summary>
public static class Validation
{
/// <summary>
/// Determines whether the specified eval string contains only alpha characters.
/// </summary>
/// <param name="evalString">The eval string.</param>
/// <returns>
/// <c>true</c> if the specified eval string is alpha; otherwise, <c>false</c>.
/// </returns>
public static bool IsAlpha(this string evalString)
{
return !Regex.IsMatch(evalString, RegexPattern.ALPHA);
}
/// <summary>
/// Determines whether the specified eval string contains only alphanumeric characters
/// </summary>
/// <param name="evalString">The eval string.</param>
/// <returns>
/// <c>true</c> if the string is alphanumeric; otherwise, <c>false</c>.
/// </returns>
public static bool IsAlphaNumeric(this string evalString)
{
return !Regex.IsMatch(evalString, RegexPattern.ALPHA_NUMERIC);
}
/// <summary>
/// Determines whether the specified eval string contains only alphanumeric characters
/// </summary>
/// <param name="evalString">The eval string.</param>
/// <param name="allowSpaces">if set to <c>true</c> [allow spaces].</param>
/// <returns>
/// <c>true</c> if the string is alphanumeric; otherwise, <c>false</c>.
/// </returns>
public static bool IsAlphaNumeric(this string evalString, bool allowSpaces)
{
if(allowSpaces)
return !Regex.IsMatch(evalString, RegexPattern.ALPHA_NUMERIC_SPACE);
return IsAlphaNumeric(evalString);
}
/// <summary>
/// Determines whether the specified eval string contains only numeric characters
/// </summary>
/// <param name="evalString">The eval string.</param>
/// <returns>
/// <c>true</c> if the string is numeric; otherwise, <c>false</c>.
/// </returns>
public static bool IsNumeric(this string evalString)
{
return !Regex.IsMatch(evalString, RegexPattern.NUMERIC);
}
/// <summary>
/// Determines whether the specified email address string is valid based on regular expression evaluation.
/// </summary>
/// <param name="emailAddressString">The email address string.</param>
/// <returns>
/// <c>true</c> if the specified email address is valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsEmail(this string emailAddressString)
{
return Regex.IsMatch(emailAddressString, RegexPattern.EMAIL);
}
/// <summary>
/// Determines whether the specified string is lower case.
/// </summary>
/// <param name="inputString">The input string.</param>
/// <returns>
/// <c>true</c> if the specified string is lower case; otherwise, <c>false</c>.
/// </returns>
public static bool IsLowerCase(this string inputString)
{
return Regex.IsMatch(inputString, RegexPattern.LOWER_CASE);
}
/// <summary>
/// Determines whether the specified string is upper case.
/// </summary>
/// <param name="inputString">The input string.</param>
/// <returns>
/// <c>true</c> if the specified string is upper case; otherwise, <c>false</c>.
/// </returns>
public static bool IsUpperCase(this string inputString)
{
return Regex.IsMatch(inputString, RegexPattern.UPPER_CASE);
}
/// <summary>
/// Determines whether the specified string is a valid GUID.
/// </summary>
/// <param name="guid">The GUID.</param>
/// <returns>
/// <c>true</c> if the specified string is a valid GUID; otherwise, <c>false</c>.
/// </returns>
public static bool IsGuid(this string guid)
{
return Regex.IsMatch(guid, RegexPattern.GUID);
}
/// <summary>
/// Determines whether the specified string is a valid US Zip Code, using either 5 or 5+4 format.
/// </summary>
/// <param name="zipCode">The zip code.</param>
/// <returns>
/// <c>true</c> if it is a valid zip code; otherwise, <c>false</c>.
/// </returns>
public static bool IsZIPCodeAny(this string zipCode)
{
return Regex.IsMatch(zipCode, RegexPattern.US_ZIPCODE_PLUS_FOUR_OPTIONAL);
}
/// <summary>
/// Determines whether the specified string is a valid US Zip Code, using the 5 digit format.
/// </summary>
/// <param name="zipCode">The zip code.</param>
/// <returns>
/// <c>true</c> if it is a valid zip code; otherwise, <c>false</c>.
/// </returns>
public static bool IsZIPCodeFive(this string zipCode)
{
return Regex.IsMatch(zipCode, RegexPattern.US_ZIPCODE);
}
/// <summary>
/// Determines whether the specified string is a valid US Zip Code, using the 5+4 format.
/// </summary>
/// <param name="zipCode">The zip code.</param>
/// <returns>
/// <c>true</c> if it is a valid zip code; otherwise, <c>false</c>.
/// </returns>
public static bool IsZIPCodeFivePlusFour(this string zipCode)
{
return Regex.IsMatch(zipCode, RegexPattern.US_ZIPCODE_PLUS_FOUR);
}
/// <summary>
/// Determines whether the specified string is a valid Social Security number. Dashes are optional.
/// </summary>
/// <param name="socialSecurityNumber">The Social Security Number</param>
/// <returns>
/// <c>true</c> if it is a valid Social Security number; otherwise, <c>false</c>.
/// </returns>
public static bool IsSocialSecurityNumber(this string socialSecurityNumber)
{
return Regex.IsMatch(socialSecurityNumber, RegexPattern.SOCIAL_SECURITY);
}
/// <summary>
/// Determines whether the specified string is a valid IP address.
/// </summary>
/// <param name="ipAddress">The ip address.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsIPAddress(this string ipAddress)
{
return Regex.IsMatch(ipAddress, RegexPattern.IP_ADDRESS);
}
/// <summary>
/// Determines whether the specified string is a valid US phone number using the referenced regex string.
/// </summary>
/// <param name="telephoneNumber">The telephone number.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsUSTelephoneNumber(this string telephoneNumber)
{
return Regex.IsMatch(telephoneNumber, RegexPattern.US_TELEPHONE);
}
/// <summary>
/// Determines whether the specified string is a valid currency string using the referenced regex string.
/// </summary>
/// <param name="currency">The currency string.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsUSCurrency(this string currency)
{
return Regex.IsMatch(currency, RegexPattern.US_CURRENCY);
}
/// <summary>
/// Determines whether the specified string is a valid URL string using the referenced regex string.
/// </summary>
/// <param name="url">The URL string.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsURL(this string url)
{
return Regex.IsMatch(url, RegexPattern.URL);
}
/// <summary>
/// Determines whether the specified string is consider a strong password based on the supplied string.
/// </summary>
/// <param name="password">The password.</param>
/// <returns>
/// <c>true</c> if strong; otherwise, <c>false</c>.
/// </returns>
public static bool IsStrongPassword(this string password)
{
return Regex.IsMatch(password, RegexPattern.STRONG_PASSWORD);
}
#region Credit Cards
/// <summary>
/// Determines whether the specified string is a valid credit, based on matching any one of the eight credit card strings
/// </summary>
/// <param name="creditCard">The credit card.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsCreditCardAny(this string creditCard)
{
if(CreditPassesFormatCheck(creditCard))
{
creditCard = CleanCreditCardNumber(creditCard);
return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_AMERICAN_EXPRESS) ||
Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_CARTE_BLANCHE) ||
Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_DINERS_CLUB) ||
Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_DISCOVER) ||
Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_EN_ROUTE) ||
Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_JCB) ||
Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_MASTER_CARD) ||
Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_VISA);
}
return false;
}
/// <summary>
/// Determines whether the specified string is an American Express, Discover, MasterCard, or Visa
/// </summary>
/// <param name="creditCard">The credit card.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsCreditCardBigFour(this string creditCard)
{
if(CreditPassesFormatCheck(creditCard))
{
creditCard = CleanCreditCardNumber(creditCard);
return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_AMERICAN_EXPRESS) ||
Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_DISCOVER) ||
Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_MASTER_CARD) ||
Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_VISA);
}
return false;
}
/// <summary>
/// Determines whether the specified string is an American Express card
/// </summary>
/// <param name="creditCard">The credit card.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsCreditCardAmericanExpress(this string creditCard)
{
if(CreditPassesFormatCheck(creditCard))
{
creditCard = CleanCreditCardNumber(creditCard);
return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_AMERICAN_EXPRESS);
}
return false;
}
/// <summary>
/// Determines whether the specified string is an Carte Blanche card
/// </summary>
/// <param name="creditCard">The credit card.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsCreditCardCarteBlanche(this string creditCard)
{
if(CreditPassesFormatCheck(creditCard))
{
creditCard = CleanCreditCardNumber(creditCard);
return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_CARTE_BLANCHE);
}
return false;
}
/// <summary>
/// Determines whether the specified string is an Diner's Club card
/// </summary>
/// <param name="creditCard">The credit card.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsCreditCardDinersClub(this string creditCard)
{
if(CreditPassesFormatCheck(creditCard))
{
creditCard = CleanCreditCardNumber(creditCard);
return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_DINERS_CLUB);
}
return false;
}
/// <summary>
/// Determines whether the specified string is a Discover card
/// </summary>
/// <param name="creditCard">The credit card.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsCreditCardDiscover(this string creditCard)
{
if(CreditPassesFormatCheck(creditCard))
{
creditCard = CleanCreditCardNumber(creditCard);
return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_DISCOVER);
}
return false;
}
/// <summary>
/// Determines whether the specified string is an En Route card
/// </summary>
/// <param name="creditCard">The credit card.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsCreditCardEnRoute(this string creditCard)
{
if(CreditPassesFormatCheck(creditCard))
{
creditCard = CleanCreditCardNumber(creditCard);
return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_EN_ROUTE);
}
return false;
}
/// <summary>
/// Determines whether the specified string is an JCB card
/// </summary>
/// <param name="creditCard">The credit card.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsCreditCardJCB(this string creditCard)
{
if(CreditPassesFormatCheck(creditCard))
{
creditCard = CleanCreditCardNumber(creditCard);
return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_JCB);
}
return false;
}
/// <summary>
/// Determines whether the specified string is a Master Card credit card
/// </summary>
/// <param name="creditCard">The credit card.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsCreditCardMasterCard(this string creditCard)
{
if(CreditPassesFormatCheck(creditCard))
{
creditCard = CleanCreditCardNumber(creditCard);
return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_MASTER_CARD);
}
return false;
}
/// <summary>
/// Determines whether the specified string is Visa card.
/// </summary>
/// <param name="creditCard">The credit card.</param>
/// <returns>
/// <c>true</c> if valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsCreditCardVisa(this string creditCard)
{
if(CreditPassesFormatCheck(creditCard))
{
creditCard = CleanCreditCardNumber(creditCard);
return Regex.IsMatch(creditCard, RegexPattern.CREDIT_CARD_VISA);
}
return false;
}
/// <summary>
/// Cleans the credit card number, returning just the numeric values.
/// </summary>
/// <param name="creditCard">The credit card.</param>
/// <returns></returns>
public static string CleanCreditCardNumber(this string creditCard)
{
Regex regex = new Regex(RegexPattern.CREDIT_CARD_STRIP_NON_NUMERIC, RegexOptions.IgnoreCase | RegexOptions.Singleline);
return regex.Replace(creditCard, String.Empty);
}
/// <summary>
/// Determines whether the credit card number, once cleaned, passes the Luhn algorith.
/// See: http://en.wikipedia.org/wiki/Luhn_algorithm
/// </summary>
/// <param name="creditCardNumber">The credit card number.</param>
/// <returns></returns>
private static bool CreditPassesFormatCheck(this string creditCardNumber)
{
creditCardNumber = CleanCreditCardNumber(creditCardNumber);
if(creditCardNumber.IsInteger())
{
int[] numArray = new int[creditCardNumber.Length];
for(int i = 0; i < numArray.Length; i++)
numArray[i] = Convert.ToInt16(creditCardNumber[i].ToString());
return IsValidLuhn(numArray);
}
return false;
}
/// <summary>
/// Determines whether the specified int array passes the Luhn algorith
/// </summary>
/// <param name="digits">The int array to evaluate</param>
/// <returns>
/// <c>true</c> if it validates; otherwise, <c>false</c>.
/// </returns>
public static bool IsValidLuhn(this int[] digits)
{
int sum = 0;
bool alt = false;
for(int i = digits.Length - 1; i >= 0; i--)
{
if(alt)
{
digits[i] *= 2;
if(digits[i] > 9)
digits[i] -= 9; // equivalent to adding the value of digits
}
sum += digits[i];
alt = !alt;
}
return sum % 10 == 0;
}
/// <summary>
/// Determine whether the passed string is numeric, by attempting to parse it to a double
/// </summary>
/// <param name="str">The string to evaluated for numeric conversion</param>
/// <returns>
/// <c>true</c> if the string can be converted to a number; otherwise, <c>false</c>.
/// </returns>
public static bool IsStringNumeric(this string str)
{
double result;
return (double.TryParse(str, NumberStyles.Float, NumberFormatInfo.CurrentInfo, out result));
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace System.Net
{
// More sophisticated password cache that stores multiple
// name-password pairs and associates these with host/realm.
public class CredentialCache : ICredentials, ICredentialsByHost, IEnumerable
{
private readonly Dictionary<CredentialKey, NetworkCredential> _cache = new Dictionary<CredentialKey, NetworkCredential>();
private readonly Dictionary<CredentialHostKey, NetworkCredential> _cacheForHosts = new Dictionary<CredentialHostKey, NetworkCredential>();
internal int _version;
private int _numbDefaultCredInCache = 0;
// [thread token optimization] The resulting counter of default credential resided in the cache.
internal bool IsDefaultInCache
{
get
{
return _numbDefaultCredInCache != 0;
}
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Net.CredentialCache'/> class.
/// </para>
/// </devdoc>
public CredentialCache()
{
}
/// <devdoc>
/// <para>
/// Adds a <see cref='System.Net.NetworkCredential'/> instance to the credential cache.
/// </para>
/// </devdoc>
public void Add(Uri uriPrefix, string authType, NetworkCredential cred)
{
// Parameter validation
if (uriPrefix == null)
{
throw new ArgumentNullException("uriPrefix");
}
if (authType == null)
{
throw new ArgumentNullException("authType");
}
++_version;
CredentialKey key = new CredentialKey(uriPrefix, authType);
GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + cred.Domain + "],[" + cred.UserName + "]");
_cache.Add(key, cred);
if (cred is SystemNetworkCredential)
{
++_numbDefaultCredInCache;
}
}
public void Add(string host, int port, string authenticationType, NetworkCredential credential)
{
// Parameter validation
if (host == null)
{
throw new ArgumentNullException("host");
}
if (authenticationType == null)
{
throw new ArgumentNullException("authenticationType");
}
if (host.Length == 0)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, "host"));
}
if (port < 0)
{
throw new ArgumentOutOfRangeException("port");
}
++_version;
CredentialHostKey key = new CredentialHostKey(host, port, authenticationType);
GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]");
_cacheForHosts.Add(key, credential);
if (credential is SystemNetworkCredential)
{
++_numbDefaultCredInCache;
}
}
/// <devdoc>
/// <para>
/// Removes a <see cref='System.Net.NetworkCredential'/> instance from the credential cache.
/// </para>
/// </devdoc>
public void Remove(Uri uriPrefix, string authType)
{
if (uriPrefix == null || authType == null)
{
// These couldn't possibly have been inserted into
// the cache because of the test in Add().
return;
}
++_version;
CredentialKey key = new CredentialKey(uriPrefix, authType);
GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");
if (_cache[key] is SystemNetworkCredential)
{
--_numbDefaultCredInCache;
}
_cache.Remove(key);
}
public void Remove(string host, int port, string authenticationType)
{
if (host == null || authenticationType == null)
{
// These couldn't possibly have been inserted into
// the cache because of the test in Add().
return;
}
if (port < 0)
{
return;
}
++_version;
CredentialHostKey key = new CredentialHostKey(host, port, authenticationType);
GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");
if (_cacheForHosts[key] is SystemNetworkCredential)
{
--_numbDefaultCredInCache;
}
_cacheForHosts.Remove(key);
}
/// <devdoc>
/// <para>
/// Returns the <see cref='System.Net.NetworkCredential'/>
/// instance associated with the supplied Uri and
/// authentication type.
/// </para>
/// </devdoc>
public NetworkCredential GetCredential(Uri uriPrefix, string authType)
{
if (uriPrefix == null)
{
throw new ArgumentNullException("uriPrefix");
}
if (authType == null)
{
throw new ArgumentNullException("authType");
}
GlobalLog.Print("CredentialCache::GetCredential(uriPrefix=\"" + uriPrefix + "\", authType=\"" + authType + "\")");
int longestMatchPrefix = -1;
NetworkCredential mostSpecificMatch = null;
IDictionaryEnumerator credEnum = _cache.GetEnumerator();
// Enumerate through every credential in the cache
while (credEnum.MoveNext())
{
CredentialKey key = (CredentialKey)credEnum.Key;
// Determine if this credential is applicable to the current Uri/AuthType
if (key.Match(uriPrefix, authType))
{
int prefixLen = key.UriPrefixLength;
// Check if the match is better than the current-most-specific match
if (prefixLen > longestMatchPrefix)
{
// Yes: update the information about currently preferred match
longestMatchPrefix = prefixLen;
mostSpecificMatch = (NetworkCredential)credEnum.Value;
}
}
}
GlobalLog.Print("CredentialCache::GetCredential returning " + ((mostSpecificMatch == null) ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")"));
return mostSpecificMatch;
}
public NetworkCredential GetCredential(string host, int port, string authenticationType)
{
if (host == null)
{
throw new ArgumentNullException("host");
}
if (authenticationType == null)
{
throw new ArgumentNullException("authenticationType");
}
if (host.Length == 0)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, "host"));
}
if (port < 0)
{
throw new ArgumentOutOfRangeException("port");
}
GlobalLog.Print("CredentialCache::GetCredential(host=\"" + host + ":" + port.ToString() + "\", authenticationType=\"" + authenticationType + "\")");
NetworkCredential match = null;
IDictionaryEnumerator credEnum = _cacheForHosts.GetEnumerator();
// Enumerate through every credential in the cache
while (credEnum.MoveNext())
{
CredentialHostKey key = (CredentialHostKey)credEnum.Key;
// Determine if this credential is applicable to the current Uri/AuthType
if (key.Match(host, port, authenticationType))
{
match = (NetworkCredential)credEnum.Value;
}
}
GlobalLog.Print("CredentialCache::GetCredential returning " + ((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")"));
return match;
}
public IEnumerator GetEnumerator()
{
return new CredentialEnumerator(this, _cache, _cacheForHosts, _version);
}
/// <devdoc>
/// <para>
/// Gets the default system credentials from the <see cref='System.Net.CredentialCache'/>.
/// </para>
/// </devdoc>
public static ICredentials DefaultCredentials
{
get
{
return SystemNetworkCredential.s_defaultCredential;
}
}
public static NetworkCredential DefaultNetworkCredentials
{
get
{
return SystemNetworkCredential.s_defaultCredential;
}
}
private class CredentialEnumerator : IEnumerator
{
private CredentialCache _cache;
private ICredentials[] _array;
private int _index = -1;
private int _version;
internal CredentialEnumerator(CredentialCache cache, Dictionary<CredentialKey, NetworkCredential> table, Dictionary<CredentialHostKey, NetworkCredential> hostTable, int version)
{
_cache = cache;
_array = new ICredentials[table.Count + hostTable.Count];
((ICollection)table.Values).CopyTo(_array, 0);
((ICollection)hostTable.Values).CopyTo(_array, table.Count);
_version = version;
}
object IEnumerator.Current
{
get
{
if (_index < 0 || _index >= _array.Length)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
if (_version != _cache._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
return _array[_index];
}
}
bool IEnumerator.MoveNext()
{
if (_version != _cache._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if (++_index < _array.Length)
{
return true;
}
_index = _array.Length;
return false;
}
void IEnumerator.Reset()
{
_index = -1;
}
}
}
// Abstraction for credentials in password-based
// authentication schemes (basic, digest, NTLM, Kerberos).
//
// Note that this is not applicable to public-key based
// systems such as SSL client authentication.
//
// "Password" here may be the clear text password or it
// could be a one-way hash that is sufficient to
// authenticate, as in HTTP/1.1 digest.
internal class SystemNetworkCredential : NetworkCredential
{
internal static readonly SystemNetworkCredential s_defaultCredential = new SystemNetworkCredential();
// We want reference equality to work. Making this private is a good way to guarantee that.
private SystemNetworkCredential() :
base(string.Empty, string.Empty, string.Empty)
{
}
}
internal class CredentialHostKey
{
public readonly string Host;
public readonly string AuthenticationType;
public readonly int Port;
internal CredentialHostKey(string host, int port, string authenticationType)
{
Host = host;
Port = port;
AuthenticationType = authenticationType;
}
internal bool Match(string host, int port, string authenticationType)
{
if (host == null || authenticationType == null)
{
return false;
}
// If the protocols don't match, this credential is not applicable for the given Uri.
if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase) ||
!string.Equals(Host, host, StringComparison.OrdinalIgnoreCase) ||
port != Port)
{
return false;
}
GlobalLog.Print("CredentialKey::Match(" + Host.ToString() + ":" + Port.ToString() + " & " + host.ToString() + ":" + port.ToString() + ")");
return true;
}
private int _hashCode = 0;
private bool _computedHashCode = false;
public override int GetHashCode()
{
if (!_computedHashCode)
{
// Compute HashCode on demand
_hashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + Host.ToUpperInvariant().GetHashCode() + Port.GetHashCode();
_computedHashCode = true;
}
return _hashCode;
}
public override bool Equals(object comparand)
{
CredentialHostKey comparedCredentialKey = comparand as CredentialHostKey;
if (comparand == null)
{
// This covers also the compared == null case
return false;
}
bool equals =
string.Equals(AuthenticationType, comparedCredentialKey.AuthenticationType, StringComparison.OrdinalIgnoreCase) &&
string.Equals(Host, comparedCredentialKey.Host, StringComparison.OrdinalIgnoreCase) &&
Port == comparedCredentialKey.Port;
GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + comparedCredentialKey.ToString() + ") returns " + equals.ToString());
return equals;
}
public override string ToString()
{
return "[" + Host.Length.ToString(NumberFormatInfo.InvariantInfo) + "]:" + Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + Logging.ObjectToString(AuthenticationType);
}
}
internal class CredentialKey
{
public readonly Uri UriPrefix;
public readonly int UriPrefixLength = -1;
public readonly string AuthenticationType;
private int _hashCode = 0;
private bool _computedHashCode = false;
internal CredentialKey(Uri uriPrefix, string authenticationType)
{
UriPrefix = uriPrefix;
UriPrefixLength = UriPrefix.ToString().Length;
AuthenticationType = authenticationType;
}
internal bool Match(Uri uri, string authenticationType)
{
if (uri == null || authenticationType == null)
{
return false;
}
// If the protocols don't match, this credential is not applicable for the given Uri.
if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase))
{
return false;
}
GlobalLog.Print("CredentialKey::Match(" + UriPrefix.ToString() + " & " + uri.ToString() + ")");
return IsPrefix(uri, UriPrefix);
}
// IsPrefix (Uri)
//
// Determines whether <prefixUri> is a prefix of this URI. A prefix
// match is defined as:
//
// scheme match
// + host match
// + port match, if any
// + <prefix> path is a prefix of <URI> path, if any
//
// Returns:
// True if <prefixUri> is a prefix of this URI
internal bool IsPrefix(Uri uri, Uri prefixUri)
{
if (prefixUri.Scheme != uri.Scheme || prefixUri.Host != uri.Host || prefixUri.Port != uri.Port)
{
return false;
}
int prefixLen = prefixUri.AbsolutePath.LastIndexOf('/');
if (prefixLen > uri.AbsolutePath.LastIndexOf('/'))
{
return false;
}
return String.Compare(uri.AbsolutePath, 0, prefixUri.AbsolutePath, 0, prefixLen, StringComparison.OrdinalIgnoreCase) == 0;
}
public override int GetHashCode()
{
if (!_computedHashCode)
{
// Compute HashCode on demand
_hashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + UriPrefixLength + UriPrefix.GetHashCode();
_computedHashCode = true;
}
return _hashCode;
}
public override bool Equals(object comparand)
{
CredentialKey comparedCredentialKey = comparand as CredentialKey;
if (comparand == null)
{
// This covers also the compared==null case
return false;
}
bool equals =
string.Equals(AuthenticationType, comparedCredentialKey.AuthenticationType, StringComparison.OrdinalIgnoreCase) &&
UriPrefix.Equals(comparedCredentialKey.UriPrefix);
GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + comparedCredentialKey.ToString() + ") returns " + equals.ToString());
return equals;
}
public override string ToString()
{
return "[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + Logging.ObjectToString(UriPrefix) + ":" + Logging.ObjectToString(AuthenticationType);
}
}
}
| |
using System.IO.MemoryMappedFiles;
namespace Tmds.DBus.Protocol;
public static class Address
{
private static bool _systemAddressResolved = false;
private static string? _systemAddress = null;
private static bool _sessionAddressResolved = false;
private static string? _sessionAddress = null;
public static string? System
{
get
{
if (_systemAddressResolved)
{
return _systemAddress;
}
_systemAddress = Environment.GetEnvironmentVariable("DBUS_SYSTEM_BUS_ADDRESS");
if (string.IsNullOrEmpty(_systemAddress) && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_systemAddress = "unix:path=/var/run/dbus/system_bus_socket";
}
_systemAddressResolved = true;
return _systemAddress;
}
}
public static string? Session
{
get
{
if (_sessionAddressResolved)
{
return _sessionAddress;
}
_sessionAddress = Environment.GetEnvironmentVariable("DBUS_SESSION_BUS_ADDRESS");
if (string.IsNullOrEmpty(_sessionAddress))
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_sessionAddress = GetSessionBusAddressFromSharedMemory();
}
else
{
_sessionAddress = GetSessionBusAddressFromX11();
}
}
_sessionAddressResolved = true;
return _sessionAddress;
}
}
private static string? GetSessionBusAddressFromX11()
{
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DISPLAY")))
{
var display = XOpenDisplay(null);
if (display == IntPtr.Zero)
{
return null;
}
string username;
unsafe
{
const int BufLen = 1024;
byte* stackBuf = stackalloc byte[BufLen];
Passwd passwd;
IntPtr result;
getpwuid_r(getuid(), out passwd, stackBuf, BufLen, out result);
if (result != IntPtr.Zero)
{
username = Marshal.PtrToStringAnsi(passwd.Name)!;
}
else
{
return null;
}
}
var machineId = DBusEnvironment.MachineId.Replace("-", string.Empty);
var selectionName = $"_DBUS_SESSION_BUS_SELECTION_{username}_{machineId}";
var selectionAtom = XInternAtom(display, selectionName, false);
if (selectionAtom == IntPtr.Zero)
{
return null;
}
var owner = XGetSelectionOwner(display, selectionAtom);
if (owner == IntPtr.Zero)
{
return null;
}
var addressAtom = XInternAtom(display, "_DBUS_SESSION_BUS_ADDRESS", false);
if (addressAtom == IntPtr.Zero)
{
return null;
}
IntPtr actualReturnType;
IntPtr actualReturnFormat;
IntPtr nrItemsReturned;
IntPtr bytesAfterReturn;
IntPtr propReturn;
int rv = XGetWindowProperty(display, owner, addressAtom, 0, 1024, false, (IntPtr)31 /* XA_STRING */,
out actualReturnType, out actualReturnFormat, out nrItemsReturned, out bytesAfterReturn, out propReturn);
string? address = rv == 0 ? Marshal.PtrToStringAnsi(propReturn) : null;
if (propReturn != IntPtr.Zero)
{
XFree(propReturn);
}
XCloseDisplay(display);
return address;
}
else
{
return null;
}
}
private static string? GetSessionBusAddressFromSharedMemory()
{
string? result = ReadSharedMemoryString("DBusDaemonAddressInfo", 255);
if (string.IsNullOrEmpty(result))
{
result = ReadSharedMemoryString("DBusDaemonAddressInfoDebug", 255);
}
return result;
}
private static string? ReadSharedMemoryString(string id, long maxlen = -1)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return null;
}
MemoryMappedFile? shmem;
try
{
shmem = MemoryMappedFile.OpenExisting(id);
}
catch
{
shmem = null;
}
if (shmem == null)
{
return null;
}
MemoryMappedViewStream s = shmem.CreateViewStream();
long len = s.Length;
if (maxlen >= 0 && len > maxlen)
{
len = maxlen;
}
if (len == 0)
{
return string.Empty;
}
if (len > Int32.MaxValue)
{
len = Int32.MaxValue;
}
byte[] bytes = new byte[len];
int count = s.Read(bytes, 0, (int)len);
if (count <= 0)
{
return string.Empty;
}
count = 0;
while (count < len && bytes[count] != 0)
{
count++;
}
return Encoding.UTF8.GetString(bytes, 0, count);
}
struct Passwd
{
public IntPtr Name;
public IntPtr Password;
public uint UserID;
public uint GroupID;
public IntPtr UserInfo;
public IntPtr HomeDir;
public IntPtr Shell;
}
[DllImport("libc")]
private static extern unsafe int getpwuid_r(uint uid, out Passwd pwd, byte* buf, int bufLen, out IntPtr result);
[DllImport("libc")]
private static extern uint getuid();
[DllImport("libX11")]
private static extern IntPtr XOpenDisplay(string? name);
[DllImport("libX11")]
private static extern int XCloseDisplay(IntPtr display);
[DllImport("libX11")]
private static extern IntPtr XInternAtom(IntPtr display, string atom_name, bool only_if_exists);
[DllImport("libX11")]
private static extern int XGetWindowProperty(IntPtr display, IntPtr w, IntPtr property,
int long_offset, int long_length, bool delete, IntPtr req_type,
out IntPtr actual_type_return, out IntPtr actual_format_return,
out IntPtr nitems_return, out IntPtr bytes_after_return, out IntPtr prop_return);
[DllImport("libX11")]
private static extern int XFree(IntPtr data);
[DllImport("libX11")]
private static extern IntPtr XGetSelectionOwner(IntPtr display, IntPtr Atom);
}
| |
// ============================================================================
// FileName: MainConsole.cs
//
// Description:
// Main console display for the demonstration SIP Proxy.
//
// Author(s):
// Aaron Clauson
//
// History:
// 13 Aug 2006 Aaron Clauson Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2006 Aaron Clauson ([email protected]), Blue Face Ltd, Dublin, Ireland (www.blueface.ie)
// 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 Blue Face Ltd.
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// ============================================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security;
using System.ServiceProcess;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using SIPSorcery.AppServer.DialPlan;
using SIPSorcery.CRM;
using SIPSorcery.Net;
using SIPSorcery.Persistence;
using SIPSorcery.Servers;
using SIPSorcery.SIP;
using SIPSorcery.SIP.App;
using SIPSorcery.Sys;
using SIPSorcery.Web.Services;
using log4net;
namespace SIPSorcery.SIPAppServer
{
public class SIPAppServerDaemon
{
private static ILog logger = SIPAppServerState.logger;
private static ILog dialPlanLogger = AppState.GetLogger("dialplan");
private XmlNode m_sipAppServerSocketsNode = SIPAppServerState.SIPAppServerSocketsNode;
private static int m_monitorEventLoopbackPort = SIPAppServerState.MonitorLoopbackPort;
private string m_traceDirectory = SIPAppServerState.TraceDirectory;
private string m_currentDirectory = AppState.CurrentDirectory;
private string m_rubyScriptCommonPath = SIPAppServerState.RubyScriptCommonPath;
private SIPEndPoint m_outboundProxy = SIPAppServerState.OutboundProxy;
private string m_dialplanImpersonationUsername = SIPAppServerState.DialPlanEngineImpersonationUsername;
private string m_dialplanImpersonationPassword = SIPAppServerState.DialPlanEngineImpersonationPassword;
private int m_dailyCallLimit = SIPAppServerState.DailyCallLimit;
private int m_maxDialPlanExecutionLimit = SIPAppServerState.DialPlanMaxExecutionLimit;
private SIPSorceryPersistor m_sipSorceryPersistor;
private SIPSorcery.Entities.CDRDataLayer m_cdrDataLayer;
private SIPMonitorEventWriter m_monitorEventWriter;
private SIPAppServerCore m_appServerCore;
private SIPCallManager m_callManager;
private SIPDialogueManager m_sipDialogueManager;
private SIPTransport m_sipTransport;
private DialPlanEngine m_dialPlanEngine;
private ServiceHost m_callManagerSvcHost;
private CustomerSessionManager m_customerSessionManager;
private StorageTypes m_storageType;
private string m_connectionString;
private SIPEndPoint m_appServerEndPoint;
private string m_callManagerServiceAddress;
private bool m_monitorCalls; // If true this app server instance will monitor the sip dialogues table for expired calls to hangup.
public SIPAppServerDaemon(StorageTypes storageType, string connectionString)
{
m_storageType = storageType;
m_connectionString = connectionString;
m_monitorCalls = true;
}
public SIPAppServerDaemon(
StorageTypes storageType,
string connectionString,
SIPEndPoint appServerEndPoint,
string callManagerServiceAddress,
bool monitorCalls)
{
m_storageType = storageType;
m_connectionString = connectionString;
m_appServerEndPoint = appServerEndPoint;
m_callManagerServiceAddress = callManagerServiceAddress;
m_monitorCalls = monitorCalls;
}
public void Start()
{
try
{
logger.Debug("pid=" + Process.GetCurrentProcess().Id + ".");
logger.Debug("os=" + System.Environment.OSVersion + ".");
logger.Debug("current directory=" + m_currentDirectory + ".");
logger.Debug("base directory=" + AppDomain.CurrentDomain.BaseDirectory + ".");
SIPDNSManager.SIPMonitorLogEvent = FireSIPMonitorEvent;
m_sipSorceryPersistor = new SIPSorceryPersistor(m_storageType, m_connectionString);
m_customerSessionManager = new CustomerSessionManager(m_storageType, m_connectionString);
m_cdrDataLayer = new Entities.CDRDataLayer();
#region Initialise the SIP Application Server and its logging mechanisms including CDRs.
logger.Debug("Initiating SIP Application Server Agent.");
// Send events from this process to the monitoring socket.
if (m_monitorEventLoopbackPort != 0)
{
m_monitorEventWriter = new SIPMonitorEventWriter(m_monitorEventLoopbackPort);
}
if (m_cdrDataLayer != null)
{
SIPCDR.CDRCreated += m_cdrDataLayer.Add;
SIPCDR.CDRAnswered += m_cdrDataLayer.Update;
SIPCDR.CDRHungup += m_cdrDataLayer.Update;
SIPCDR.CDRUpdated += m_cdrDataLayer.Update;
}
#region Initialise the SIPTransport layers.
m_sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine(), true);
if (m_appServerEndPoint != null)
{
if (m_appServerEndPoint.Protocol == SIPProtocolsEnum.udp)
{
logger.Debug("Using single SIP transport socket for App Server " + m_appServerEndPoint.ToString() + ".");
m_sipTransport.AddSIPChannel(new SIPUDPChannel(m_appServerEndPoint.GetIPEndPoint()));
}
else if (m_appServerEndPoint.Protocol == SIPProtocolsEnum.tcp)
{
logger.Debug("Using single SIP transport socket for App Server " + m_appServerEndPoint.ToString() + ".");
m_sipTransport.AddSIPChannel(new SIPTCPChannel(m_appServerEndPoint.GetIPEndPoint()));
}
else
{
throw new ApplicationException("The SIP End Point of " + m_appServerEndPoint + " cannot be used with the App Server transport layer.");
}
}
else if (m_sipAppServerSocketsNode != null)
{
m_sipTransport.AddSIPChannel(SIPTransportConfig.ParseSIPChannelsNode(m_sipAppServerSocketsNode));
}
else
{
throw new ApplicationException("The SIP App Server could not be started, no SIP sockets have been configured.");
}
m_sipTransport.SIPRequestInTraceEvent += LogSIPRequestIn;
m_sipTransport.SIPRequestOutTraceEvent += LogSIPRequestOut;
m_sipTransport.SIPResponseInTraceEvent += LogSIPResponseIn;
m_sipTransport.SIPResponseOutTraceEvent += LogSIPResponseOut;
m_sipTransport.SIPBadRequestInTraceEvent += LogSIPBadRequestIn;
m_sipTransport.SIPBadResponseInTraceEvent += LogSIPBadResponseIn;
#endregion
m_dialPlanEngine = new DialPlanEngine(
m_sipTransport,
m_sipSorceryPersistor.SIPDomainManager.GetDomain,
FireSIPMonitorEvent,
m_sipSorceryPersistor,
m_outboundProxy,
m_rubyScriptCommonPath,
m_dialplanImpersonationUsername,
m_dialplanImpersonationPassword,
m_maxDialPlanExecutionLimit);
m_sipDialogueManager = new SIPDialogueManager(
m_sipTransport,
m_outboundProxy,
FireSIPMonitorEvent,
m_sipSorceryPersistor.SIPDialoguePersistor,
m_sipSorceryPersistor.SIPCDRPersistor,
SIPRequestAuthenticator.AuthenticateSIPRequest,
m_sipSorceryPersistor.SIPAccountsPersistor.Get,
m_sipSorceryPersistor.SIPDomainManager.GetDomain);
m_callManager = new SIPCallManager(
m_sipTransport,
m_outboundProxy,
FireSIPMonitorEvent,
m_sipDialogueManager,
m_sipSorceryPersistor.SIPDialoguePersistor,
m_sipSorceryPersistor.SIPCDRPersistor,
m_dialPlanEngine,
m_sipSorceryPersistor.SIPDialPlanPersistor.Get,
m_sipSorceryPersistor.SIPAccountsPersistor.Get,
m_sipSorceryPersistor.SIPRegistrarBindingPersistor.Get,
m_sipSorceryPersistor.SIPProvidersPersistor.Get,
m_sipSorceryPersistor.SIPDomainManager.GetDomain,
m_customerSessionManager.CustomerPersistor,
m_sipSorceryPersistor.SIPDialPlanPersistor,
m_traceDirectory,
m_monitorCalls,
m_dailyCallLimit);
m_callManager.Start();
m_appServerCore = new SIPAppServerCore(
m_sipTransport,
m_sipSorceryPersistor.SIPDomainManager.GetDomain,
m_sipSorceryPersistor.SIPAccountsPersistor.Get,
FireSIPMonitorEvent,
m_callManager,
m_sipDialogueManager,
SIPRequestAuthenticator.AuthenticateSIPRequest,
m_outboundProxy);
#endregion
#region Initialise WCF services.
try
{
if (WCFUtility.DoesWCFServiceExist(typeof(CallManagerServices).FullName.ToString()))
{
CallManagerServiceInstanceProvider callManagerSvcInstanceProvider = new CallManagerServiceInstanceProvider(m_callManager, m_sipDialogueManager);
Uri callManagerBaseAddress = null;
if (m_callManagerServiceAddress != null)
{
logger.Debug("Adding service address to Call Manager Service " + m_callManagerServiceAddress + ".");
callManagerBaseAddress = new Uri(m_callManagerServiceAddress);
}
if (callManagerBaseAddress != null)
{
m_callManagerSvcHost = new ServiceHost(typeof(CallManagerServices), callManagerBaseAddress);
}
else
{
m_callManagerSvcHost = new ServiceHost(typeof(CallManagerServices));
}
m_callManagerSvcHost.Description.Behaviors.Add(callManagerSvcInstanceProvider);
m_callManagerSvcHost.Open();
logger.Debug("CallManager hosted service successfully started on " + m_callManagerSvcHost.BaseAddresses[0].AbsoluteUri + ".");
}
}
catch (Exception excp)
{
logger.Warn("Exception starting CallManager hosted service. " + excp.Message);
}
#endregion
}
catch (Exception excp)
{
logger.Error("Exception SIPAppServerDaemon Start. " + excp.Message);
throw excp;
}
}
public void Stop()
{
try
{
logger.Debug("SIP Application Server stopping...");
DNSManager.Stop();
m_dialPlanEngine.StopScriptMonitoring = true;
if (m_callManagerSvcHost != null)
{
m_callManagerSvcHost.Close();
}
if (m_callManager != null)
{
m_callManager.Stop();
}
if (m_monitorEventWriter != null)
{
m_monitorEventWriter.Close();
}
// Shutdown the SIPTransport layer.
m_sipTransport.Shutdown();
m_sipSorceryPersistor.StopCDRWrites = true;
logger.Debug("SIP Application Server stopped.");
}
catch (Exception excp)
{
logger.Error("Exception SIPAppServerDaemon Stop." + excp.Message);
}
}
#region Logging functions.
private void FireSIPMonitorEvent(SIPMonitorEvent sipMonitorEvent)
{
try
{
if (sipMonitorEvent != null && m_monitorEventWriter != null)
{
if (sipMonitorEvent is SIPMonitorConsoleEvent)
{
SIPMonitorConsoleEvent consoleEvent = sipMonitorEvent as SIPMonitorConsoleEvent;
if (consoleEvent.ServerType == SIPMonitorServerTypesEnum.RegisterAgent ||
(consoleEvent.EventType != SIPMonitorEventTypesEnum.FullSIPTrace &&
consoleEvent.EventType != SIPMonitorEventTypesEnum.SIPTransaction &&
consoleEvent.EventType != SIPMonitorEventTypesEnum.Timing &&
consoleEvent.EventType != SIPMonitorEventTypesEnum.UnrecognisedMessage &&
consoleEvent.EventType != SIPMonitorEventTypesEnum.ContactRegisterInProgress &&
consoleEvent.EventType != SIPMonitorEventTypesEnum.Monitor))
{
string eventUsername = (sipMonitorEvent.Username.IsNullOrBlank()) ? null : " " + sipMonitorEvent.Username;
dialPlanLogger.Debug("as (" + DateTime.Now.ToString("mm:ss:fff") + eventUsername + "): " + sipMonitorEvent.Message);
}
if (consoleEvent.EventType != SIPMonitorEventTypesEnum.SIPTransaction)
{
m_monitorEventWriter.Send(sipMonitorEvent);
}
}
else
{
m_monitorEventWriter.Send(sipMonitorEvent);
}
}
}
catch (Exception excp)
{
logger.Error("Exception FireSIPMonitorEvent. " + excp.Message);
}
}
private void LogSIPRequestIn(SIPEndPoint localSIPEndPoint, SIPEndPoint endPoint, SIPRequest sipRequest)
{
string message = "App Svr Received: " + localSIPEndPoint.ToString() + "<-" + endPoint.ToString() + "\r\n" + sipRequest.ToString();
//logger.Debug("as: request in " + sipRequest.Method + " " + localSIPEndPoint.ToString() + "<-" + endPoint.ToString() + ", callid=" + sipRequest.Header.CallId + ".");
string fromUser = (sipRequest.Header.From != null && sipRequest.Header.From.FromURI != null) ? sipRequest.Header.From.FromURI.User : "Error on From header";
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, message, fromUser, localSIPEndPoint, endPoint));
}
private void LogSIPRequestOut(SIPEndPoint localSIPEndPoint, SIPEndPoint endPoint, SIPRequest sipRequest)
{
string message = "App Svr Sent: " + localSIPEndPoint.ToString() + "->" + endPoint.ToString() + "\r\n" + sipRequest.ToString();
//logger.Debug("as: request out " + sipRequest.Method + " " + localSIPEndPoint.ToString() + "->" + endPoint.ToString() + ", callid=" + sipRequest.Header.CallId + ".");
string fromUser = (sipRequest.Header.From != null && sipRequest.Header.From.FromURI != null) ? sipRequest.Header.From.FromURI.User : "Error on From header";
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, message, fromUser, localSIPEndPoint, endPoint));
}
private void LogSIPResponseIn(SIPEndPoint localSIPEndPoint, SIPEndPoint endPoint, SIPResponse sipResponse)
{
string message = "App Svr Received: " + localSIPEndPoint.ToString() + "<-" + endPoint.ToString() + "\r\n" + sipResponse.ToString();
//logger.Debug("as: response in " + sipResponse.Header.CSeqMethod + " " + localSIPEndPoint.ToString() + "<-" + endPoint.ToString() + ", callid=" + sipResponse.Header.CallId + ".");
string fromUser = (sipResponse.Header.From != null && sipResponse.Header.From.FromURI != null) ? sipResponse.Header.From.FromURI.User : "Error on From header";
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, message, fromUser, localSIPEndPoint, endPoint));
}
private void LogSIPResponseOut(SIPEndPoint localSIPEndPoint, SIPEndPoint endPoint, SIPResponse sipResponse)
{
string message = "App Svr Sent: " + localSIPEndPoint.ToString() + "->" + endPoint.ToString() + "\r\n" + sipResponse.ToString();
//logger.Debug("as: response out " + sipResponse.Header.CSeqMethod + " " + localSIPEndPoint.ToString() + "->" + endPoint.ToString() + ", callid=" + sipResponse.Header.CallId + ".");
string fromUser = (sipResponse.Header.From != null && sipResponse.Header.From.FromURI != null) ? sipResponse.Header.From.FromURI.User : "Error on From header";
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, message, fromUser, localSIPEndPoint, endPoint));
}
private void LogSIPBadRequestIn(SIPEndPoint localSIPEndPoint, SIPEndPoint endPoint, string sipMessage, SIPValidationFieldsEnum errorField, string rawMessage)
{
string errorMessage = "App Svr Bad Request Received: " + localSIPEndPoint + "<-" + endPoint.ToString() + ", " + errorField + ". " + sipMessage;
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.BadSIPMessage, errorMessage, null));
if (rawMessage != null)
{
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, errorMessage + "\r\n" + rawMessage, null));
}
}
private void LogSIPBadResponseIn(SIPEndPoint localSIPEndPoint, SIPEndPoint endPoint, string sipMessage, SIPValidationFieldsEnum errorField, string rawMessage)
{
string errorMessage = "App Svr Bad Response Received: " + localSIPEndPoint + "<-" + endPoint.ToString() + ", " + errorField + ". " + sipMessage;
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.BadSIPMessage, errorMessage, null));
if (rawMessage != null)
{
FireSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, errorMessage + "\r\n" + rawMessage, null));
}
}
#endregion
}
}
| |
using System.Collections.Generic;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
{
/// <summary>
/// Tag service to query for tags in the tags db table. The tags returned are only relevant for published content & saved media or members
/// </summary>
/// <remarks>
/// If there is unpublished content with tags, those tags will not be contained
/// </remarks>
public class TagService : ITagService
{
private readonly RepositoryFactory _repositoryFactory;
private readonly IDatabaseUnitOfWorkProvider _uowProvider;
public TagService()
: this(new RepositoryFactory())
{}
public TagService(RepositoryFactory repositoryFactory)
: this(new PetaPocoUnitOfWorkProvider(), repositoryFactory)
{
}
public TagService(IDatabaseUnitOfWorkProvider provider)
: this(provider, new RepositoryFactory())
{
}
public TagService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory)
{
_repositoryFactory = repositoryFactory;
_uowProvider = provider;
}
/// <summary>
/// Gets tagged Content by a specific 'Tag Group'.
/// </summary>
/// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Content, not the actual Content item.</remarks>
/// <param name="tagGroup">Name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="TaggedEntity"/></returns>
public IEnumerable<TaggedEntity> GetTaggedContentByTagGroup(string tagGroup)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, tagGroup);
}
}
/// <summary>
/// Gets tagged Content by a specific 'Tag' and optional 'Tag Group'.
/// </summary>
/// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Content, not the actual Content item.</remarks>
/// <param name="tag">Tag</param>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="TaggedEntity"/></returns>
public IEnumerable<TaggedEntity> GetTaggedContentByTag(string tag, string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, tag, tagGroup);
}
}
/// <summary>
/// Gets tagged Media by a specific 'Tag Group'.
/// </summary>
/// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Media, not the actual Media item.</remarks>
/// <param name="tagGroup">Name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="TaggedEntity"/></returns>
public IEnumerable<TaggedEntity> GetTaggedMediaByTagGroup(string tagGroup)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, tagGroup);
}
}
/// <summary>
/// Gets tagged Media by a specific 'Tag' and optional 'Tag Group'.
/// </summary>
/// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Media, not the actual Media item.</remarks>
/// <param name="tag">Tag</param>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="TaggedEntity"/></returns>
public IEnumerable<TaggedEntity> GetTaggedMediaByTag(string tag, string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Media, tag, tagGroup);
}
}
/// <summary>
/// Gets tagged Members by a specific 'Tag Group'.
/// </summary>
/// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Member, not the actual Member item.</remarks>
/// <param name="tagGroup">Name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="TaggedEntity"/></returns>
public IEnumerable<TaggedEntity> GetTaggedMembersByTagGroup(string tagGroup)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Member, tagGroup);
}
}
/// <summary>
/// Gets tagged Members by a specific 'Tag' and optional 'Tag Group'.
/// </summary>
/// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Member, not the actual Member item.</remarks>
/// <param name="tag">Tag</param>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="TaggedEntity"/></returns>
public IEnumerable<TaggedEntity> GetTaggedMembersByTag(string tag, string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Member, tag, tagGroup);
}
}
/// <summary>
/// Gets every tag stored in the database
/// </summary>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="ITag"/></returns>
public IEnumerable<ITag> GetAllTags(string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTagsForEntityType(TaggableObjectTypes.All, tagGroup);
}
}
/// <summary>
/// Gets all tags for content items
/// </summary>
/// <remarks>Use the optional tagGroup parameter to limit the
/// result to a specific 'Tag Group'.</remarks>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="ITag"/></returns>
public IEnumerable<ITag> GetAllContentTags(string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTagsForEntityType(TaggableObjectTypes.Content, tagGroup);
}
}
/// <summary>
/// Gets all tags for media items
/// </summary>
/// <remarks>Use the optional tagGroup parameter to limit the
/// result to a specific 'Tag Group'.</remarks>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="ITag"/></returns>
public IEnumerable<ITag> GetAllMediaTags(string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTagsForEntityType(TaggableObjectTypes.Media, tagGroup);
}
}
/// <summary>
/// Gets all tags for member items
/// </summary>
/// <remarks>Use the optional tagGroup parameter to limit the
/// result to a specific 'Tag Group'.</remarks>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="ITag"/></returns>
public IEnumerable<ITag> GetAllMemberTags(string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTagsForEntityType(TaggableObjectTypes.Member, tagGroup);
}
}
/// <summary>
/// Gets all tags attached to a property by entity id
/// </summary>
/// <remarks>Use the optional tagGroup parameter to limit the
/// result to a specific 'Tag Group'.</remarks>
/// <param name="contentId">The content item id to get tags for</param>
/// <param name="propertyTypeAlias">Property type alias</param>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="ITag"/></returns>
public IEnumerable<ITag> GetTagsForProperty(int contentId, string propertyTypeAlias, string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTagsForProperty(contentId, propertyTypeAlias, tagGroup);
}
}
/// <summary>
/// Gets all tags attached to an entity (content, media or member) by entity id
/// </summary>
/// <remarks>Use the optional tagGroup parameter to limit the
/// result to a specific 'Tag Group'.</remarks>
/// <param name="contentId">The content item id to get tags for</param>
/// <param name="tagGroup">Optional name of the 'Tag Group'</param>
/// <returns>An enumerable list of <see cref="ITag"/></returns>
public IEnumerable<ITag> GetTagsForEntity(int contentId, string tagGroup = null)
{
using (var repository = _repositoryFactory.CreateTagRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetTagsForEntity(contentId, tagGroup);
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using WampSharp.Core.Serialization;
using WampSharp.V2.Core.Contracts;
namespace WampSharp.V2.PubSub
{
internal abstract class MatchTopicContainer
{
#region Fields
private readonly ConcurrentDictionary<string, WampTopic> mTopicUriToSubject;
private readonly object mLock = new object();
#endregion
#region Constructor
/// <summary>
/// Creates a new instance of <see cref="WampTopicContainer"/>.
/// </summary>
public MatchTopicContainer()
{
mTopicUriToSubject =
new ConcurrentDictionary<string, WampTopic>();
}
#endregion
#region Public Methods
public IEnumerable<string> TopicUris
{
get { return mTopicUriToSubject.Keys; }
}
public IEnumerable<IWampTopic> Topics
{
get { return mTopicUriToSubject.Values; }
}
public IDisposable Subscribe(IWampRawTopicRouterSubscriber subscriber, string topicUri, SubscribeOptions options)
{
lock (mLock)
{
IWampTopic topic = GetOrCreateTopicByUri(topicUri);
return topic.Subscribe(subscriber);
}
}
public bool Publish<TMessage>(IWampFormatter<TMessage> formatter,
long publicationId,
PublishOptions options,
string topicUri)
{
return PublishSafe(topicUri,
topic =>
topic.Publish(formatter, publicationId, options));
}
public bool Publish<TMessage>(IWampFormatter<TMessage> formatter,
long publicationId,
PublishOptions options,
string topicUri,
TMessage[] arguments)
{
return PublishSafe(topicUri,
topic =>
topic.Publish(formatter, publicationId, options, arguments));
}
public bool Publish<TMessage>(IWampFormatter<TMessage> formatter,
long publicationId,
PublishOptions options,
string topicUri,
TMessage[] arguments,
IDictionary<string, TMessage> argumentKeywords)
{
return PublishSafe(topicUri,
topic =>
topic.Publish(formatter, publicationId, options, arguments, argumentKeywords));
}
private bool PublishSafe
(string topicUri, Action<IWampTopic> invoker)
{
lock (mLock)
{
bool anyTopics = false;
IEnumerable<IWampTopic> topics = GetMatchingTopics(topicUri);
foreach (IWampTopic topic in topics)
{
anyTopics = true;
invoker(topic);
}
return anyTopics;
}
}
public IWampTopic CreateTopicByUri(string topicUri, bool persistent)
{
WampTopic wampTopic = CreateWampTopic(topicUri, persistent);
IDictionary<string, WampTopic> casted = mTopicUriToSubject;
casted.Add(topicUri, wampTopic);
RaiseTopicCreated(wampTopic);
return wampTopic;
}
public IWampTopic GetOrCreateTopicByUri(string topicUri)
{
// Pretty ugly.
bool created = false;
WampTopic result =
mTopicUriToSubject.GetOrAdd(topicUri,
key =>
{
WampTopic topic = CreateWampTopic(topicUri, false);
created = true;
return topic;
});
if (created)
{
RaiseTopicCreated(result);
}
return result;
}
public IWampTopic GetTopicByUri(string topicUri)
{
WampTopic result;
if (mTopicUriToSubject.TryGetValue(topicUri, out result))
{
return result;
}
return null;
}
public bool TryRemoveTopicByUri(string topicUri, out IWampTopic topic)
{
WampTopic value;
bool result = mTopicUriToSubject.TryRemove(topicUri, out value);
topic = value;
if (result)
{
RaiseTopicRemoved(topic);
}
return result;
}
#endregion
#region Private Methods
private WampTopic CreateWampTopic(string topicUri, bool persistent)
{
WampTopic topic = new WampTopic(topicUri, persistent);
// Non persistent topics die when they are empty :)
if (!persistent)
{
topic.TopicEmpty += OnTopicEmpty;
}
return topic;
}
private void OnTopicEmpty(object sender, EventArgs e)
{
lock (mLock)
{
IWampTopic topic = sender as IWampTopic;
if (!topic.HasSubscribers)
{
topic.TopicEmpty -= OnTopicEmpty;
topic.Dispose();
IWampTopic deletedTopic;
TryRemoveTopicByUri(topic.TopicUri, out deletedTopic);
}
}
}
#endregion
#region Events
public event EventHandler<WampTopicCreatedEventArgs> TopicCreated;
public event EventHandler<WampTopicRemovedEventArgs> TopicRemoved;
private void RaiseTopicCreated(IWampTopic wampTopic)
{
EventHandler<WampTopicCreatedEventArgs> topicCreated = TopicCreated;
if (topicCreated != null)
{
topicCreated(this, new WampTopicCreatedEventArgs(wampTopic));
}
}
private void RaiseTopicRemoved(IWampTopic topic)
{
EventHandler<WampTopicRemovedEventArgs> topicRemoved = TopicRemoved;
if (topicRemoved != null)
{
topicRemoved(this, new WampTopicRemovedEventArgs(topic));
}
}
#endregion
#region Abstract Methods
public abstract IWampCustomizedSubscriptionId GetSubscriptionId(string topicUri, SubscribeOptions options);
protected abstract IEnumerable<IWampTopic> GetMatchingTopics(string criteria);
public abstract bool Handles(SubscribeOptions options);
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="TestSubscriber.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Actor;
using Akka.Event;
using Akka.TestKit;
using Reactive.Streams;
namespace Akka.Streams.TestKit
{
public static class TestSubscriber
{
#region messages
public interface ISubscriberEvent : INoSerializationVerificationNeeded, IDeadLetterSuppression { }
public struct OnSubscribe : ISubscriberEvent
{
public readonly ISubscription Subscription;
public OnSubscribe(ISubscription subscription)
{
Subscription = subscription;
}
public override string ToString() => $"TestSubscriber.OnSubscribe({Subscription})";
}
public struct OnNext<T> : ISubscriberEvent
{
public readonly T Element;
public OnNext(T element)
{
Element = element;
}
public override string ToString() => $"TestSubscriber.OnNext({Element})";
}
public sealed class OnComplete: ISubscriberEvent
{
public static readonly OnComplete Instance = new OnComplete();
private OnComplete() { }
public override string ToString() => $"TestSubscriber.OnComplete";
}
public struct OnError : ISubscriberEvent
{
public readonly Exception Cause;
public OnError(Exception cause)
{
Cause = cause;
}
public override string ToString() => $"TestSubscriber.OnError({Cause.Message})";
}
#endregion
/// <summary>
/// Implementation of <see cref="ISubscriber{T}"/> that allows various assertions. All timeouts are dilated automatically,
/// for more details about time dilation refer to <see cref="TestKit"/>.
/// </summary>
public class ManualProbe<T> : ISubscriber<T>
{
private readonly TestProbe _probe;
internal ManualProbe(TestKitBase testKit)
{
_probe = testKit.CreateTestProbe();
}
private volatile ISubscription _subscription;
public void OnSubscribe(ISubscription subscription)
{
_probe.Ref.Tell(new OnSubscribe(subscription));
}
public void OnError(Exception cause)
{
_probe.Ref.Tell(new OnError(cause));
}
public void OnComplete()
{
_probe.Ref.Tell(TestSubscriber.OnComplete.Instance);
}
public void OnNext(T element)
{
_probe.Ref.Tell(new OnNext<T>(element));
}
/// <summary>
/// Expects and returns <see cref="ISubscription"/>.
/// </summary>
public ISubscription ExpectSubscription()
{
_subscription = _probe.ExpectMsg<OnSubscribe>().Subscription;
return _subscription;
}
/// <summary>
/// Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>).
/// </summary>
public ISubscriberEvent ExpectEvent()
{
return _probe.ExpectMsg<ISubscriberEvent>();
}
/// <summary>
/// Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>).
/// </summary>
public ISubscriberEvent ExpectEvent(TimeSpan max)
{
return _probe.ExpectMsg<ISubscriberEvent>(max);
}
/// <summary>
/// Fluent DSL. Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>).
/// </summary>
public ManualProbe<T> ExpectEvent(ISubscriberEvent e)
{
_probe.ExpectMsg(e);
return this;
}
/// <summary>
/// Expect and return a stream element.
/// </summary>
public T ExpectNext()
{
var t = _probe.RemainingOrDilated(null);
var message = _probe.ReceiveOne(t);
if (message is OnNext<T>) return ((OnNext<T>) message).Element;
else throw new Exception("expected OnNext, found " + message);
}
/// <summary>
/// Fluent DSL. Expect a stream element.
/// </summary>
public ManualProbe<T> ExpectNext(T element)
{
_probe.ExpectMsg<OnNext<T>>(x => Equals(x.Element, element));
return this;
}
/// <summary>
/// Fluent DSL. Expect a stream element during specified timeout.
/// </summary>
public ManualProbe<T> ExpectNext(T element, TimeSpan timeout)
{
_probe.ExpectMsg<OnNext<T>>(x => Equals(x.Element, element), timeout);
return this;
}
/// <summary>
/// Fluent DSL. Expect multiple stream elements.
/// </summary>
public ManualProbe<T> ExpectNext(T e1, T e2, params T[] elems)
{
var len = elems.Length + 2;
var e = ExpectNextN(len).ToArray();
AssertEquals(e.Length, len, "expected to get {0} events, but got {1}", len, e.Length);
AssertEquals(e[0], e1, "expected [0] element to be {0} but found {1}", e1, e[0]);
AssertEquals(e[1], e2, "expected [1] element to be {0} but found {1}", e2, e[1]);
for (var i = 0; i < elems.Length; i++)
{
var j = i + 2;
AssertEquals(e[j], elems[i], "expected [{2}] element to be {0} but found {1}", elems[i], e[j], j);
}
return this;
}
/// <summary>
/// FluentDSL. Expect multiple stream elements in arbitrary order.
/// </summary>
public ManualProbe<T> ExpectNextUnordered(T e1, T e2, params T[] elems)
{
var len = elems.Length + 2;
var e = ExpectNextN(len).ToArray();
AssertEquals(e.Length, len, "expected to get {0} events, but got {1}", len, e.Length);
var expectedSet = new HashSet<T>(elems) {e1, e2};
expectedSet.ExceptWith(e);
Assert(expectedSet.Count == 0, "unexpected elemenents [{0}] found in the result", string.Join(", ", expectedSet));
return this;
}
/// <summary>
/// Expect and return the next <paramref name="n"/> stream elements.
/// </summary>
public IEnumerable<T> ExpectNextN(long n)
{
var res = new List<T>((int)n);
for (int i = 0; i < n; i++)
{
var next = _probe.ExpectMsg<OnNext<T>>();
res.Add(next.Element);
}
return res;
}
/// <summary>
/// Fluent DSL. Expect the given elements to be signalled in order.
/// </summary>
public ManualProbe<T> ExpectNextN(IEnumerable<T> all)
{
foreach (var x in all)
_probe.ExpectMsg<OnNext<T>>(y => Equals(y.Element, x));
return this;
}
/// <summary>
/// Fluent DSL. Expect the given elements to be signalled in any order.
/// </summary>
public ManualProbe<T> ExpectNextUnorderedN(IEnumerable<T> all)
{
var collection = new HashSet<T>(all);
while (collection.Count > 0)
{
var next = ExpectNext();
Assert(collection.Contains(next), $"expected one of (${string.Join(", ", collection)}), but received {next}");
collection.Remove(next);
}
return this;
}
/// <summary>
/// Fluent DSL. Expect completion.
/// </summary>
public ManualProbe<T> ExpectComplete()
{
_probe.ExpectMsg<OnComplete>();
return this;
}
/// <summary>
/// Expect and return the signalled <see cref="Exception"/>.
/// </summary>
public Exception ExpectError()
{
return _probe.ExpectMsg<OnError>().Cause;
}
/// <summary>
/// Expect subscription to be followed immediatly by an error signal. By default single demand will be signalled in order to wake up a possibly lazy upstream.
/// <seealso cref="ExpectSubscriptionAndError(bool)"/>
/// </summary>
public Exception ExpectSubscriptionAndError()
{
return ExpectSubscriptionAndError(true);
}
/// <summary>
/// Expect subscription to be followed immediatly by an error signal. Depending on the `signalDemand` parameter demand may be signalled
/// immediatly after obtaining the subscription in order to wake up a possibly lazy upstream.You can disable this by setting the `signalDemand` parameter to `false`.
/// <seealso cref="ExpectSubscriptionAndError()"/>
/// </summary>
public Exception ExpectSubscriptionAndError(bool signalDemand)
{
var sub = ExpectSubscription();
if(signalDemand) sub.Request(1);
return ExpectError();
}
/// <summary>
/// Fluent DSL. Expect subscription followed by immediate stream completion. By default single demand will be signalled in order to wake up a possibly lazy upstream
/// </summary>
/// <seealso cref="ExpectSubscriptionAndComplete(bool)"/>
public ManualProbe<T> ExpectSubscriptionAndComplete()
{
return ExpectSubscriptionAndComplete(true);
}
/// <summary>
/// Fluent DSL. Expect subscription followed by immediate stream completion. Depending on the `signalDemand` parameter
/// demand may be signalled immediatly after obtaining the subscription in order to wake up a possibly lazy upstream.
/// You can disable this by setting the `signalDemand` parameter to `false`.
/// </summary>
/// <seealso cref="ExpectSubscriptionAndComplete()"/>
public ManualProbe<T> ExpectSubscriptionAndComplete(bool signalDemand)
{
var sub = ExpectSubscription();
if (signalDemand) sub.Request(1);
ExpectComplete();
return this;
}
/// <summary>
/// Expect given next element or error signal, returning whichever was signalled.
/// </summary>
public object ExpectNextOrError()
{
var message = _probe.FishForMessage(m => m is OnNext<T> || m is OnError, hint: "OnNext(_) or error");
if (message is OnNext<T>)
return ((OnNext<T>) message).Element;
return ((OnError) message).Cause;
}
/// <summary>
/// Fluent DSL. Expect given next element or error signal.
/// </summary>
public ManualProbe<T> ExpectNextOrError(T element, Exception cause)
{
_probe.FishForMessage(
m =>
(m is OnNext<T> && ((OnNext<T>) m).Element.Equals(element)) ||
(m is OnError && ((OnError) m).Cause.Equals(cause)),
hint: $"OnNext({element}) or {cause.GetType().Name}");
return this;
}
/// <summary>
/// Expect given next element or stream completion, returning whichever was signalled.
/// </summary>
public object ExpectNextOrComplete()
{
var message = _probe.FishForMessage(m => m is OnNext<T> || m is OnComplete, hint: "OnNext(_) or OnComplete");
if (message is OnNext<T>)
return ((OnNext<T>) message).Element;
return message;
}
/// <summary>
/// Fluent DSL. Expect given next element or stream completion.
/// </summary>
public ManualProbe<T> ExpectNextOrComplete(T element)
{
_probe.FishForMessage(
m =>
(m is OnNext<T> && ((OnNext<T>) m).Element.Equals(element)) ||
m is OnComplete,
hint: $"OnNext({element}) or OnComplete");
return this;
}
/// <summary>
/// Fluent DSL. Same as <see cref="ExpectNoMsg(TimeSpan)"/>, but correctly treating the timeFactor.
/// </summary>
public ManualProbe<T> ExpectNoMsg()
{
_probe.ExpectNoMsg();
return this;
}
/// <summary>
/// Fluent DSL. Assert that no message is received for the specified time.
/// </summary>
public ManualProbe<T> ExpectNoMsg(TimeSpan remaining)
{
_probe.ExpectNoMsg(remaining);
return this;
}
public TOther ExpectNext<TOther>(Predicate<TOther> predicate)
{
return _probe.ExpectMsg<OnNext<TOther>>(x => predicate(x.Element)).Element;
}
public TOther ExpectEvent<TOther>(Func<ISubscriberEvent, TOther> func)
{
return func(_probe.ExpectMsg<ISubscriberEvent>());
}
/// <summary>
/// Receive messages for a given duration or until one does not match a given partial function.
/// </summary>
public IEnumerable<TOther> ReceiveWhile<TOther>(TimeSpan? max = null, TimeSpan? idle = null, Func<object, TOther> filter = null, int msgs = int.MaxValue) where TOther : class
{
return _probe.ReceiveWhile(max, idle, filter, msgs);
}
public TOther Within<TOther>(TimeSpan max, Func<TOther> func)
{
return _probe.Within(TimeSpan.Zero, max, func);
}
/// <summary>
/// Attempt to drain the stream into a strict collection (by requesting <see cref="long.MaxValue"/> elements).
/// </summary>
/// <remarks>
/// Use with caution: Be warned that this may not be a good idea if the stream is infinite or its elements are very large!
/// </remarks>
public IList<T> ToStrict(TimeSpan atMost)
{
var deadline = DateTime.UtcNow + atMost;
// if no subscription was obtained yet, we expect it
if (_subscription == null) ExpectSubscription();
_subscription.Request(long.MaxValue);
var result = new List<T>();
while (true)
{
var e = ExpectEvent(TimeSpan.FromTicks(Math.Max(deadline.Ticks - DateTime.UtcNow.Ticks, 0)));
if (e is OnError)
throw new ArgumentException(
$"ToStrict received OnError while draining stream! Accumulated elements: ${string.Join(", ", result)}",
((OnError) e).Cause);
if (e is OnComplete)
break;
if (e is OnNext<T>)
result.Add(((OnNext<T>) e).Element);
}
return result;
}
private void Assert(bool predicate, string format, params object[] args)
{
if (!predicate) throw new Exception(string.Format(format, args));
}
private void AssertEquals<T1, T2>(T1 x, T2 y, string format, params object[] args)
{
if (!Equals(x, y)) throw new Exception(string.Format(format, args));
}
}
/// <summary>
/// Single subscription tracking for <see cref="ManualProbe{T}"/>.
/// </summary>
public class Probe<T> : ManualProbe<T>
{
private readonly Lazy<ISubscription> _subscription;
internal Probe(TestKitBase testKit) : base(testKit)
{
_subscription = new Lazy<ISubscription>(ExpectSubscription);
}
/// <summary>
/// Asserts that a subscription has been received or will be received
/// </summary>
public Probe<T> EnsureSubscription()
{
var _ = _subscription.Value; // initializes lazy val
return this;
}
public Probe<T> Request(long n)
{
_subscription.Value.Request(n);
return this;
}
public Probe<T> RequestNext(T element)
{
_subscription.Value.Request(1);
ExpectNext(element);
return this;
}
public Probe<T> Cancel()
{
_subscription.Value.Cancel();
return this;
}
public T RequestNext()
{
_subscription.Value.Request(1);
return ExpectNext();
}
}
public static ManualProbe<T> CreateManualProbe<T>(this TestKitBase testKit)
{
return new ManualProbe<T>(testKit);
}
public static Probe<T> CreateProbe<T>(this TestKitBase testKit)
{
return new Probe<T>(testKit);
}
}
}
| |
//Sourced from https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Net.Http.Formatting/Formatting/MediaTypeFormatter.cs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace RestBus.Client.Http.Formatting
{
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
#if !NETFX_CORE
using System.Configuration;
#endif
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Net.Http;
using System.Net;
using System.Threading;
using Internal;
/// <summary>
/// Base class to handle serializing and deserializing strongly-typed objects using <see cref="ObjectContent"/>.
/// </summary>
internal abstract class MediaTypeFormatter
{
private const int DefaultMinHttpCollectionKeys = 1;
private const int DefaultMaxHttpCollectionKeys = 1000; // same default as ASPNET
private const string IWellKnownComparerTypeName = "System.IWellKnownStringEqualityComparer, mscorlib, Version=4.0.0.0, PublicKeyToken=b77a5c561934e089";
private static readonly ConcurrentDictionary<Type, Type> _delegatingEnumerableCache = new ConcurrentDictionary<Type, Type>();
private static ConcurrentDictionary<Type, ConstructorInfo> _delegatingEnumerableConstructorCache = new ConcurrentDictionary<Type, ConstructorInfo>();
private static Lazy<int> _defaultMaxHttpCollectionKeys = new Lazy<int>(InitializeDefaultCollectionKeySize, true); // Max number of keys is 1000
private static int _maxHttpCollectionKeys = -1;
private readonly List<MediaTypeHeaderValue> _supportedMediaTypes;
private readonly List<Encoding> _supportedEncodings;
#if !NETFX_CORE // No MediaTypeMappings in portable library or IRequiredMemberSelector (no model state on client)
private readonly List<MediaTypeMapping> _mediaTypeMappings;
private IRequiredMemberSelector _requiredMemberSelector;
#endif
/// <summary>
/// Initializes a new instance of the <see cref="MediaTypeFormatter"/> class.
/// </summary>
protected MediaTypeFormatter()
{
_supportedMediaTypes = new List<MediaTypeHeaderValue>();
SupportedMediaTypes = new MediaTypeHeaderValueCollection(_supportedMediaTypes);
_supportedEncodings = new List<Encoding>();
SupportedEncodings = new Collection<Encoding>(_supportedEncodings);
#if !NETFX_CORE // No MediaTypeMappings in portable library
_mediaTypeMappings = new List<MediaTypeMapping>();
MediaTypeMappings = new Collection<MediaTypeMapping>(_mediaTypeMappings);
#endif
}
/// <summary>
/// Initializes a new instance of the <see cref="MediaTypeFormatter"/> class.
/// </summary>
/// <param name="formatter">The <see cref="MediaTypeFormatter"/> instance to copy settings from.</param>
protected MediaTypeFormatter(MediaTypeFormatter formatter)
{
if (formatter == null)
{
throw Error.ArgumentNull("formatter");
}
_supportedMediaTypes = formatter._supportedMediaTypes;
SupportedMediaTypes = formatter.SupportedMediaTypes;
_supportedEncodings = formatter._supportedEncodings;
SupportedEncodings = formatter.SupportedEncodings;
#if !NETFX_CORE // No MediaTypeMappings in portable library or IRequiredMemberSelector (no model state on client)
_mediaTypeMappings = formatter._mediaTypeMappings;
MediaTypeMappings = formatter.MediaTypeMappings;
_requiredMemberSelector = formatter._requiredMemberSelector;
#endif
}
/// <summary>
/// Gets or sets the maximum number of keys stored in a NameValueCollection.
/// </summary>
public static int MaxHttpCollectionKeys
{
get
{
if (_maxHttpCollectionKeys < 0)
{
_maxHttpCollectionKeys = _defaultMaxHttpCollectionKeys.Value;
}
return _maxHttpCollectionKeys;
}
set
{
if (value < DefaultMinHttpCollectionKeys)
{
throw Error.ArgumentMustBeGreaterThanOrEqualTo("value", value, DefaultMinHttpCollectionKeys);
}
_maxHttpCollectionKeys = value;
}
}
/// <summary>
/// Gets the mutable collection of <see cref="MediaTypeHeaderValue"/> elements supported by
/// this <see cref="MediaTypeFormatter"/> instance.
/// </summary>
public Collection<MediaTypeHeaderValue> SupportedMediaTypes { get; private set; }
internal List<MediaTypeHeaderValue> SupportedMediaTypesInternal
{
get { return _supportedMediaTypes; }
}
/// <summary>
/// Gets the mutable collection of character encodings supported by
/// this <see cref="MediaTypeFormatter"/> instance. The encodings are
/// used when reading or writing data.
/// </summary>
public Collection<Encoding> SupportedEncodings { get; private set; }
internal List<Encoding> SupportedEncodingsInternal
{
get { return _supportedEncodings; }
}
#if !NETFX_CORE // No MediaTypeMappings in portable library
/// <summary>
/// Gets the mutable collection of <see cref="MediaTypeMapping"/> elements used
/// by this <see cref="MediaTypeFormatter"/> instance to determine the
/// <see cref="MediaTypeHeaderValue"/> of requests or responses.
/// </summary>
public Collection<MediaTypeMapping> MediaTypeMappings { get; private set; }
internal List<MediaTypeMapping> MediaTypeMappingsInternal
{
get { return _mediaTypeMappings; }
}
#endif
#if !NETFX_CORE // IRequiredMemberSelector is not in portable libraries because there is no model state on the client.
/// <summary>
/// Gets or sets the <see cref="IRequiredMemberSelector"/> used to determine required members.
/// </summary>
public virtual IRequiredMemberSelector RequiredMemberSelector
{
get
{
return _requiredMemberSelector;
}
set
{
_requiredMemberSelector = value;
}
}
#endif
internal virtual bool CanWriteAnyTypes
{
get { return true; }
}
/// <summary>
/// Returns a <see cref="Task"/> to deserialize an object of the given <paramref name="type"/> from the given <paramref name="readStream"/>
/// </summary>
/// <remarks>
/// <para>This implementation throws a <see cref="NotSupportedException"/>. Derived types should override this method if the formatter
/// supports reading.</para>
/// <para>An implementation of this method should NOT close <paramref name="readStream"/> upon completion. The stream will be closed independently when
/// the <see cref="HttpContent"/> instance is disposed.
/// </para>
/// </remarks>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="readStream">The <see cref="Stream"/> to read.</param>
/// <param name="content">The <see cref="HttpContent"/> if available. It may be <c>null</c>.</param>
/// <param name="formatterLogger">The <see cref="IFormatterLogger"/> to log events to.</param>
/// <returns>A <see cref="Task"/> whose result will be an object of the given type.</returns>
/// <exception cref="NotSupportedException">Derived types need to support reading.</exception>
/// <seealso cref="CanReadType(Type)"/>
public virtual Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
throw Error.NotSupported(Properties.Resources.MediaTypeFormatterCannotRead, GetType().Name);
}
/// <summary>
/// Returns a <see cref="Task"/> to deserialize an object of the given <paramref name="type"/> from the given <paramref name="readStream"/>
/// </summary>
/// <remarks>
/// <para>This implementation throws a <see cref="NotSupportedException"/>. Derived types should override this method if the formatter
/// supports reading.</para>
/// <para>An implementation of this method should NOT close <paramref name="readStream"/> upon completion. The stream will be closed independently when
/// the <see cref="HttpContent"/> instance is disposed.
/// </para>
/// </remarks>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="readStream">The <see cref="Stream"/> to read.</param>
/// <param name="content">The <see cref="HttpContent"/> if available. It may be <c>null</c>.</param>
/// <param name="formatterLogger">The <see cref="IFormatterLogger"/> to log events to.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A <see cref="Task"/> whose result will be an object of the given type.</returns>
/// <exception cref="NotSupportedException">Derived types need to support reading.</exception>
/// <seealso cref="CanReadType(Type)"/>
public virtual Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,
IFormatterLogger formatterLogger, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return TaskHelpers.Canceled<object>();
}
return ReadFromStreamAsync(type, readStream, content, formatterLogger);
}
/// <summary>
/// Returns a <see cref="Task"/> that serializes the given <paramref name="value"/> of the given <paramref name="type"/>
/// to the given <paramref name="writeStream"/>.
/// </summary>
/// <remarks>
/// <para>This implementation throws a <see cref="NotSupportedException"/>. Derived types should override this method if the formatter
/// supports reading.</para>
/// <para>An implementation of this method should NOT close <paramref name="writeStream"/> upon completion. The stream will be closed independently when
/// the <see cref="HttpContent"/> instance is disposed.
/// </para>
/// </remarks>
/// <param name="type">The type of the object to write.</param>
/// <param name="value">The object value to write. It may be <c>null</c>.</param>
/// <param name="writeStream">The <see cref="Stream"/> to which to write.</param>
/// <param name="content">The <see cref="HttpContent"/> if available. It may be <c>null</c>.</param>
/// <param name="transportContext">The <see cref="TransportContext"/> if available. It may be <c>null</c>.</param>
/// <returns>A <see cref="Task"/> that will perform the write.</returns>
/// <exception cref="NotSupportedException">Derived types need to support writing.</exception>
/// <seealso cref="CanWriteType(Type)"/>
public virtual Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
// HttpContent.SerializeToStreamAsync doesn't take in a CancellationToken. So, there is no easy way to get the CancellationToken
// to the formatter while writing response. We are cheating here by passing fake cancellation tokens. We should fix this
// when we fix HttpContent.
return WriteToStreamAsync(type, value, writeStream, content, transportContext, CancellationToken.None);
}
/// <summary>
/// Returns a <see cref="Task"/> that serializes the given <paramref name="value"/> of the given <paramref name="type"/>
/// to the given <paramref name="writeStream"/>.
/// </summary>
/// <remarks>
/// <para>This implementation throws a <see cref="NotSupportedException"/>. Derived types should override this method if the formatter
/// supports reading.</para>
/// <para>An implementation of this method should NOT close <paramref name="writeStream"/> upon completion. The stream will be closed independently when
/// the <see cref="HttpContent"/> instance is disposed.
/// </para>
/// </remarks>
/// <param name="type">The type of the object to write.</param>
/// <param name="value">The object value to write. It may be <c>null</c>.</param>
/// <param name="writeStream">The <see cref="Stream"/> to which to write.</param>
/// <param name="content">The <see cref="HttpContent"/> if available. It may be <c>null</c>.</param>
/// <param name="transportContext">The <see cref="TransportContext"/> if available. It may be <c>null</c>.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A <see cref="Task"/> that will perform the write.</returns>
/// <exception cref="NotSupportedException">Derived types need to support writing.</exception>
/// <seealso cref="CanWriteType(Type)"/>
public virtual Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
TransportContext transportContext, CancellationToken cancellationToken)
{
throw Error.NotSupported(Properties.Resources.MediaTypeFormatterCannotWrite, GetType().Name);
}
private static bool TryGetDelegatingType(Type interfaceType, ref Type type)
{
if (type != null && type.IsInterface() && type.IsGenericType())
{
Type genericType = type.ExtractGenericInterface(interfaceType);
if (genericType != null)
{
type = GetOrAddDelegatingType(type, genericType);
return true;
}
}
return false;
}
private static int InitializeDefaultCollectionKeySize()
{
return Int32.MaxValue;
}
/// <summary>
/// This method converts <see cref="IEnumerable{T}"/> (and interfaces that mandate it) to a <see cref="DelegatingEnumerable{T}"/> for serialization purposes.
/// </summary>
/// <param name="type">The type to potentially be wrapped. If the type is wrapped, it's changed in place.</param>
/// <returns>Returns <c>true</c> if the type was wrapped; <c>false</c>, otherwise</returns>
internal static bool TryGetDelegatingTypeForIEnumerableGenericOrSame(ref Type type)
{
return TryGetDelegatingType(FormattingUtilities.EnumerableInterfaceGenericType, ref type);
}
/// <summary>
/// This method converts <see cref="IQueryable{T}"/> (and interfaces that mandate it) to a <see cref="DelegatingEnumerable{T}"/> for serialization purposes.
/// </summary>
/// <param name="type">The type to potentially be wrapped. If the type is wrapped, it's changed in place.</param>
/// <returns>Returns <c>true</c> if the type was wrapped; <c>false</c>, otherwise</returns>
internal static bool TryGetDelegatingTypeForIQueryableGenericOrSame(ref Type type)
{
return TryGetDelegatingType(FormattingUtilities.QueryableInterfaceGenericType, ref type);
}
internal static ConstructorInfo GetTypeRemappingConstructor(Type type)
{
ConstructorInfo constructorInfo;
_delegatingEnumerableConstructorCache.TryGetValue(type, out constructorInfo);
return constructorInfo;
}
/// <summary>
/// Determines the best <see cref="Encoding"/> amongst the supported encodings
/// for reading or writing an HTTP entity body based on the provided <paramref name="contentHeaders"/>.
/// </summary>
/// <param name="contentHeaders">The content headers provided as part of the request or response.</param>
/// <returns>The <see cref="Encoding"/> to use when reading the request or writing the response.</returns>
public Encoding SelectCharacterEncoding(HttpContentHeaders contentHeaders)
{
// Performance-sensitive
Encoding encoding = null;
if (contentHeaders != null && contentHeaders.ContentType != null)
{
// Find encoding based on content type charset parameter
string charset = contentHeaders.ContentType.CharSet;
if (!String.IsNullOrWhiteSpace(charset))
{
for (int i = 0; i < _supportedEncodings.Count; i++)
{
Encoding supportedEncoding = _supportedEncodings[i];
if (charset.Equals(supportedEncoding.WebName, StringComparison.OrdinalIgnoreCase))
{
encoding = supportedEncoding;
break;
}
}
}
}
if (encoding == null)
{
// We didn't find a character encoding match based on the content headers.
// Instead we try getting the default character encoding.
if (_supportedEncodings.Count > 0)
{
encoding = _supportedEncodings[0];
}
}
if (encoding == null)
{
// No supported encoding was found so there is no way for us to start reading or writing.
throw Error.InvalidOperation(Properties.Resources.MediaTypeFormatterNoEncoding, GetType().Name);
}
return encoding;
}
/// <summary>
/// Sets the default headers for content that will be formatted using this formatter. This method
/// is called from the <see cref="ObjectContent"/> constructor.
/// This implementation sets the Content-Type header to the value of <paramref name="mediaType"/> if it is
/// not <c>null</c>. If it is <c>null</c> it sets the Content-Type to the default media type of this formatter.
/// If the Content-Type does not specify a charset it will set it using this formatters configured
/// <see cref="Encoding"/>.
/// </summary>
/// <remarks>
/// Subclasses can override this method to set content headers such as Content-Type etc. Subclasses should
/// call the base implementation. Subclasses should treat the passed in <paramref name="mediaType"/> (if not <c>null</c>)
/// as the authoritative media type and use that as the Content-Type.
/// </remarks>
/// <param name="type">The type of the object being serialized. See <see cref="ObjectContent"/>.</param>
/// <param name="headers">The content headers that should be configured.</param>
/// <param name="mediaType">The authoritative media type. Can be <c>null</c>.</param>
public virtual void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
if (type == null)
{
throw Error.ArgumentNull("type");
}
if (headers == null)
{
throw Error.ArgumentNull("headers");
}
if (mediaType != null)
{
headers.ContentType = new MediaTypeHeaderValue(mediaType.MediaType);
}
// If content type is not set then set it based on supported media types.
if (headers.ContentType == null)
{
MediaTypeHeaderValue defaultMediaType = null;
if (_supportedMediaTypes.Count > 0)
{
defaultMediaType = _supportedMediaTypes[0];
}
if (defaultMediaType != null)
{
headers.ContentType = new MediaTypeHeaderValue(defaultMediaType.MediaType);
}
}
// If content type charset parameter is not set then set it based on the supported encodings.
if (headers.ContentType != null && headers.ContentType.CharSet == null)
{
Encoding defaultEncoding = null;
if (_supportedEncodings.Count > 0)
{
defaultEncoding = _supportedEncodings[0];
}
if (defaultEncoding != null)
{
headers.ContentType.CharSet = defaultEncoding.WebName;
}
}
}
/// <summary>
/// Returns a specialized instance of the <see cref="MediaTypeFormatter"/> that can handle formatting a response for the given
/// parameters. This method is called after a formatter has been selected through content negotiation.
/// </summary>
/// <remarks>
/// The default implementation returns <c>this</c> instance. Derived classes can choose to return a new instance if
/// they need to close over any of the parameters.
/// </remarks>
/// <param name="type">The type being serialized.</param>
/// <param name="request">The request.</param>
/// <param name="mediaType">The media type chosen for the serialization. Can be <c>null</c>.</param>
/// <returns>An instance that can format a response to the given <paramref name="request"/>.</returns>
public virtual MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
{
if (type == null)
{
throw Error.ArgumentNull("type");
}
if (request == null)
{
throw Error.ArgumentNull("request");
}
return this;
}
/// <summary>
/// Determines whether this <see cref="MediaTypeFormatter"/> can deserialize
/// an object of the specified type.
/// </summary>
/// <remarks>
/// Derived classes must implement this method and indicate if a type can or cannot be deserialized.
/// </remarks>
/// <param name="type">The type of object that will be deserialized.</param>
/// <returns><c>true</c> if this <see cref="MediaTypeFormatter"/> can deserialize an object of that type; otherwise <c>false</c>.</returns>
public abstract bool CanReadType(Type type);
/// <summary>
/// Determines whether this <see cref="MediaTypeFormatter"/> can serialize
/// an object of the specified type.
/// </summary>
/// <remarks>
/// Derived classes must implement this method and indicate if a type can or cannot be serialized.
/// </remarks>
/// <param name="type">The type of object that will be serialized.</param>
/// <returns><c>true</c> if this <see cref="MediaTypeFormatter"/> can serialize an object of that type; otherwise <c>false</c>.</returns>
public abstract bool CanWriteType(Type type);
private static Type GetOrAddDelegatingType(Type type, Type genericType)
{
return _delegatingEnumerableCache.GetOrAdd(
type,
(typeToRemap) =>
{
// The current method is called by methods that already checked the type for is not null, is generic and is or implements IEnumerable<T>
// This retrieves the T type of the IEnumerable<T> interface.
Type elementType = genericType.GetGenericArguments()[0];
Type delegatingType = FormattingUtilities.DelegatingEnumerableGenericType.MakeGenericType(elementType);
ConstructorInfo delegatingConstructor = delegatingType.GetConstructor(new Type[] { FormattingUtilities.EnumerableInterfaceGenericType.MakeGenericType(elementType) });
_delegatingEnumerableConstructorCache.TryAdd(delegatingType, delegatingConstructor);
return delegatingType;
});
}
/// <summary>
/// Gets the default value for the specified type.
/// </summary>
public static object GetDefaultValueForType(Type type)
{
if (type == null)
{
throw Error.ArgumentNull("type");
}
if (type.IsValueType())
{
return Activator.CreateInstance(type);
}
return null;
}
/// <summary>
/// Collection class that validates it contains only <see cref="MediaTypeHeaderValue"/> instances
/// that are not null and not media ranges.
/// </summary>
internal class MediaTypeHeaderValueCollection : Collection<MediaTypeHeaderValue>
{
private static readonly Type _mediaTypeHeaderValueType = typeof(MediaTypeHeaderValue);
internal MediaTypeHeaderValueCollection(IList<MediaTypeHeaderValue> list)
: base(list)
{
}
/// <summary>
/// Inserts the <paramref name="item"/> into the collection at the specified <paramref name="index"/>.
/// </summary>
/// <param name="index">The zero-based index at which item should be inserted.</param>
/// <param name="item">The object to insert. It cannot be <c>null</c>.</param>
protected override void InsertItem(int index, MediaTypeHeaderValue item)
{
ValidateMediaType(item);
base.InsertItem(index, item);
}
/// <summary>
/// Replaces the element at the specified <paramref name="index"/>.
/// </summary>
/// <param name="index">The zero-based index of the item that should be replaced.</param>
/// <param name="item">The new value for the element at the specified index. It cannot be <c>null</c>.</param>
protected override void SetItem(int index, MediaTypeHeaderValue item)
{
ValidateMediaType(item);
base.SetItem(index, item);
}
private static void ValidateMediaType(MediaTypeHeaderValue item)
{
if (item == null)
{
throw Error.ArgumentNull("item");
}
ParsedMediaTypeHeaderValue parsedMediaType = new ParsedMediaTypeHeaderValue(item);
if (parsedMediaType.IsAllMediaRange || parsedMediaType.IsSubtypeMediaRange)
{
throw Error.Argument("item", Properties.Resources.CannotUseMediaRangeForSupportedMediaType, _mediaTypeHeaderValueType.Name, item.MediaType);
}
}
}
}
}
| |
using NUnit.Framework;
using SJP.Schematic.Core;
namespace SJP.Schematic.DataAccess.Tests
{
[TestFixture]
internal static class CamelCaseNameTranslatorTests
{
[Test]
public static void SchemaToNamespace_GivenNullName_ThrowsArgumentNullException()
{
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.SchemaToNamespace(null), Throws.ArgumentNullException);
}
[Test]
public static void SchemaToNamespace_GivenNullSchema_ReturnsNull()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("test");
var result = nameTranslator.SchemaToNamespace(testName);
Assert.That(result, Is.Null);
}
[Test]
public static void SchemaToNamespace_GivenSpaceSeparatedSchemaName_ReturnsSpaceRemovedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("first second", "test");
const string expected = "firstsecond";
var result = nameTranslator.SchemaToNamespace(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void SchemaToNamespace_GivenUnderscoreSeparatedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("first_second", "test");
const string expected = "firstSecond";
var result = nameTranslator.SchemaToNamespace(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void SchemaToNamespace_GivenPascalCasedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("FirstSecond", "test");
const string expected = "firstSecond";
var result = nameTranslator.SchemaToNamespace(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void TableToClassName_GivenNullName_ThrowsArgumentNullException()
{
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.TableToClassName(null), Throws.ArgumentNullException);
}
[Test]
public static void TableToClassName_GivenSpaceSeparatedLocalName_ReturnsSpaceRemovedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("first second");
const string expected = "firstsecond";
var result = nameTranslator.TableToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void TableToClassName_GivenUnderscoreSeparatedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("first_second");
const string expected = "firstSecond";
var result = nameTranslator.TableToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void TableToClassName_GivenPascalCasedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("FirstSecond");
const string expected = "firstSecond";
var result = nameTranslator.TableToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ViewToClassName_GivenNullName_ThrowsArgumentNullException()
{
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.ViewToClassName(null), Throws.ArgumentNullException);
}
[Test]
public static void ViewToClassName_GivenSpaceSeparatedLocalName_ReturnsSpaceRemovedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("first second");
const string expected = "firstsecond";
var result = nameTranslator.ViewToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ViewToClassName_GivenUnderscoreSeparatedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("first_second");
const string expected = "firstSecond";
var result = nameTranslator.ViewToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ViewToClassName_GivenPascalCasedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("FirstSecond");
const string expected = "firstSecond";
var result = nameTranslator.ViewToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ColumnToPropertyName_GivenNullClassName_ThrowsArgumentNullException()
{
const string columnName = "test";
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(null, columnName), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenEmptyClassName_ThrowsArgumentNullException()
{
const string columnName = "test";
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(string.Empty, columnName), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenWhiteSpaceClassName_ThrowsArgumentNullException()
{
const string columnName = "test";
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(" ", columnName), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenNullColumnName_ThrowsArgumentNullException()
{
const string className = "test";
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(className, null), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenEmptyColumnName_ThrowsArgumentNullException()
{
const string className = "test";
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(className, string.Empty), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenWhiteSpaceColumnName_ThrowsArgumentNullException()
{
const string className = "test";
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(className, " "), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenSpaceSeparatedSchemaName_ReturnsSpaceRemovedText()
{
var nameTranslator = new CamelCaseNameTranslator();
const string className = "test";
const string testName = "first second";
const string expected = "firstsecond";
var result = nameTranslator.ColumnToPropertyName(className, testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ColumnToPropertyName_GivenUnderscoreSeparatedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
const string className = "test";
const string testName = "first_second";
const string expected = "firstSecond";
var result = nameTranslator.ColumnToPropertyName(className, testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ColumnToPropertyName_GivenPascalCasedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
const string className = "test";
const string testName = "FirstSecond";
const string expected = "firstSecond";
var result = nameTranslator.ColumnToPropertyName(className, testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ColumnToPropertyName_GivenTransformedNameMatchingClassName_ReturnsUnderscoreAppendedColumnName()
{
var nameTranslator = new CamelCaseNameTranslator();
const string className = "firstSecond";
const string testName = "FirstSecond";
const string expected = "firstSecond_";
var result = nameTranslator.ColumnToPropertyName(className, testName);
Assert.That(result, Is.EqualTo(expected));
}
}
}
| |
using System;
using System.Collections.Generic;
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
namespace Gum.Graphics.Animation
{
/// <summary>
/// Represents a collection of AnimationFrames which can be used to perform
/// texture flipping animation on IAnimationChainAnimatables such as Sprites.
/// </summary>
public partial class AnimationChain : List<AnimationFrame>, IEquatable<AnimationChain>
{
#region Fields
private string mName;
//private string mParentFileName;
internal int mIndexInLoadedAchx = -1;
#endregion
#region Properties
/// <summary>
/// Sets the frame time to every frame in the animation to the value. For example, assigning a FrameTime of .2 will make every frame in the animation last .2 seconds.
/// </summary>
public float FrameTime
{
set
{
foreach (AnimationFrame frame in this)
frame.FrameLength = value;
}
}
public int IndexInLoadedAchx
{
get { return mIndexInLoadedAchx; }
}
#region XML Docs
/// <summary>
/// Gets the last AnimationFrame of the AnimationChain or null if
/// there are no AnimationFrames.
/// </summary>
#endregion
public AnimationFrame LastFrame
{
get
{
if (this.Count == 0)
{
return null;
}
else
{
return this[this.Count - 1];
}
}
}
#region XML Docs
/// <summary>
/// The name of the AnimationChain.
/// </summary>
#endregion
public string Name
{
get { return mName; }
set { mName = value; }
}
private string mParentAchxFileName;
public string ParentAchxFileName
{
get { return mParentAchxFileName; }
set { mParentAchxFileName = value; }
}
private string mParentGifFileName;
public string ParentGifFileName
{
get { return mParentGifFileName; }
set { mParentGifFileName = value; }
}
/// <summary>
/// The total duration of the animation in seconds. This is obtained by adding the FrameTime of all contained frames.
/// </summary>
public float TotalLength
{
get
{
float sum = 0;
for (int i = 0; i < this.Count; i++)
{
AnimationFrame af = this[i];
sum += af.FrameLength;
}
return sum;
}
}
#endregion
#region Methods
#region Constructors
#region XML Docs
/// <summary>
/// Creates an empty AnimationChain.
/// </summary>
#endregion
public AnimationChain()
: base()
{ }
#region XML Docs
/// <summary>
/// Creates a new AnimationChain with the argument capacity.
/// </summary>
/// <param name="capacity">Sets the initial capacity. Used to reduce memory allocation.</param>
#endregion
public AnimationChain(int capacity)
: base(capacity)
{ }
#endregion
#region Public Methods
public AnimationChain Clone()
{
AnimationChain animationChain = new AnimationChain();
foreach (AnimationFrame animationFrame in this)
{
animationChain.Add(animationFrame.Clone());
}
animationChain.ParentGifFileName = ParentGifFileName;
animationChain.ParentAchxFileName = ParentAchxFileName;
animationChain.mIndexInLoadedAchx = mIndexInLoadedAchx;
animationChain.mName = this.mName;
return animationChain;
}
#region XML Docs
/// <summary>
/// Searches for and returns the AnimationFrame with its Name matching
/// the nameToSearchFor argument, or null if none are found.
/// </summary>
/// <param name="nameToSearchFor">The name of the AnimationFrame to search for.</param>
/// <returns>The AnimationFrame with matching name, or null if none exists.</returns>
#endregion
public AnimationFrame FindByName(string nameToSearchFor)
{
for (int i = 0; i < this.Count; i++)
{
AnimationFrame af = this[i];
if (af.Texture.Name == nameToSearchFor)
return af;
}
return null;
}
#region XML Docs
/// <summary>
/// Returns the shortest absolute number of frames between the two argument frame numbers. This
/// method moves forward and backward and considers looping.
/// </summary>
/// <param name="frame1">The index of the first frame.</param>
/// <param name="frame2">The index of the second frame.</param>
/// <returns>The positive or negative number of frames between the two arguments.</returns>
#endregion
public int FrameToFrame(int frame1, int frame2)
{
int difference = frame2 - frame1;
if (difference > this.Count / 2.0)
difference -= this.Count;
else if (difference < -this.Count / 2.0)
difference += this.Count;
return difference;
}
public void ReplaceTexture(Texture2D oldTexture, Texture2D newTexture)
{
for (int i = 0; i < this.Count; i++)
{
if (this[i].Texture == oldTexture)
{
this[i].Texture = newTexture;
this[i].TextureName = newTexture.Name;
}
}
}
public override string ToString()
{
return Name + " (" + Count + ")";
}
#endregion
#endregion
#region IEquatable<AnimationChain> Members
bool IEquatable<AnimationChain>.Equals(AnimationChain other)
{
return this == other;
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XslCompiledTransform.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <spec>http://webdata/xml/specs/XslCompiledTransform.xml</spec>
//------------------------------------------------------------------------------
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Security.Permissions;
using System.Xml.XPath;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.Runtime;
using System.Xml.Xsl.Xslt;
using System.Runtime.Versioning;
using System.Xml.XmlConfiguration;
namespace System.Xml.Xsl {
#if ! HIDE_XSL
//----------------------------------------------------------------------------------------------------
// Clarification on null values in this API:
// stylesheet, stylesheetUri - cannot be null
// settings - if null, XsltSettings.Default will be used
// stylesheetResolver - if null, XmlNullResolver will be used for includes/imports.
// However, if the principal stylesheet is given by its URI, that
// URI will be resolved using XmlUrlResolver (for compatibility
// with XslTransform and XmlReader).
// typeBuilder - cannot be null
// scriptAssemblyPath - can be null only if scripts are disabled
// compiledStylesheet - cannot be null
// executeMethod, queryData - cannot be null
// earlyBoundTypes - null means no script types
// documentResolver - if null, XmlNullResolver will be used
// input, inputUri - cannot be null
// arguments - null means no arguments
// results, resultsFile - cannot be null
//----------------------------------------------------------------------------------------------------
public sealed class XslCompiledTransform {
// Reader settings used when creating XmlReader from inputUri
private static readonly XmlReaderSettings ReaderSettings = null;
// Permission set that contains Reflection [MemberAccess] permissions
private static readonly PermissionSet MemberAccessPermissionSet;
// Version for GeneratedCodeAttribute
private const string Version = ThisAssembly.Version;
static XslCompiledTransform() {
MemberAccessPermissionSet = new PermissionSet(PermissionState.None);
MemberAccessPermissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
ReaderSettings = new XmlReaderSettings();
}
// Options of compilation
private bool enableDebug = false;
// Results of compilation
private CompilerResults compilerResults = null;
private XmlWriterSettings outputSettings = null;
private QilExpression qil = null;
// Executable command for the compiled stylesheet
private XmlILCommand command = null;
public XslCompiledTransform() {}
public XslCompiledTransform(bool enableDebug) {
this.enableDebug = enableDebug;
}
/// <summary>
/// This function is called on every recompilation to discard all previous results
/// </summary>
private void Reset() {
this.compilerResults = null;
this.outputSettings = null;
this.qil = null;
this.command = null;
}
internal CompilerErrorCollection Errors {
get { return this.compilerResults != null ? this.compilerResults.Errors : null; }
}
/// <summary>
/// Writer settings specified in the stylesheet
/// </summary>
public XmlWriterSettings OutputSettings {
get {
return this.outputSettings;
}
}
public TempFileCollection TemporaryFiles {
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
get { return this.compilerResults != null ? this.compilerResults.TempFiles : null; }
}
//------------------------------------------------
// Load methods
//------------------------------------------------
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
public void Load(XmlReader stylesheet) {
Reset();
LoadInternal(stylesheet, XsltSettings.Default, XsltConfigSection.CreateDefaultResolver());
}
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
public void Load(XmlReader stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) {
Reset();
LoadInternal(stylesheet, settings, stylesheetResolver);
}
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
public void Load(IXPathNavigable stylesheet) {
Reset();
LoadInternal(stylesheet, XsltSettings.Default, XsltConfigSection.CreateDefaultResolver());
}
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
public void Load(IXPathNavigable stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) {
Reset();
LoadInternal(stylesheet, settings, stylesheetResolver);
}
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public void Load(string stylesheetUri) {
Reset();
if (stylesheetUri == null) {
throw new ArgumentNullException("stylesheetUri");
}
LoadInternal(stylesheetUri, XsltSettings.Default, XsltConfigSection.CreateDefaultResolver());
}
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public void Load(string stylesheetUri, XsltSettings settings, XmlResolver stylesheetResolver) {
Reset();
if (stylesheetUri == null) {
throw new ArgumentNullException("stylesheetUri");
}
LoadInternal(stylesheetUri, settings, stylesheetResolver);
}
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
private CompilerResults LoadInternal(object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) {
if (stylesheet == null) {
throw new ArgumentNullException("stylesheet");
}
if (settings == null) {
settings = XsltSettings.Default;
}
CompileXsltToQil(stylesheet, settings, stylesheetResolver);
CompilerError error = GetFirstError();
if (error != null) {
throw new XslLoadException(error);
}
if (!settings.CheckOnly) {
CompileQilToMsil(settings);
}
return this.compilerResults;
}
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
private void CompileXsltToQil(object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) {
this.compilerResults = new Compiler(settings, this.enableDebug, null).Compile(stylesheet, stylesheetResolver, out this.qil);
}
/// <summary>
/// Returns the first compiler error except warnings
/// </summary>
private CompilerError GetFirstError() {
foreach (CompilerError error in compilerResults.Errors) {
if (!error.IsWarning) {
return error;
}
}
return null;
}
private void CompileQilToMsil(XsltSettings settings) {
this.command = new XmlILGenerator().Generate(this.qil, /*typeBuilder:*/null);
this.outputSettings = this.command.StaticData.DefaultWriterSettings;
this.qil = null;
}
//------------------------------------------------
// Compile stylesheet to a TypeBuilder
//------------------------------------------------
private static volatile ConstructorInfo GeneratedCodeCtor;
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public static CompilerErrorCollection CompileToType(XmlReader stylesheet, XsltSettings settings, XmlResolver stylesheetResolver, bool debug, TypeBuilder typeBuilder, string scriptAssemblyPath) {
if (stylesheet == null)
throw new ArgumentNullException("stylesheet");
if (typeBuilder == null)
throw new ArgumentNullException("typeBuilder");
if (settings == null)
settings = XsltSettings.Default;
if (settings.EnableScript && scriptAssemblyPath == null)
throw new ArgumentNullException("scriptAssemblyPath");
if (scriptAssemblyPath != null)
scriptAssemblyPath = Path.GetFullPath(scriptAssemblyPath);
QilExpression qil;
CompilerErrorCollection errors = new Compiler(settings, debug, scriptAssemblyPath).Compile(stylesheet, stylesheetResolver, out qil).Errors;
if (!errors.HasErrors) {
// Mark the type with GeneratedCodeAttribute to identify its origin
if (GeneratedCodeCtor == null)
GeneratedCodeCtor = typeof(GeneratedCodeAttribute).GetConstructor(new Type[] { typeof(string), typeof(string) });
typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(GeneratedCodeCtor,
new object[] { typeof(XslCompiledTransform).FullName, Version }));
new XmlILGenerator().Generate(qil, typeBuilder);
}
return errors;
}
//------------------------------------------------
// Load compiled stylesheet from a Type
//------------------------------------------------
public void Load(Type compiledStylesheet) {
Reset();
if (compiledStylesheet == null)
throw new ArgumentNullException("compiledStylesheet");
object[] customAttrs = compiledStylesheet.GetCustomAttributes(typeof(GeneratedCodeAttribute), /*inherit:*/false);
GeneratedCodeAttribute generatedCodeAttr = customAttrs.Length > 0 ? (GeneratedCodeAttribute)customAttrs[0] : null;
// If GeneratedCodeAttribute is not there, it is not a compiled stylesheet class
if (generatedCodeAttr != null && generatedCodeAttr.Tool == typeof(XslCompiledTransform).FullName) {
if(new Version(Version).CompareTo(new Version(generatedCodeAttr.Version)) < 0) {
throw new ArgumentException(Res.GetString(Res.Xslt_IncompatibleCompiledStylesheetVersion, generatedCodeAttr.Version, Version), "compiledStylesheet");
}
FieldInfo fldData = compiledStylesheet.GetField(XmlQueryStaticData.DataFieldName, BindingFlags.Static | BindingFlags.NonPublic);
FieldInfo fldTypes = compiledStylesheet.GetField(XmlQueryStaticData.TypesFieldName, BindingFlags.Static | BindingFlags.NonPublic);
// If private fields are not there, it is not a compiled stylesheet class
if (fldData != null && fldTypes != null) {
if (System.Xml.XmlConfiguration.XsltConfigSection.EnableMemberAccessForXslCompiledTransform)
{
// Need MemberAccess reflection permission to access a private data field and create a delegate
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
}
// Retrieve query static data from the type
byte[] queryData = fldData.GetValue(/*this:*/null) as byte[];
if (queryData != null) {
MethodInfo executeMethod = compiledStylesheet.GetMethod("Execute", BindingFlags.Static | BindingFlags.NonPublic);
Type[] earlyBoundTypes = (Type[])fldTypes.GetValue(/*this:*/null);
// Load the stylesheet
Load(executeMethod, queryData, earlyBoundTypes);
return;
}
}
}
// Throw an exception if the command was not loaded
if (this.command == null)
throw new ArgumentException(Res.GetString(Res.Xslt_NotCompiledStylesheet, compiledStylesheet.FullName), "compiledStylesheet");
}
public void Load(MethodInfo executeMethod, byte[] queryData, Type[] earlyBoundTypes) {
Reset();
if (executeMethod == null)
throw new ArgumentNullException("executeMethod");
if (queryData == null)
throw new ArgumentNullException("queryData");
// earlyBoundTypes may be null
if (!System.Xml.XmlConfiguration.XsltConfigSection.EnableMemberAccessForXslCompiledTransform)
{
// make sure we have permission to create the delegate if the type is not visible.
// If the declaring type is null we cannot check for visibility.
// NOTE: a DynamicMethod will always have a DeclaringType == null. DynamicMethods will do demand on their own if skipVisibility is true.
if (executeMethod.DeclaringType != null && !executeMethod.DeclaringType.IsVisible)
{
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
}
}
DynamicMethod dm = executeMethod as DynamicMethod;
Delegate delExec = (dm != null) ? dm.CreateDelegate(typeof(ExecuteDelegate)) : Delegate.CreateDelegate(typeof(ExecuteDelegate), executeMethod);
this.command = new XmlILCommand((ExecuteDelegate)delExec, new XmlQueryStaticData(queryData, earlyBoundTypes));
this.outputSettings = this.command.StaticData.DefaultWriterSettings;
}
//------------------------------------------------
// Transform methods which take an IXPathNavigable
//------------------------------------------------
public void Transform(IXPathNavigable input, XmlWriter results) {
CheckArguments(input, results);
Transform(input, (XsltArgumentList)null, results, XsltConfigSection.CreateDefaultResolver());
}
public void Transform(IXPathNavigable input, XsltArgumentList arguments, XmlWriter results) {
CheckArguments(input, results);
Transform(input, arguments, results, XsltConfigSection.CreateDefaultResolver());
}
public void Transform(IXPathNavigable input, XsltArgumentList arguments, TextWriter results) {
CheckArguments(input, results);
using (XmlWriter writer = XmlWriter.Create(results, OutputSettings)) {
Transform(input, arguments, writer, XsltConfigSection.CreateDefaultResolver());
writer.Close();
}
}
public void Transform(IXPathNavigable input, XsltArgumentList arguments, Stream results) {
CheckArguments(input, results);
using (XmlWriter writer = XmlWriter.Create(results, OutputSettings)) {
Transform(input, arguments, writer, XsltConfigSection.CreateDefaultResolver());
writer.Close();
}
}
//------------------------------------------------
// Transform methods which take an XmlReader
//------------------------------------------------
public void Transform(XmlReader input, XmlWriter results) {
CheckArguments(input, results);
Transform(input, (XsltArgumentList)null, results, XsltConfigSection.CreateDefaultResolver());
}
public void Transform(XmlReader input, XsltArgumentList arguments, XmlWriter results) {
CheckArguments(input, results);
Transform(input, arguments, results, XsltConfigSection.CreateDefaultResolver());
}
public void Transform(XmlReader input, XsltArgumentList arguments, TextWriter results) {
CheckArguments(input, results);
using (XmlWriter writer = XmlWriter.Create(results, OutputSettings)) {
Transform(input, arguments, writer, XsltConfigSection.CreateDefaultResolver());
writer.Close();
}
}
public void Transform(XmlReader input, XsltArgumentList arguments, Stream results) {
CheckArguments(input, results);
using (XmlWriter writer = XmlWriter.Create(results, OutputSettings)) {
Transform(input, arguments, writer, XsltConfigSection.CreateDefaultResolver());
writer.Close();
}
}
//------------------------------------------------
// Transform methods which take a uri
// SxS Note: Annotations should propagate to the caller to have him either check that
// the passed URIs are SxS safe or decide that they don't have to be SxS safe and
// suppress the message.
//------------------------------------------------
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")]
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public void Transform(string inputUri, XmlWriter results) {
CheckArguments(inputUri, results);
using (XmlReader reader = XmlReader.Create(inputUri, ReaderSettings)) {
Transform(reader, (XsltArgumentList)null, results, XsltConfigSection.CreateDefaultResolver());
}
}
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")]
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public void Transform(string inputUri, XsltArgumentList arguments, XmlWriter results) {
CheckArguments(inputUri, results);
using (XmlReader reader = XmlReader.Create(inputUri, ReaderSettings)) {
Transform(reader, arguments, results, XsltConfigSection.CreateDefaultResolver());
}
}
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")]
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public void Transform(string inputUri, XsltArgumentList arguments, TextWriter results) {
CheckArguments(inputUri, results);
using (XmlReader reader = XmlReader.Create(inputUri, ReaderSettings))
using (XmlWriter writer = XmlWriter.Create(results, OutputSettings)) {
Transform(reader, arguments, writer, XsltConfigSection.CreateDefaultResolver());
writer.Close();
}
}
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")]
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public void Transform(string inputUri, XsltArgumentList arguments, Stream results) {
CheckArguments(inputUri, results);
using (XmlReader reader = XmlReader.Create(inputUri, ReaderSettings))
using (XmlWriter writer = XmlWriter.Create(results, OutputSettings)) {
Transform(reader, arguments, writer, XsltConfigSection.CreateDefaultResolver());
writer.Close();
}
}
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")]
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public void Transform(string inputUri, string resultsFile) {
if (inputUri == null)
throw new ArgumentNullException("inputUri");
if (resultsFile == null)
throw new ArgumentNullException("resultsFile");
// SQLBUDT 276415: Prevent wiping out the content of the input file if the output file is the same
using (XmlReader reader = XmlReader.Create(inputUri, ReaderSettings))
using (XmlWriter writer = XmlWriter.Create(resultsFile, OutputSettings)) {
Transform(reader, (XsltArgumentList)null, writer, XsltConfigSection.CreateDefaultResolver());
writer.Close();
}
}
//------------------------------------------------
// Main Transform overloads
//------------------------------------------------
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
public void Transform(XmlReader input, XsltArgumentList arguments, XmlWriter results, XmlResolver documentResolver) {
CheckArguments(input, results);
CheckCommand();
this.command.Execute((object)input, documentResolver, arguments, results);
}
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
public void Transform(IXPathNavigable input, XsltArgumentList arguments, XmlWriter results, XmlResolver documentResolver) {
CheckArguments(input, results);
CheckCommand();
this.command.Execute((object)input.CreateNavigator(), documentResolver, arguments, results);
}
//------------------------------------------------
// Helper methods
//------------------------------------------------
private static void CheckArguments(object input, object results) {
if (input == null)
throw new ArgumentNullException("input");
if (results == null)
throw new ArgumentNullException("results");
}
private static void CheckArguments(string inputUri, object results) {
if (inputUri == null)
throw new ArgumentNullException("inputUri");
if (results == null)
throw new ArgumentNullException("results");
}
private void CheckCommand() {
if (this.command == null) {
throw new InvalidOperationException(Res.GetString(Res.Xslt_NoStylesheetLoaded));
}
}
//------------------------------------------------
// Test suites entry points
//------------------------------------------------
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
private QilExpression TestCompile(object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) {
Reset();
CompileXsltToQil(stylesheet, settings, stylesheetResolver);
return qil;
}
private void TestGenerate(XsltSettings settings) {
Debug.Assert(qil != null, "You must compile to Qil first");
CompileQilToMsil(settings);
}
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
private void Transform(string inputUri, XsltArgumentList arguments, XmlWriter results, XmlResolver documentResolver) {
command.Execute(inputUri, documentResolver, arguments, results);
}
internal static void PrintQil(object qil, XmlWriter xw, bool printComments, bool printTypes, bool printLineInfo) {
QilExpression qilExpr = (QilExpression)qil;
QilXmlWriter.Options options = QilXmlWriter.Options.None;
QilValidationVisitor.Validate(qilExpr);
if (printComments) options |= QilXmlWriter.Options.Annotations;
if (printTypes) options |= QilXmlWriter.Options.TypeInfo;
if (printLineInfo) options |= QilXmlWriter.Options.LineInfo;
QilXmlWriter qw = new QilXmlWriter(xw, options);
qw.ToXml(qilExpr);
xw.Flush();
}
}
#endif // ! HIDE_XSL
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion License
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
namespace Irony.Parsing
{
public enum ParseMode
{
/// <summary>
/// Default, continuous input file
/// </summary>
File,
/// <summary>
/// Line-by-line scanning in VS integration for syntax highlighting
/// </summary>
VsLineScan,
/// <summary>
/// Line-by-line from console
/// </summary>
CommandLine,
}
[Flags]
public enum ParseOptions
{
Reserved = 0x01,
/// <summary>
/// Run code analysis; effective only in Module mode
/// </summary>
AnalyzeCode = 0x10,
}
public enum ParserStatus
{
/// <summary>
/// Initial state
/// </summary>
Init,
Parsing,
/// <summary>
/// Previewing tokens
/// </summary>
Previewing,
/// <summary>
/// Recovering from error
/// </summary>
Recovering,
Accepted,
AcceptedPartial,
Error,
}
/// <summary>
/// A struct used for packing/unpacking ScannerState int value; used for VS integration.
/// When Terminal produces incomplete token, it sets
/// this state to non-zero value; this value identifies this terminal as the one who will continue scanning when
/// it resumes, and the terminal's internal state when there may be several types of multi-line tokens for one terminal.
/// For ex., there maybe several types of string literal like in Python.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct VsScannerStateMap
{
[FieldOffset(0)]
public int Value;
/// <summary>
/// 1-based index of active multiline term in MultilineTerminals
/// </summary>
[FieldOffset(0)]
public byte TerminalIndex;
/// <summary>
/// Terminal subtype (used in StringLiteral to identify string kind)
/// </summary>
[FieldOffset(1)]
public byte TokenSubType;
[FieldOffset(2)]
public short TerminalFlags;
}
/// <summary>
/// The purpose of this class is to provide a container for information shared
/// between parser, scanner and token filters.
/// </summary>
public partial class ParsingContext
{
public readonly LanguageData Language;
public readonly Parser Parser;
/// <summary>
/// Defaults to Grammar.DefaultCulture, might be changed by app code
/// </summary>
public CultureInfo Culture;
/// <summary>
/// Maximum error count to report
/// </summary>
public int MaxErrors = 20;
public ParseMode Mode = ParseMode.File;
public ParseOptions Options;
public bool TracingEnabled;
#region properties and fields
public readonly TokenStack OpenBraces = new TokenStack();
/// <summary>
/// Values dictionary to use by custom language implementations to save some temporary values during parsing
/// </summary>
public readonly Dictionary<string, object> Values = new Dictionary<string, object>();
/// <summary>
/// Accumulated comment tokens
/// </summary>
public TokenList CurrentCommentTokens = new TokenList();
/// <summary>
/// List for terminals - for current parser state and current input char
/// </summary>
public TerminalList CurrentTerminals = new TerminalList();
/// <summary>
/// The token just scanned by Scanner
/// </summary>
public Token CurrentToken;
/// <summary>
/// Error flag, once set remains set
/// </summary>
public bool HasErrors;
public ParserTrace ParserTrace = new ParserTrace();
/// <summary>
/// Location of last line start
/// </summary>
public SourceLocation PreviousLineStart;
public Token PreviousToken;
public ISourceStream Source;
public int TabWidth = 8;
/// <summary>
/// State variable used in line scanning mode for VS integration
/// </summary>
public VsScannerStateMap VsLineScanState;
internal readonly ParserStack ParserStack = new ParserStack();
internal TokenStack BufferedTokens = new TokenStack();
/// <summary>
/// Stream of tokens after filter
/// </summary>
internal IEnumerator<Token> FilteredTokens;
internal TokenStack PreviewTokens = new TokenStack();
internal ParsingEventArgs SharedParsingEventArgs;
internal ValidateTokenEventArgs SharedValidateTokenEventArgs;
internal TokenFilterList TokenFilters = new TokenFilterList();
public ParseTreeNode CurrentParserInput { get; internal set; }
public ParserState CurrentParserState { get; internal set; }
public ParseTree CurrentParseTree { get; internal set; }
public ParserStatus Status { get; internal set; }
#endregion properties and fields
#region constructors
public ParsingContext(Parser parser)
{
this.Parser = parser;
this.Language = this.Parser.Language;
this.Culture = this.Language.Grammar.DefaultCulture;
// This might be a problem for multi-threading - if we have several contexts on parallel threads with different culture.
// Resources.Culture is static property (this is not Irony's fault, this is auto-generated file).
Resources.Culture = this.Culture;
this.SharedParsingEventArgs = new ParsingEventArgs(this);
this.SharedValidateTokenEventArgs = new ValidateTokenEventArgs(this);
}
#endregion constructors
#region Events: TokenCreated
public event EventHandler<ParsingEventArgs> TokenCreated;
internal void OnTokenCreated()
{
if (this.TokenCreated != null)
this.TokenCreated(this, this.SharedParsingEventArgs);
}
#endregion Events: TokenCreated
#region Error handling and tracing
public void AddParserError(string message, params object[] args)
{
var location = this.CurrentParserInput == null ? this.Source.Location : this.CurrentParserInput.Span.Location;
this.HasErrors = true;
this.AddParserMessage(ErrorLevel.Error, location, message, args);
}
public void AddParserMessage(ErrorLevel level, SourceLocation location, string message, params object[] args)
{
if (this.CurrentParseTree == null)
return;
if (this.CurrentParseTree.ParserMessages.Count >= this.MaxErrors)
return;
if (args != null && args.Length > 0)
message = string.Format(message, args);
this.CurrentParseTree.ParserMessages.Add(new LogMessage(level, location, message, this.CurrentParserState));
if (this.TracingEnabled)
this.AddTrace(true, message);
}
public void AddTrace(string message, params object[] args)
{
this.AddTrace(false, message, args);
}
public void AddTrace(bool asError, string message, params object[] args)
{
if (!this.TracingEnabled)
return;
if (args != null && args.Length > 0)
message = string.Format(message, args);
this.ParserTrace.Add(new ParserTraceEntry(this.CurrentParserState, this.ParserStack.Top, this.CurrentParserInput, message, asError));
}
public Token CreateErrorToken(string message, params object[] args)
{
if (args != null && args.Length > 0)
message = string.Format(message, args);
return this.Source.CreateToken(this.Language.Grammar.SyntaxError, message);
}
#region comments
// Computes set of expected terms in a parser state. While there may be extended list of symbols expected at some point,
// we want to reorganize and reduce it. For example, if the current state expects all arithmetic operators as an input,
// it would be better to not list all operators (+, -, *, /, etc) but simply put "operator" covering them all.
// To achieve this grammar writer can group operators (or any other terminals) into named groups using Grammar's methods
// AddTermReportGroup, AddNoReportGroup etc. Then instead of reporting each operator separately, Irony would include
// a single "group name" to represent them all.
// The "expected report set" is not computed during parser construction (it would take considerable time),
// but does it on demand during parsing, when error is detected and the expected set is actually needed for error message.
// Multi-threading concerns. When used in multi-threaded environment (web server), the LanguageData would be shared in
// application-wide cache to avoid rebuilding the parser data on every request. The LanguageData is immutable, except
// this one case - the expected sets are constructed late by CoreParser on the when-needed basis.
// We don't do any locking here, just compute the set and on return from this function the state field is assigned.
// We assume that this field assignment is an atomic, concurrency-safe operation. The worst thing that might happen
// is "double-effort" when two threads start computing the same set around the same time, and the last one to finish would
// leave its result in the state field.
#endregion comments
internal static StringSet ComputeGroupedExpectedSetForState(Grammar grammar, ParserState state)
{
var terms = new TerminalSet();
terms.UnionWith(state.ExpectedTerminals);
var result = new StringSet();
// Eliminate no-report terminals
foreach (var group in grammar.TermReportGroups)
{
if (group.GroupType == TermReportGroupType.DoNotReport)
terms.ExceptWith(group.Terminals);
}
// Add normal and operator groups
foreach (var group in grammar.TermReportGroups)
{
if ((group.GroupType == TermReportGroupType.Normal || group.GroupType == TermReportGroupType.Operator) &&
terms.Overlaps(group.Terminals))
{
result.Add(group.Alias);
terms.ExceptWith(group.Terminals);
}
}
// Add remaining terminals "as is"
foreach (var terminal in terms)
{
result.Add(terminal.ErrorAlias);
}
return result;
}
#endregion Error handling and tracing
public SourceSpan ComputeStackRangeSpan(int nodeCount)
{
if (nodeCount == 0)
return new SourceSpan(this.CurrentParserInput.Span.Location, this.CurrentParserInput.Span.Location);
var first = this.ParserStack[this.ParserStack.Count - nodeCount];
var last = this.ParserStack.Top;
return new SourceSpan(first.Span.Location, last.Span.EndLocation);
}
public void SetSourceLocation(SourceLocation location)
{
foreach (var filter in this.TokenFilters)
{
filter.OnSetSourceLocation(location);
}
this.Source.Location = location;
}
internal void Reset()
{
this.CurrentParserState = this.Parser.InitialState;
this.CurrentParserInput = null;
this.CurrentCommentTokens = new TokenList();
this.ParserStack.Clear();
this.HasErrors = false;
this.ParserStack.Push(new ParseTreeNode(this.CurrentParserState));
this.CurrentParseTree = null;
this.OpenBraces.Clear();
this.ParserTrace.Clear();
this.CurrentTerminals.Clear();
this.CurrentToken = null;
this.PreviousToken = null;
this.PreviousLineStart = new SourceLocation(0, -1, 0);
this.BufferedTokens.Clear();
this.PreviewTokens.Clear();
this.Values.Clear();
foreach (var filter in this.TokenFilters)
{
filter.Reset();
}
}
#region Expected term set computations
public StringSet GetExpectedTermSet()
{
if (this.CurrentParserState == null)
return new StringSet();
// See note about multi-threading issues in ComputeReportedExpectedSet comments.
if (this.CurrentParserState.ReportedExpectedSet == null)
this.CurrentParserState.ReportedExpectedSet = Construction.ParserDataBuilder.ComputeGroupedExpectedSetForState(this.Language.Grammar, this.CurrentParserState);
// Filter out closing braces which are not expected based on previous input.
// While the closing parenthesis ")" might be expected term in a state in general,
// if there was no opening parenthesis in preceding input then we would not
// expect a closing one.
var expectedSet = FilterBracesInExpectedSet(this.CurrentParserState.ReportedExpectedSet);
return expectedSet;
}
private StringSet FilterBracesInExpectedSet(StringSet stateExpectedSet)
{
var result = new StringSet();
result.UnionWith(stateExpectedSet);
// Find what brace we expect
var nextClosingBrace = string.Empty;
if (this.OpenBraces.Count > 0)
{
var lastOpenBraceTerm = this.OpenBraces.Peek().KeyTerm;
var nextClosingBraceTerm = lastOpenBraceTerm.IsPairFor as KeyTerm;
if (nextClosingBraceTerm != null)
nextClosingBrace = nextClosingBraceTerm.Text;
}
// Now check all closing braces in result set, and leave only nextClosingBrace
foreach (var term in this.Language.Grammar.KeyTerms.Values)
{
if (term.Flags.IsSet(TermFlags.IsCloseBrace))
{
var brace = term.Text;
if (result.Contains(brace) && brace != nextClosingBrace)
result.Remove(brace);
}
}
return result;
}
#endregion Expected term set computations
}
}
| |
// 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.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
/////////////////////////////////////////////////////////////////////////////////
// Defines the structure used when binding types
// CheckConstraints options.
[Flags]
internal enum CheckConstraintsFlags
{
None = 0x00,
Outer = 0x01,
NoDupErrors = 0x02,
NoErrors = 0x04,
}
/////////////////////////////////////////////////////////////////////////////////
// TypeBind has static methods to accomplish most tasks.
//
// For some of these tasks there are also instance methods. The instance
// method versions don't report not found errors (they may report others) but
// instead record error information in the TypeBind instance. Call the
// ReportErrors method to report recorded errors.
internal static class TypeBind
{
// Check the constraints of any type arguments in the given Type.
public static bool CheckConstraints(CSemanticChecker checker, ErrorHandling errHandling, CType type, CheckConstraintsFlags flags)
{
type = type.GetNakedType(false);
if (type is NullableType nub)
{
type = nub.GetAts();
}
if (!(type is AggregateType ats))
return true;
if (ats.GetTypeArgsAll().Count == 0)
{
// Common case: there are no type vars, so there are no constraints.
ats.fConstraintsChecked = true;
ats.fConstraintError = false;
return true;
}
if (ats.fConstraintsChecked)
{
// Already checked.
if (!ats.fConstraintError || (flags & CheckConstraintsFlags.NoDupErrors) != 0)
{
// No errors or no need to report errors again.
return !ats.fConstraintError;
}
}
TypeArray typeVars = ats.getAggregate().GetTypeVars();
TypeArray typeArgsThis = ats.GetTypeArgsThis();
TypeArray typeArgsAll = ats.GetTypeArgsAll();
Debug.Assert(typeVars.Count == typeArgsThis.Count);
if (!ats.fConstraintsChecked)
{
ats.fConstraintsChecked = true;
ats.fConstraintError = false;
}
// Check the outer type first. If CheckConstraintsFlags.Outer is not specified and the
// outer type has already been checked then don't bother checking it.
if (ats.outerType != null && ((flags & CheckConstraintsFlags.Outer) != 0 || !ats.outerType.fConstraintsChecked))
{
CheckConstraints(checker, errHandling, ats.outerType, flags);
ats.fConstraintError |= ats.outerType.fConstraintError;
}
if (typeVars.Count > 0)
ats.fConstraintError |= !CheckConstraintsCore(checker, errHandling, ats.getAggregate(), typeVars, typeArgsThis, typeArgsAll, null, (flags & CheckConstraintsFlags.NoErrors));
// Now check type args themselves.
for (int i = 0; i < typeArgsThis.Count; i++)
{
CType arg = typeArgsThis[i].GetNakedType(true);
if (arg is AggregateType atArg && !atArg.fConstraintsChecked)
{
CheckConstraints(checker, errHandling, atArg, flags | CheckConstraintsFlags.Outer);
if (atArg.fConstraintError)
ats.fConstraintError = true;
}
}
return !ats.fConstraintError;
}
////////////////////////////////////////////////////////////////////////////////
// Check the constraints on the method instantiation.
public static void CheckMethConstraints(CSemanticChecker checker, ErrorHandling errCtx, MethWithInst mwi)
{
Debug.Assert(mwi.Meth() != null && mwi.GetType() != null && mwi.TypeArgs != null);
Debug.Assert(mwi.Meth().typeVars.Count == mwi.TypeArgs.Count);
Debug.Assert(mwi.GetType().getAggregate() == mwi.Meth().getClass());
if (mwi.TypeArgs.Count > 0)
{
CheckConstraintsCore(checker, errCtx, mwi.Meth(), mwi.Meth().typeVars, mwi.TypeArgs, mwi.GetType().GetTypeArgsAll(), mwi.TypeArgs, CheckConstraintsFlags.None);
}
}
////////////////////////////////////////////////////////////////////////////////
// Check whether typeArgs satisfies the constraints of typeVars. The
// typeArgsCls and typeArgsMeth are used for substitution on the bounds. The
// tree and symErr are used for error reporting.
private static bool CheckConstraintsCore(CSemanticChecker checker, ErrorHandling errHandling, Symbol symErr, TypeArray typeVars, TypeArray typeArgs, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags)
{
Debug.Assert(typeVars.Count == typeArgs.Count);
Debug.Assert(typeVars.Count > 0);
Debug.Assert(flags == CheckConstraintsFlags.None || flags == CheckConstraintsFlags.NoErrors);
bool fError = false;
for (int i = 0; i < typeVars.Count; i++)
{
// Empty bounds should be set to object.
TypeParameterType var = (TypeParameterType)typeVars[i];
CType arg = typeArgs[i];
bool fOK = CheckSingleConstraint(checker, errHandling, symErr, var, arg, typeArgsCls, typeArgsMeth, flags);
fError |= !fOK;
}
return !fError;
}
private static bool CheckSingleConstraint(CSemanticChecker checker, ErrorHandling errHandling, Symbol symErr, TypeParameterType var, CType arg, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags)
{
bool fReportErrors = 0 == (flags & CheckConstraintsFlags.NoErrors);
if (arg is ErrorType)
{
// Error should have been reported previously.
return false;
}
if (arg is PointerType)
{
if (fReportErrors)
{
throw errHandling.Error(ErrorCode.ERR_BadTypeArgument, arg);
}
return false;
}
if (arg.isStaticClass())
{
if (fReportErrors)
{
checker.ReportStaticClassError(null, arg, ErrorCode.ERR_GenericArgIsStaticClass);
}
return false;
}
bool fError = false;
if (var.HasRefConstraint() && !arg.IsRefType())
{
if (fReportErrors)
{
throw errHandling.Error(ErrorCode.ERR_RefConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg);
}
fError = true;
}
TypeArray bnds = checker.SymbolLoader.GetTypeManager().SubstTypeArray(var.GetBounds(), typeArgsCls, typeArgsMeth);
int itypeMin = 0;
if (var.HasValConstraint())
{
// If we have a type variable that is constrained to a value type, then we
// want to check if its a nullable type, so that we can report the
// constraint error below. In order to do this however, we need to check
// that either the type arg is not a value type, or it is a nullable type.
//
// To check whether or not its a nullable type, we need to get the resolved
// bound from the type argument and check against that.
if (!arg.IsValType() || arg is NullableType)
{
if (fReportErrors)
{
throw errHandling.Error(ErrorCode.ERR_ValConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg);
}
fError = true;
}
// Since FValCon() is set it is redundant to check System.ValueType as well.
if (bnds.Count != 0 && bnds[0].isPredefType(PredefinedType.PT_VALUE))
{
itypeMin = 1;
}
}
for (int j = itypeMin; j < bnds.Count; j++)
{
CType typeBnd = bnds[j];
if (!SatisfiesBound(checker, arg, typeBnd))
{
if (fReportErrors)
{
// The bound isn't satisfied because of a constraint type. Explain to the user why not.
// There are 4 main cases, based on the type of the supplied type argument:
// - reference type, or type parameter known to be a reference type
// - nullable type, from which there is a boxing conversion to the constraint type(see below for details)
// - type variable
// - value type
// These cases are broken out because: a) The sets of conversions which can be used
// for constraint satisfaction is different based on the type argument supplied,
// and b) Nullable is one funky type, and user's can use all the help they can get
// when using it.
ErrorCode error;
if (arg.IsRefType())
{
// A reference type can only satisfy bounds to types
// to which they have an implicit reference conversion
error = ErrorCode.ERR_GenericConstraintNotSatisfiedRefType;
}
else if (arg is NullableType nubArg && checker.SymbolLoader.HasBaseConversion(nubArg.GetUnderlyingType(), typeBnd)) // This is inlining FBoxingConv
{
// nullable types do not satisfy bounds to every type that they are boxable to
// They only satisfy bounds of object and ValueType
if (typeBnd.isPredefType(PredefinedType.PT_ENUM) || nubArg.GetUnderlyingType() == typeBnd)
{
// Nullable types don't satisfy bounds of EnumType, or the underlying type of the enum
// even though the conversion from Nullable to these types is a boxing conversion
// This is a rare case, because these bounds can never be directly stated ...
// These bounds can only occur when one type paramter is constrained to a second type parameter
// and the second type parameter is instantiated with Enum or the underlying type of the first type
// parameter
error = ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum;
}
else
{
// Nullable types don't satisfy the bounds of any interface type
// even when there is a boxing conversion from the Nullable type to
// the interface type. This will be a relatively common scenario
// so we cal it out separately from the previous case.
Debug.Assert(typeBnd.isInterfaceType());
error = ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface;
}
}
else
{
// Value types can only satisfy bounds through boxing conversions.
// Note that the exceptional case of Nullable types and boxing is handled above.
error = ErrorCode.ERR_GenericConstraintNotSatisfiedValType;
}
throw errHandling.Error(error, new ErrArg(symErr), new ErrArg(typeBnd, ErrArgFlags.Unique), var, new ErrArg(arg, ErrArgFlags.Unique));
}
fError = true;
}
}
// Check the newable constraint.
if (!var.HasNewConstraint() || arg.IsValType())
{
return !fError;
}
if (arg.isClassType())
{
AggregateSymbol agg = ((AggregateType)arg).getAggregate();
// Due to late binding nature of IDE created symbols, the AggregateSymbol might not
// have all the information necessary yet, if it is not fully bound.
// by calling LookupAggMember, it will ensure that we will update all the
// information necessary at least for the given method.
checker.SymbolLoader.LookupAggMember(NameManager.GetPredefinedName(PredefinedName.PN_CTOR), agg, symbmask_t.MASK_ALL);
if (agg.HasPubNoArgCtor() && !agg.IsAbstract())
{
return !fError;
}
}
if (fReportErrors)
{
throw errHandling.Error(ErrorCode.ERR_NewConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg);
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// Determine whether the arg type satisfies the typeBnd constraint. Note that
// typeBnd could be just about any type (since we added naked type parameter
// constraints).
private static bool SatisfiesBound(CSemanticChecker checker, CType arg, CType typeBnd)
{
if (typeBnd == arg)
return true;
switch (typeBnd.GetTypeKind())
{
default:
Debug.Assert(false, "Unexpected type.");
return false;
case TypeKind.TK_VoidType:
case TypeKind.TK_PointerType:
case TypeKind.TK_ErrorType:
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_TypeParameterType:
break;
case TypeKind.TK_NullableType:
typeBnd = ((NullableType)typeBnd).GetAts();
break;
case TypeKind.TK_AggregateType:
break;
}
Debug.Assert(typeBnd is AggregateType || typeBnd is TypeParameterType || typeBnd is ArrayType);
switch (arg.GetTypeKind())
{
default:
return false;
case TypeKind.TK_ErrorType:
case TypeKind.TK_PointerType:
return false;
case TypeKind.TK_NullableType:
arg = ((NullableType)arg).GetAts();
// Fall through.
goto case TypeKind.TK_TypeParameterType;
case TypeKind.TK_TypeParameterType:
case TypeKind.TK_ArrayType:
case TypeKind.TK_AggregateType:
return checker.SymbolLoader.HasBaseConversion(arg, typeBnd);
}
}
}
}
| |
// 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 Xunit;
namespace System.Collections.Immutable.Tests
{
public abstract partial class ImmutableDictionaryTestBase : ImmutablesTestBase
{
[Fact]
public virtual void EmptyTest()
{
this.EmptyTestHelper(Empty<int, bool>(), 5);
}
[Fact]
public void ContainsTest()
{
this.ContainsTestHelper(Empty<int, string>(), 5, "foo");
}
[Fact]
public void RemoveTest()
{
this.RemoveTestHelper(Empty<int, GenericParameterHelper>(), 5);
}
[Fact]
public void SetItemTest()
{
var map = this.Empty<string, int>()
.SetItem("Microsoft", 100)
.SetItem("Corporation", 50);
Assert.Equal(2, map.Count);
map = map.SetItem("Microsoft", 200);
Assert.Equal(2, map.Count);
Assert.Equal(200, map["Microsoft"]);
// Set it to the same thing again and make sure it's all good.
var sameMap = map.SetItem("Microsoft", 200);
Assert.Same(map, sameMap);
}
[Fact]
public void SetItemsTest()
{
var template = new Dictionary<string, int>
{
{ "Microsoft", 100 },
{ "Corporation", 50 },
};
var map = this.Empty<string, int>().SetItems(template);
Assert.Equal(2, map.Count);
var changes = new Dictionary<string, int>
{
{ "Microsoft", 150 },
{ "Dogs", 90 },
};
map = map.SetItems(changes);
Assert.Equal(3, map.Count);
Assert.Equal(150, map["Microsoft"]);
Assert.Equal(50, map["Corporation"]);
Assert.Equal(90, map["Dogs"]);
map = map.SetItems(
new[] {
new KeyValuePair<string, int>("Microsoft", 80),
new KeyValuePair<string, int>("Microsoft", 70),
});
Assert.Equal(3, map.Count);
Assert.Equal(70, map["Microsoft"]);
Assert.Equal(50, map["Corporation"]);
Assert.Equal(90, map["Dogs"]);
map = this.Empty<string, int>().SetItems(new[] { // use an array for code coverage
new KeyValuePair<string, int>("a", 1), new KeyValuePair<string, int>("b", 2),
new KeyValuePair<string, int>("a", 3),
});
Assert.Equal(2, map.Count);
Assert.Equal(3, map["a"]);
Assert.Equal(2, map["b"]);
}
[Fact]
public void ContainsKeyTest()
{
this.ContainsKeyTestHelper(Empty<int, GenericParameterHelper>(), 1, new GenericParameterHelper());
}
[Fact]
public void IndexGetNonExistingKeyThrowsTest()
{
Assert.Throws<KeyNotFoundException>(() => this.Empty<int, int>()[3]);
}
[Fact]
public void IndexGetTest()
{
var map = this.Empty<int, int>().Add(3, 5);
Assert.Equal(5, map[3]);
}
/// <summary>
/// Verifies that the GetHashCode method returns the standard one.
/// </summary>
[Fact]
public void GetHashCodeTest()
{
var dictionary = Empty<string, int>();
Assert.Equal(EqualityComparer<object>.Default.GetHashCode(dictionary), dictionary.GetHashCode());
}
[Fact]
public void ICollectionOfKVMembers()
{
var dictionary = (ICollection<KeyValuePair<string, int>>)Empty<string, int>();
Assert.Throws<NotSupportedException>(() => dictionary.Add(new KeyValuePair<string, int>()));
Assert.Throws<NotSupportedException>(() => dictionary.Remove(new KeyValuePair<string, int>()));
Assert.Throws<NotSupportedException>(() => dictionary.Clear());
Assert.True(dictionary.IsReadOnly);
}
[Fact]
public void ICollectionMembers()
{
((ICollection)Empty<string, int>()).CopyTo(new object[0], 0);
var dictionary = (ICollection)Empty<string, int>().Add("a", 1);
Assert.True(dictionary.IsSynchronized);
Assert.NotNull(dictionary.SyncRoot);
Assert.Same(dictionary.SyncRoot, dictionary.SyncRoot);
var array = new object[2];
dictionary.CopyTo(array, 1);
Assert.Null(array[0]);
Assert.Equal(new DictionaryEntry("a", 1), (DictionaryEntry)array[1]);
}
[Fact]
public void IDictionaryOfKVMembers()
{
var dictionary = (IDictionary<string, int>)Empty<string, int>().Add("c", 3);
Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1));
Assert.Throws<NotSupportedException>(() => dictionary.Remove("a"));
Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2);
Assert.Throws<KeyNotFoundException>(() => dictionary["a"]);
Assert.Equal(3, dictionary["c"]);
}
[Fact]
public void IDictionaryMembers()
{
var dictionary = (IDictionary)Empty<string, int>().Add("c", 3);
Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1));
Assert.Throws<NotSupportedException>(() => dictionary.Remove("a"));
Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2);
Assert.Throws<NotSupportedException>(() => dictionary.Clear());
Assert.False(dictionary.Contains("a"));
Assert.True(dictionary.Contains("c"));
Assert.Throws<KeyNotFoundException>(() => dictionary["a"]);
Assert.Equal(3, dictionary["c"]);
Assert.True(dictionary.IsFixedSize);
Assert.True(dictionary.IsReadOnly);
Assert.Equal(new[] { "c" }, dictionary.Keys.Cast<string>().ToArray());
Assert.Equal(new[] { 3 }, dictionary.Values.Cast<int>().ToArray());
}
[Fact]
public void IDictionaryEnumerator()
{
var dictionary = (IDictionary)Empty<string, int>().Add("a", 1);
var enumerator = dictionary.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Entry, enumerator.Current);
Assert.Equal(enumerator.Key, enumerator.Entry.Key);
Assert.Equal(enumerator.Value, enumerator.Entry.Value);
Assert.Equal("a", enumerator.Key);
Assert.Equal(1, enumerator.Value);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.False(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key);
Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value);
Assert.Equal("a", enumerator.Key);
Assert.Equal(1, enumerator.Value);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void TryGetKey()
{
var dictionary = Empty<int>(StringComparer.OrdinalIgnoreCase)
.Add("a", 1);
string actualKey;
Assert.True(dictionary.TryGetKey("a", out actualKey));
Assert.Equal("a", actualKey);
Assert.True(dictionary.TryGetKey("A", out actualKey));
Assert.Equal("a", actualKey);
Assert.False(dictionary.TryGetKey("b", out actualKey));
Assert.Equal("b", actualKey);
}
protected void EmptyTestHelper<K, V>(IImmutableDictionary<K, V> empty, K someKey)
{
Assert.Same(empty, empty.Clear());
Assert.Equal(0, empty.Count);
Assert.Equal(0, empty.Count());
Assert.Equal(0, empty.Keys.Count());
Assert.Equal(0, empty.Values.Count());
Assert.Same(EqualityComparer<V>.Default, GetValueComparer(empty));
Assert.False(empty.ContainsKey(someKey));
Assert.False(empty.Contains(new KeyValuePair<K, V>(someKey, default(V))));
Assert.Equal(default(V), empty.GetValueOrDefault(someKey));
V value;
Assert.False(empty.TryGetValue(someKey, out value));
Assert.Equal(default(V), value);
}
protected void AddExistingKeySameValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2)
{
Assert.NotNull(map);
Assert.NotNull(key);
Assert.True(GetValueComparer(map).Equals(value1, value2));
map = map.Add(key, value1);
Assert.Same(map, map.Add(key, value2));
Assert.Same(map, map.AddRange(new[] { new KeyValuePair<TKey, TValue>(key, value2) }));
}
/// <summary>
/// Verifies that adding a key-value pair where the key already is in the map but with a different value throws.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="map">The map to manipulate.</param>
/// <param name="key">The key to add.</param>
/// <param name="value1">The first value to add.</param>
/// <param name="value2">The second value to add.</param>
/// <remarks>
/// Adding a key-value pair to a map where that key already exists, but with a different value, cannot fit the
/// semantic of "adding", either by just returning or mutating the value on the existing key. Throwing is the only reasonable response.
/// </remarks>
protected void AddExistingKeyDifferentValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2)
{
Assert.NotNull(map);
Assert.NotNull(key);
Assert.False(GetValueComparer(map).Equals(value1, value2));
var map1 = map.Add(key, value1);
var map2 = map.Add(key, value2);
AssertExtensions.Throws<ArgumentException>(null, () => map1.Add(key, value2));
AssertExtensions.Throws<ArgumentException>(null, () => map2.Add(key, value1));
}
protected void ContainsKeyTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.ContainsKey(key));
Assert.True(map.Add(key, value).ContainsKey(key));
}
protected void ContainsTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.Contains(new KeyValuePair<TKey, TValue>(key, value)));
Assert.False(map.Contains(key, value));
Assert.True(map.Add(key, value).Contains(new KeyValuePair<TKey, TValue>(key, value)));
Assert.True(map.Add(key, value).Contains(key, value));
}
protected void RemoveTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key)
{
// no-op remove
Assert.Same(map, map.Remove(key));
Assert.Same(map, map.RemoveRange(Enumerable.Empty<TKey>()));
// substantial remove
var addedMap = map.Add(key, default(TValue));
var removedMap = addedMap.Remove(key);
Assert.NotSame(addedMap, removedMap);
Assert.False(removedMap.ContainsKey(key));
}
protected abstract IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>();
protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer);
protected abstract IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary);
}
}
| |
// 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.
extern alias System_Runtime_Extensions;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage.Streams;
using BufferedStream = System_Runtime_Extensions::System.IO.BufferedStream;
namespace System.IO
{
/// <summary>
/// Contains extension methods for conversion between WinRT streams and managed streams.
/// This class is the public facade for the stream adapters library.
/// </summary>
public static class WindowsRuntimeStreamExtensions
{
#region Constants and static Fields
private const int DefaultBufferSize = 16384; // = 0x4000 = 16 KBytes.
private static readonly ConditionalWeakTable<object, Stream> s_winRtToNetFxAdapterMap
= new ConditionalWeakTable<object, Stream>();
private static readonly ConditionalWeakTable<Stream, NetFxToWinRtStreamAdapter> s_netFxToWinRtAdapterMap
= new ConditionalWeakTable<Stream, NetFxToWinRtStreamAdapter>();
#endregion Constants and static Fields
#region Helpers
#if DEBUG
private static void AssertMapContains<TKey, TValue>(ConditionalWeakTable<TKey, TValue> map, TKey key, TValue value,
bool valueMayBeWrappedInBufferedStream)
where TKey : class
where TValue : class
{
TValue valueInMap;
Debug.Assert(key != null);
bool hasValueForKey = map.TryGetValue(key, out valueInMap);
Debug.Assert(hasValueForKey);
if (valueMayBeWrappedInBufferedStream)
{
BufferedStream bufferedValueInMap = valueInMap as BufferedStream;
Debug.Assert(object.ReferenceEquals(value, valueInMap)
|| (bufferedValueInMap != null && object.ReferenceEquals(value, bufferedValueInMap.UnderlyingStream)));
}
else
{
Debug.Assert(object.ReferenceEquals(value, valueInMap));
}
}
#endif // DEBUG
private static void EnsureAdapterBufferSize(Stream adapter, int requiredBufferSize, string methodName)
{
Debug.Assert(adapter != null);
Debug.Assert(!string.IsNullOrWhiteSpace(methodName));
int currentBufferSize = 0;
BufferedStream bufferedAdapter = adapter as BufferedStream;
if (bufferedAdapter != null)
currentBufferSize = bufferedAdapter.BufferSize;
if (requiredBufferSize != currentBufferSize)
{
if (requiredBufferSize == 0)
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_CannotChangeBufferSizeOfWinRtStreamAdapterToZero, methodName));
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_CannotChangeBufferSizeOfWinRtStreamAdapter, methodName));
}
}
#endregion Helpers
#region WinRt-to-NetFx conversion
[CLSCompliant(false)]
public static Stream AsStreamForRead(this IInputStream windowsRuntimeStream)
{
return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStreamForRead", forceBufferSize: false);
}
[CLSCompliant(false)]
public static Stream AsStreamForRead(this IInputStream windowsRuntimeStream, int bufferSize)
{
return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStreamForRead", forceBufferSize: true);
}
[CLSCompliant(false)]
public static Stream AsStreamForWrite(this IOutputStream windowsRuntimeStream)
{
return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStreamForWrite", forceBufferSize: false);
}
[CLSCompliant(false)]
public static Stream AsStreamForWrite(this IOutputStream windowsRuntimeStream, int bufferSize)
{
return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStreamForWrite", forceBufferSize: true);
}
[CLSCompliant(false)]
public static Stream AsStream(this IRandomAccessStream windowsRuntimeStream)
{
return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStream", forceBufferSize: false);
}
[CLSCompliant(false)]
public static Stream AsStream(this IRandomAccessStream windowsRuntimeStream, int bufferSize)
{
return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStream", forceBufferSize: true);
}
private static Stream AsStreamInternal(object windowsRuntimeStream, int bufferSize, string invokedMethodName, bool forceBufferSize)
{
if (windowsRuntimeStream == null)
throw new ArgumentNullException(nameof(windowsRuntimeStream));
if (bufferSize < 0)
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_WinRtAdapterBufferSizeMayNotBeNegative);
Debug.Assert(!string.IsNullOrWhiteSpace(invokedMethodName));
// If the WinRT stream is actually a wrapped managed stream, we will unwrap it and return the original.
// In that case we do not need to put the wrapper into the map.
// We currently do capability-based adapter selection for WinRt->NetFx, but not vice versa (time constraints).
// Once we added the reverse direction, we will be able replce this entire section with just a few lines.
NetFxToWinRtStreamAdapter sAdptr = windowsRuntimeStream as NetFxToWinRtStreamAdapter;
if (sAdptr != null)
{
Stream wrappedNetFxStream = sAdptr.GetManagedStream();
if (wrappedNetFxStream == null)
throw new ObjectDisposedException(nameof(windowsRuntimeStream), SR.ObjectDisposed_CannotPerformOperation);
#if DEBUG // In Chk builds, verify that the original managed stream is correctly entered into the NetFx->WinRT map:
AssertMapContains(s_netFxToWinRtAdapterMap, wrappedNetFxStream, sAdptr,
valueMayBeWrappedInBufferedStream: false);
#endif // DEBUG
return wrappedNetFxStream;
}
// We have a real WinRT stream.
Stream adapter;
bool adapterExists = s_winRtToNetFxAdapterMap.TryGetValue(windowsRuntimeStream, out adapter);
// There is already an adapter:
if (adapterExists)
{
Debug.Assert((adapter is BufferedStream && ((BufferedStream)adapter).UnderlyingStream is WinRtToNetFxStreamAdapter)
|| (adapter is WinRtToNetFxStreamAdapter));
if (forceBufferSize)
EnsureAdapterBufferSize(adapter, bufferSize, invokedMethodName);
return adapter;
}
// We do not have an adapter for this WinRT stream yet and we need to create one.
// Do that in a thread-safe manner in a separate method such that we only have to pay for the compiler allocating
// the required closure if this code path is hit:
return AsStreamInternalFactoryHelper(windowsRuntimeStream, bufferSize, invokedMethodName, forceBufferSize);
}
// Separate method so we only pay for closure allocation if this code is executed:
private static Stream WinRtToNetFxAdapterMap_GetValue(object winRtStream)
{
return s_winRtToNetFxAdapterMap.GetValue(winRtStream, (wrtStr) => WinRtToNetFxStreamAdapter.Create(wrtStr));
}
// Separate method so we only pay for closure allocation if this code is executed:
private static Stream WinRtToNetFxAdapterMap_GetValue(object winRtStream, int bufferSize)
{
return s_winRtToNetFxAdapterMap.GetValue(winRtStream, (wrtStr) => new BufferedStream(WinRtToNetFxStreamAdapter.Create(wrtStr), bufferSize));
}
private static Stream AsStreamInternalFactoryHelper(object windowsRuntimeStream, int bufferSize, string invokedMethodName, bool forceBufferSize)
{
Debug.Assert(windowsRuntimeStream != null);
Debug.Assert(bufferSize >= 0);
Debug.Assert(!string.IsNullOrWhiteSpace(invokedMethodName));
// Get the adapter for this windowsRuntimeStream again (it may have been created concurrently).
// If none exists yet, create a new one:
Stream adapter = (bufferSize == 0)
? WinRtToNetFxAdapterMap_GetValue(windowsRuntimeStream)
: WinRtToNetFxAdapterMap_GetValue(windowsRuntimeStream, bufferSize);
Debug.Assert(adapter != null);
Debug.Assert((adapter is BufferedStream && ((BufferedStream)adapter).UnderlyingStream is WinRtToNetFxStreamAdapter)
|| (adapter is WinRtToNetFxStreamAdapter));
if (forceBufferSize)
EnsureAdapterBufferSize(adapter, bufferSize, invokedMethodName);
WinRtToNetFxStreamAdapter actualAdapter = adapter as WinRtToNetFxStreamAdapter;
if (actualAdapter == null)
actualAdapter = ((BufferedStream)adapter).UnderlyingStream as WinRtToNetFxStreamAdapter;
actualAdapter.SetWonInitializationRace();
return adapter;
}
#endregion WinRt-to-NetFx conversion
#region NetFx-to-WinRt conversion
[CLSCompliant(false)]
public static IInputStream AsInputStream(this Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotReadableToInputStream);
object adapter = AsWindowsRuntimeStreamInternal(stream);
IInputStream winRtStream = adapter as IInputStream;
Debug.Assert(winRtStream != null);
return winRtStream;
}
[CLSCompliant(false)]
public static IOutputStream AsOutputStream(this Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanWrite)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotWritableToOutputStream);
object adapter = AsWindowsRuntimeStreamInternal(stream);
IOutputStream winRtStream = adapter as IOutputStream;
Debug.Assert(winRtStream != null);
return winRtStream;
}
[CLSCompliant(false)]
public static IRandomAccessStream AsRandomAccessStream(this Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanSeek)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotSeekableToRandomAccessStream);
object adapter = AsWindowsRuntimeStreamInternal(stream);
IRandomAccessStream winRtStream = adapter as IRandomAccessStream;
Debug.Assert(winRtStream != null);
return winRtStream;
}
private static object AsWindowsRuntimeStreamInternal(Stream stream)
{
// Check to see if the managed stream is actually a wrapper of a WinRT stream:
// (This can be either an adapter directly, or an adapter wrapped in a BufferedStream.)
WinRtToNetFxStreamAdapter sAdptr = stream as WinRtToNetFxStreamAdapter;
if (sAdptr == null)
{
BufferedStream buffAdptr = stream as BufferedStream;
if (buffAdptr != null)
sAdptr = buffAdptr.UnderlyingStream as WinRtToNetFxStreamAdapter;
}
// If the managed stream us actually a WinRT stream, we will unwrap it and return the original.
// In that case we do not need to put the wrapper into the map.
if (sAdptr != null)
{
object wrappedWinRtStream = sAdptr.GetWindowsRuntimeStream<object>();
if (wrappedWinRtStream == null)
throw new ObjectDisposedException(nameof(stream), SR.ObjectDisposed_CannotPerformOperation);
#if DEBUG // In Chk builds, verify that the original WinRT stream is correctly entered into the WinRT->NetFx map:
AssertMapContains(s_winRtToNetFxAdapterMap, wrappedWinRtStream, sAdptr, valueMayBeWrappedInBufferedStream: true);
#endif // DEBUG
return wrappedWinRtStream;
}
// We have a real managed Stream.
// See if the managed stream already has an adapter:
NetFxToWinRtStreamAdapter adapter;
bool adapterExists = s_netFxToWinRtAdapterMap.TryGetValue(stream, out adapter);
// There is already an adapter:
if (adapterExists)
return adapter;
// We do not have an adapter for this managed stream yet and we need to create one.
// Do that in a thread-safe manner in a separate method such that we only have to pay for the compiler allocating
// the required closure if this code path is hit:
return AsWindowsRuntimeStreamInternalFactoryHelper(stream);
}
private static NetFxToWinRtStreamAdapter AsWindowsRuntimeStreamInternalFactoryHelper(Stream stream)
{
Debug.Assert(stream != null);
// Get the adapter for managed stream again (it may have been created concurrently).
// If none exists yet, create a new one:
NetFxToWinRtStreamAdapter adapter = s_netFxToWinRtAdapterMap.GetValue(stream, (str) => NetFxToWinRtStreamAdapter.Create(str));
Debug.Assert(adapter != null);
adapter.SetWonInitializationRace();
return adapter;
}
#endregion NetFx-to-WinRt conversion
} // class WindowsRuntimeStreamExtensions
} // namespace
// WindowsRuntimeStreamExtensions.cs
| |
#region License
// Copyright 2013-2014 Matthew Ducker
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using Obscur.Core.Cryptography.Authentication;
using Obscur.Core.Cryptography.KeyAgreement.Primitives;
using Obscur.Core.Cryptography.Support.Math.EllipticCurve.Custom.Ed25519;
namespace Obscur.Core.Cryptography.Signing.Primitives
{
public static class Ed25519
{
public static readonly int PublicKeySizeInBytes = 32;
public static readonly int SignatureSizeInBytes = 64;
public static readonly int ExpandedPrivateKeySizeInBytes = 32 * 2;
public static readonly int PrivateKeySeedSizeInBytes = 32;
public static readonly int SharedKeySizeInBytes = 32;
public static bool Verify(ArraySegment<byte> signature, ArraySegment<byte> message, ArraySegment<byte> publicKey)
{
if (signature.Count != SignatureSizeInBytes) {
throw new ArgumentException(string.Format("Signature size must be {0}", SignatureSizeInBytes), "signature.Count");
}
if (publicKey.Count != PublicKeySizeInBytes) {
throw new ArgumentException(string.Format("Public key size must be {0}", PublicKeySizeInBytes), "publicKey.Count");
}
return Ed25519Operations.crypto_sign_verify(signature.Array, signature.Offset, message.Array, message.Offset, message.Count,
publicKey.Array, publicKey.Offset);
}
public static bool Verify(byte[] signature, byte[] message, byte[] publicKey)
{
if (signature == null) {
throw new ArgumentNullException("signature");
}
if (message == null) {
throw new ArgumentNullException("message");
}
if (publicKey == null) {
throw new ArgumentNullException("publicKey");
}
if (signature.Length != SignatureSizeInBytes) {
throw new ArgumentException(string.Format("Signature size must be {0}", SignatureSizeInBytes), "signature.Length");
}
if (publicKey.Length != PublicKeySizeInBytes) {
throw new ArgumentException(string.Format("Public key size must be {0}", PublicKeySizeInBytes), "publicKey.Length");
}
return Ed25519Operations.crypto_sign_verify(signature, 0, message, 0, message.Length, publicKey, 0);
}
public static void Sign(ArraySegment<byte> signature, ArraySegment<byte> message, ArraySegment<byte> expandedPrivateKey)
{
if (signature.Array == null) {
throw new ArgumentNullException("signature.Array");
}
if (signature.Count != SignatureSizeInBytes) {
throw new ArgumentException("signature.Count");
}
if (expandedPrivateKey.Array == null) {
throw new ArgumentNullException("expandedPrivateKey.Array");
}
if (expandedPrivateKey.Count != ExpandedPrivateKeySizeInBytes) {
throw new ArgumentException("expandedPrivateKey.Count");
}
if (message.Array == null) {
throw new ArgumentNullException("message.Array");
}
Ed25519Operations.crypto_sign2(signature.Array, signature.Offset, message.Array, message.Offset, message.Count,
expandedPrivateKey.Array, expandedPrivateKey.Offset);
}
public static byte[] Sign(byte[] message, byte[] expandedPrivateKey)
{
var signature = new byte[SignatureSizeInBytes];
Sign(new ArraySegment<byte>(signature), new ArraySegment<byte>(message), new ArraySegment<byte>(expandedPrivateKey));
return signature;
}
public static byte[] PublicKeyFromSeed(byte[] privateKeySeed)
{
byte[] privateKey;
byte[] publicKey;
KeyPairFromSeed(out publicKey, out privateKey, privateKeySeed);
privateKey.SecureWipe();
return publicKey;
}
public static byte[] ExpandedPrivateKeyFromSeed(byte[] privateKeySeed)
{
byte[] privateKey;
byte[] publicKey;
KeyPairFromSeed(out publicKey, out privateKey, privateKeySeed);
publicKey.SecureWipe();
return privateKey;
}
public static void KeyPairFromSeed(out byte[] publicKey, out byte[] expandedPrivateKey, byte[] privateKeySeed)
{
if (privateKeySeed == null) {
throw new ArgumentNullException("privateKeySeed");
}
if (privateKeySeed.Length != PrivateKeySeedSizeInBytes) {
throw new ArgumentException("privateKeySeed");
}
var pk = new byte[PublicKeySizeInBytes];
var sk = new byte[ExpandedPrivateKeySizeInBytes];
Ed25519Operations.crypto_sign_keypair(pk, 0, sk, 0, privateKeySeed, 0);
publicKey = pk;
expandedPrivateKey = sk;
}
[Obsolete("Needs more testing")]
public static void KeyPairFromSeed(ArraySegment<byte> publicKey, ArraySegment<byte> expandedPrivateKey,
ArraySegment<byte> privateKeySeed)
{
if (publicKey.Array == null) {
throw new ArgumentNullException("publicKey.Array");
}
if (expandedPrivateKey.Array == null) {
throw new ArgumentNullException("expandedPrivateKey.Array");
}
if (privateKeySeed.Array == null) {
throw new ArgumentNullException("privateKeySeed.Array");
}
if (publicKey.Count != PublicKeySizeInBytes) {
throw new ArgumentException("publicKey.Count");
}
if (expandedPrivateKey.Count != ExpandedPrivateKeySizeInBytes) {
throw new ArgumentException("expandedPrivateKey.Count");
}
if (privateKeySeed.Count != PrivateKeySeedSizeInBytes) {
throw new ArgumentException("privateKeySeed.Count");
}
Ed25519Operations.crypto_sign_keypair(
publicKey.Array, publicKey.Offset,
expandedPrivateKey.Array, expandedPrivateKey.Offset,
privateKeySeed.Array, privateKeySeed.Offset);
}
public static byte[] KeyExchange(byte[] publicKey, byte[] privateKey)
{
var sharedKey = new byte[SharedKeySizeInBytes];
KeyExchange(new ArraySegment<byte>(sharedKey), new ArraySegment<byte>(publicKey), new ArraySegment<byte>(privateKey));
return sharedKey;
}
public static void KeyExchange(ArraySegment<byte> sharedKey, ArraySegment<byte> publicKey, ArraySegment<byte> privateKey, bool naclCompat = false)
{
if (sharedKey.Array == null) {
throw new ArgumentNullException("sharedKey.Array");
}
if (publicKey.Array == null) {
throw new ArgumentNullException("publicKey.Array");
}
if (privateKey.Array == null) {
throw new ArgumentNullException("privateKey");
}
if (sharedKey.Count != SharedKeySizeInBytes) {
throw new ArgumentException("sharedKey.Count != 32");
}
if (publicKey.Count != PublicKeySizeInBytes) {
throw new ArgumentException("publicKey.Count != 32");
}
if (privateKey.Count != ExpandedPrivateKeySizeInBytes) {
throw new ArgumentException("privateKey.Count != 64");
}
FieldElement montgomeryX, edwardsY, edwardsZ, sharedMontgomeryX;
FieldOperations.fe_frombytes(out edwardsY, publicKey.Array, publicKey.Offset);
FieldOperations.fe_1(out edwardsZ);
Curve25519.EdwardsToMontgomeryX(out montgomeryX, ref edwardsY, ref edwardsZ);
IHash hasher = AuthenticatorFactory.CreateHashPrimitive(HashFunction.Sha512);
hasher.BlockUpdate(privateKey.Array, privateKey.Offset, 32);
byte[] h = new byte[64];
hasher.DoFinal(h, 0);
ScalarOperations.sc_clamp(h, 0);
MontgomeryOperations.scalarmult(out sharedMontgomeryX, h, 0, ref montgomeryX);
h.SecureWipe();
FieldOperations.fe_tobytes(sharedKey.Array, sharedKey.Offset, ref sharedMontgomeryX);
if (naclCompat)
Curve25519.KeyExchangeOutputHashNaCl(sharedKey.Array, sharedKey.Offset);
}
}
}
| |
/*
* MIT License
*
* Copyright (c) 2017 Brian Groenke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace SmartPropertiesTest
{
using NUnit.Framework;
using System;
using SmartProperties;
using System.Runtime.CompilerServices;
[TestFixture]
public class PropertyModelTest
{
[Test]
public void TestPropertyChangedPropagatesToDependents()
{
var obj = new TestType();
obj.A = "test";
Assert.AreEqual(1, obj.CountA);
Assert.AreEqual(1, obj.CountB);
Assert.AreEqual(1, obj.CountC);
Assert.AreEqual(1, obj.CountD);
Assert.AreEqual(1, obj.CountE);
}
[Test]
public void TestPropertyChangedDoesNotPropagateToParents()
{
var obj = new TestType();
obj.C = "test";
Assert.AreEqual(0, obj.CountA);
Assert.AreEqual(0, obj.CountB);
Assert.AreEqual(1, obj.CountC);
Assert.AreEqual(1, obj.CountD);
Assert.AreEqual(1, obj.CountE);
}
[Test]
public void TestDependencyCycleCallsOnlyOnce_1()
{
var obj = new TestType();
obj.D = "test";
Assert.AreEqual(0, obj.CountA);
Assert.AreEqual(0, obj.CountB);
Assert.AreEqual(0, obj.CountC);
Assert.AreEqual(1, obj.CountD);
Assert.AreEqual(1, obj.CountE);
}
[Test]
public void TestDependencyCycleCallsOnlyOnce_2()
{
var obj = new TestType();
obj.E = "test";
Assert.AreEqual(0, obj.CountA);
Assert.AreEqual(0, obj.CountB);
Assert.AreEqual(0, obj.CountC);
Assert.AreEqual(1, obj.CountD);
Assert.AreEqual(1, obj.CountE);
}
[Test]
public void TestPropertyModelInitFailsForSelfDependency()
{
Assert.Throws<ArgumentException>(() => new IllegalType(), "expected exception for illegal self reference");
}
private class TestType : NotifyPropertyChangedBase
{
private string a, b, c, d, e;
internal string A
{
get
{
return this.a;
}
set
{
this.a = value;
this.OnPropertyChanged();
}
}
[DependsOn(nameof(A))]
internal string B
{
get
{
return this.b;
}
set
{
this.b = value;
this.OnPropertyChanged();
}
}
[DependsOn(nameof(B))]
internal string C
{
get
{
return this.c;
}
set
{
this.c = value;
this.OnPropertyChanged();
}
}
// The inclusion of both B and C is redundant here, since any dependent
// of C will be called as a result of a change to B. We include it here,
// however, for testing purposes, to ensure that PropertyModel doesn't
// dispatch the property change event multiple times to D.
[DependsOn(nameof(E), nameof(B), nameof(C))]
internal string D
{
get
{
return this.d;
}
set
{
this.d = value;
this.OnPropertyChanged();
}
}
[DependsOn(nameof(D))]
internal string E
{
get
{
return this.e;
}
set
{
this.e = value;
this.OnPropertyChanged();
}
}
internal int CountA { get; private set; }
internal int CountB { get; private set; }
internal int CountC { get; private set; }
internal int CountD { get; private set; }
internal int CountE { get; private set; }
protected override void OnPropertyChanged([CallerMemberName]string property = null)
{
base.OnPropertyChanged(property);
switch (property)
{
case nameof(A):
this.CountA++;
break;
case nameof(B):
this.CountB++;
break;
case nameof(C):
this.CountC++;
break;
case nameof(D):
this.CountD++;
break;
case nameof(E):
this.CountE++;
break;
}
}
}
private class IllegalType : NotifyPropertyChangedBase
{
[DependsOn(nameof(A))]
public string A { get; }
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Runtime.Serialization;
using System.Diagnostics.CodeAnalysis;
#if CORECLR
// Use stub for SystemException, SerializationInfo, SerializableAttribute and Serializable
// It is needed for WriteErrorException which ONLY used in Write-Error cmdlet.
using Microsoft.PowerShell.CoreClr.Stubs;
#endif
namespace Microsoft.PowerShell.Commands
{
#region WriteDebugCommand
/// <summary>
/// This class implements Write-Debug command
///
/// </summary>
[Cmdlet("Write", "Debug", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113424", RemotingCapability = RemotingCapability.None)]
public sealed class WriteDebugCommand : PSCmdlet
{
/// <summary>
/// Message to be sent and processed if debug mode is on.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)]
[AllowEmptyString]
[Alias("Msg")]
public string Message { get; set; } = null;
/// <summary>
/// This method implements the ProcessRecord method for Write-Debug command
/// </summary>
protected override void ProcessRecord()
{
//
// The write-debug command must use the script's InvocationInfo rather than its own,
// so we create the DebugRecord here and fill it up with the appropriate InvocationInfo;
// then, we call the command runtime directly and pass this record to WriteDebug().
//
MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
if (mshCommandRuntime != null)
{
DebugRecord record = new DebugRecord(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (invocationInfo != null)
{
record.SetInvocationInfo(invocationInfo);
}
mshCommandRuntime.WriteDebug(record);
}
else
{
WriteDebug(Message);
}
}//processrecord
}//WriteDebugCommand
#endregion WriteDebugCommand
#region WriteVerboseCommand
/// <summary>
/// This class implements Write-Verbose command
///
/// </summary>
[Cmdlet("Write", "Verbose", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113429", RemotingCapability = RemotingCapability.None)]
public sealed class WriteVerboseCommand : PSCmdlet
{
/// <summary>
/// Message to be sent if verbose messages are being shown.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)]
[AllowEmptyString]
[Alias("Msg")]
public string Message { get; set; } = null;
/// <summary>
/// This method implements the ProcessRecord method for Write-verbose command
/// </summary>
protected override void ProcessRecord()
{
//
// The write-verbose command must use the script's InvocationInfo rather than its own,
// so we create the VerboseRecord here and fill it up with the appropriate InvocationInfo;
// then, we call the command runtime directly and pass this record to WriteVerbose().
//
MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
if (mshCommandRuntime != null)
{
VerboseRecord record = new VerboseRecord(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (invocationInfo != null)
{
record.SetInvocationInfo(invocationInfo);
}
mshCommandRuntime.WriteVerbose(record);
}
else
{
WriteVerbose(Message);
}
}//processrecord
}//WriteVerboseCommand
#endregion WriteVerboseCommand
#region WriteWarningCommand
/// <summary>
/// This class implements Write-Warning command
///
/// </summary>
[Cmdlet("Write", "Warning", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113430", RemotingCapability = RemotingCapability.None)]
public sealed class WriteWarningCommand : PSCmdlet
{
/// <summary>
/// Message to be sent if warning messages are being shown.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)]
[AllowEmptyString]
[Alias("Msg")]
public string Message { get; set; } = null;
/// <summary>
/// This method implements the ProcessRecord method for Write-Warning command
/// </summary>
protected override void ProcessRecord()
{
//
// The write-warning command must use the script's InvocationInfo rather than its own,
// so we create the WarningRecord here and fill it up with the appropriate InvocationInfo;
// then, we call the command runtime directly and pass this record to WriteWarning().
//
MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
if (mshCommandRuntime != null)
{
WarningRecord record = new WarningRecord(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (invocationInfo != null)
{
record.SetInvocationInfo(invocationInfo);
}
mshCommandRuntime.WriteWarning(record);
}
else
{
WriteWarning(Message);
}
}//processrecord
}//WriteWarningCommand
#endregion WriteWarningCommand
#region WriteInformationCommand
/// <summary>
/// This class implements Write-Information command
///
/// </summary>
[Cmdlet("Write", "Information", HelpUri = "http://go.microsoft.com/fwlink/?LinkId=525909", RemotingCapability = RemotingCapability.None)]
public sealed class WriteInformationCommand : PSCmdlet
{
/// <summary>
/// Object to be sent to the Information stream.
/// </summary>
[Parameter(Position = 0, Mandatory = true)]
[Alias("Msg")]
public Object MessageData { get; set; }
/// <summary>
/// Any tags to be associated with this information
/// </summary>
[Parameter(Position = 1)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Tags { get; set; }
/// <summary>
/// This method implements the processing of the Write-Information command
/// </summary>
protected override void BeginProcessing()
{
if (Tags != null)
{
foreach (string tag in Tags)
{
if (tag.StartsWith("PS", StringComparison.OrdinalIgnoreCase))
{
ErrorRecord er = new ErrorRecord(
new InvalidOperationException(StringUtil.Format(UtilityCommonStrings.PSPrefixReservedInInformationTag, tag)),
"PSPrefixReservedInInformationTag", ErrorCategory.InvalidArgument, tag);
ThrowTerminatingError(er);
}
}
}
WriteInformation(MessageData, Tags);
}
}//WriteInformationCommand
#endregion WriteInformationCommand
#region WriteOrThrowErrorCommand
/// <summary>
/// This class implements the Write-Error command
/// </summary>
public class WriteOrThrowErrorCommand : PSCmdlet
{
/// <summary>
/// ErrorRecord.Exception -- if not specified, ErrorRecord.Exception is
/// System.Exception.
/// </summary>
[Parameter(ParameterSetName = "WithException", Mandatory = true)]
public Exception Exception { get; set; } = null;
/// <summary>
/// If Exception is specified, this is ErrorRecord.ErrorDetails.Message.
/// Otherwise, the Exception is System.Exception, and this is
/// Exception.Message.
/// </summary>
[Parameter(Position = 0, ParameterSetName = "NoException", Mandatory = true, ValueFromPipeline = true)]
[Parameter(ParameterSetName = "WithException")]
[AllowNull]
[AllowEmptyString]
[Alias("Msg")]
public string Message { get; set; } = null;
/// <summary>
/// If Exception is specified, this is ErrorRecord.ErrorDetails.Message.
/// Otherwise, the Exception is System.Exception, and this is
/// Exception.Message.
/// </summary>
[Parameter(ParameterSetName = "ErrorRecord", Mandatory = true)]
public ErrorRecord ErrorRecord { get; set; } = null;
/// <summary>
/// ErrorRecord.CategoryInfo.Category
/// </summary>
[Parameter(ParameterSetName = "NoException")]
[Parameter(ParameterSetName = "WithException")]
public ErrorCategory Category { get; set; } = ErrorCategory.NotSpecified;
/// <summary>
/// ErrorRecord.ErrorId
/// </summary>
[Parameter(ParameterSetName = "NoException")]
[Parameter(ParameterSetName = "WithException")]
public string ErrorId { get; set; } = "";
/// <summary>
/// ErrorRecord.TargetObject
/// </summary>
[Parameter(ParameterSetName = "NoException")]
[Parameter(ParameterSetName = "WithException")]
public object TargetObject { get; set; } = null;
/// <summary>
/// ErrorRecord.ErrorDetails.RecommendedAction
/// </summary>
[Parameter]
public string RecommendedAction { get; set; } = "";
/* 2005/01/25 removing throw-error
/// <summary>
/// If true, this is throw-error. Otherwise, this is write-error.
/// </summary>
internal bool _terminating = false;
*/
/// <summary>
/// ErrorRecord.CategoryInfo.Activity
/// </summary>
[Parameter]
[Alias("Activity")]
public string CategoryActivity { get; set; } = "";
/// <summary>
/// ErrorRecord.CategoryInfo.Reason
/// </summary>
[Parameter]
[Alias("Reason")]
public string CategoryReason { get; set; } = "";
/// <summary>
/// ErrorRecord.CategoryInfo.TargetName
/// </summary>
[Parameter]
[Alias("TargetName")]
public string CategoryTargetName { get; set; } = "";
/// <summary>
/// ErrorRecord.CategoryInfo.TargetType
/// </summary>
[Parameter]
[Alias("TargetType")]
public string CategoryTargetType { get; set; } = "";
/// <summary>
/// Write an error to the output pipe, or throw a terminating error.
/// </summary>
protected override void ProcessRecord()
{
ErrorRecord errorRecord = this.ErrorRecord;
if (null != errorRecord)
{
// copy constructor
errorRecord = new ErrorRecord(errorRecord, null);
}
else
{
Exception e = this.Exception;
string msg = Message;
if (null == e)
{
e = new WriteErrorException(msg);
}
string errid = ErrorId;
if (String.IsNullOrEmpty(errid))
{
errid = e.GetType().FullName;
}
errorRecord = new ErrorRecord(
e,
errid,
Category,
TargetObject
);
if ((null != this.Exception && !String.IsNullOrEmpty(msg)))
{
errorRecord.ErrorDetails = new ErrorDetails(msg);
}
}
string recact = RecommendedAction;
if (!String.IsNullOrEmpty(recact))
{
if (null == errorRecord.ErrorDetails)
{
errorRecord.ErrorDetails = new ErrorDetails(errorRecord.ToString());
}
errorRecord.ErrorDetails.RecommendedAction = recact;
}
if (!String.IsNullOrEmpty(CategoryActivity))
errorRecord.CategoryInfo.Activity = CategoryActivity;
if (!String.IsNullOrEmpty(CategoryReason))
errorRecord.CategoryInfo.Reason = CategoryReason;
if (!String.IsNullOrEmpty(CategoryTargetName))
errorRecord.CategoryInfo.TargetName = CategoryTargetName;
if (!String.IsNullOrEmpty(CategoryTargetType))
errorRecord.CategoryInfo.TargetType = CategoryTargetType;
/* 2005/01/25 removing throw-error
if (_terminating)
{
ThrowTerminatingError(errorRecord);
}
else
{
*/
// 2005/07/14-913791 "write-error output is confusing and misleading"
// set InvocationInfo to the script not the command
InvocationInfo myInvocation = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (null != myInvocation)
{
errorRecord.SetInvocationInfo(myInvocation);
errorRecord.PreserveInvocationInfoOnce = true;
errorRecord.CategoryInfo.Activity = "Write-Error";
}
WriteError(errorRecord);
/*
}
*/
}//processrecord
}//WriteOrThrowErrorCommand
/// <summary>
/// This class implements Write-Error command
/// </summary>
[Cmdlet("Write", "Error", DefaultParameterSetName = "NoException",
HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113425", RemotingCapability = RemotingCapability.None)]
public sealed class WriteErrorCommand : WriteOrThrowErrorCommand
{
/// <summary>
/// constructor
/// </summary>
public WriteErrorCommand()
{
}
}
/* 2005/01/25 removing throw-error
/// <summary>
/// This class implements Write-Error command
/// </summary>
[Cmdlet("Throw", "Error", DefaultParameterSetName = "NoException")]
public sealed class ThrowErrorCommand : WriteOrThrowErrorCommand
{
/// <summary>
/// constructor
/// </summary>
public ThrowErrorCommand()
{
using (tracer.TraceConstructor(this))
{
_terminating = true;
}
}
}
*/
#endregion WriteOrThrowErrorCommand
#region WriteErrorException
/// <summary>
/// The write-error cmdlet uses WriteErrorException
/// when the user only specifies a string and not
/// an Exception or ErrorRecord.
/// </summary>
[Serializable]
public class WriteErrorException : SystemException
{
#region ctor
/// <summary>
/// Constructor for class WriteErrorException
/// </summary>
/// <returns> constructed object </returns>
public WriteErrorException()
: base(StringUtil.Format(WriteErrorStrings.WriteErrorException))
{
}
/// <summary>
/// Constructor for class WriteErrorException
/// </summary>
/// <param name="message"> </param>
/// <returns> constructed object </returns>
public WriteErrorException(string message)
: base(message)
{
}
/// <summary>
/// Constructor for class WriteErrorException
/// </summary>
/// <param name="message"> </param>
/// <param name="innerException"> </param>
/// <returns> constructed object </returns>
public WriteErrorException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Serialization constructor for class WriteErrorException
/// </summary>
/// <param name="info"> serialization information </param>
/// <param name="context"> streaming context </param>
/// <returns> constructed object </returns>
protected WriteErrorException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
} // WriteErrorException
#endregion WriteErrorException
} //namespace
| |
// 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.Storage
{
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>
/// UsageOperations operations.
/// </summary>
internal partial class UsageOperations : IServiceOperations<StorageManagementClient>, IUsageOperations
{
/// <summary>
/// Initializes a new instance of the UsageOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal UsageOperations(StorageManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the StorageManagementClient
/// </summary>
public StorageManagementClient Client { get; private set; }
/// <summary>
/// Gets the current usage count and the limit for the resources under the
/// subscription.
/// </summary>
/// <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<UsageListResult>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
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}/providers/Microsoft.Storage/usages").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
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<UsageListResult>();
_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<UsageListResult>(_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;
}
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEditor;
public class HTGuiTools{
private static Texture2D gradientTexture;
#region Widget
public static bool BeginFoldOut(string text,bool foldOut, bool endSpace=true){
text = "<b><size=11>" + text + "</size></b>";
if (foldOut){
text = "\u25BC " + text;
}
else{
text = "\u25BA " + text;
}
if ( !GUILayout.Toggle(true,text,"dragtab")){
foldOut=!foldOut;
}
if (!foldOut && endSpace)GUILayout.Space(5f);
return foldOut;
}
public static void BeginGroup(int padding=0){
GUILayout.BeginHorizontal();
GUILayout.Space(padding);
EditorGUILayout.BeginHorizontal("As TextArea", GUILayout.MinHeight(10f));
GUILayout.BeginVertical();
GUILayout.Space(2f);
}
public static void EndGroup(bool endSpace = true){
GUILayout.Space(3f);
GUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
GUILayout.Space(3f);
GUILayout.EndHorizontal();
if (endSpace){
GUILayout.Space(10f);
}
}
public static bool Toggle(string text, bool value,bool leftToggle=false){
if (value) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
if (leftToggle){
value = EditorGUILayout.ToggleLeft(text,value);
}
else{
value = EditorGUILayout.Toggle(text,value);
}
GUI.backgroundColor = Color.white;
return value;
}
public static bool Toggle (string text, bool value,int width,bool leftToggle=false){
if (value) GUI.backgroundColor = Color.green; else GUI.backgroundColor = Color.red;
if (leftToggle){
value = EditorGUILayout.ToggleLeft(text,value,GUILayout.Width( width));
}
else{
value = EditorGUILayout.Toggle(text,value,GUILayout.Width( width));
}
GUI.backgroundColor = Color.white;
return value;
}
static public bool Button(string label,Color color,int width, bool leftAligment=false, int height=0){
GUI.backgroundColor = color;
GUIStyle buttonStyle = new GUIStyle("Button");
if (leftAligment)
buttonStyle.alignment = TextAnchor.MiddleLeft;
if (height==0){
if (GUILayout.Button( label,buttonStyle,GUILayout.Width(width))){
GUI.backgroundColor = Color.white;
return true;
}
}
else{
if (GUILayout.Button( label,buttonStyle,GUILayout.Width(width),GUILayout.Height(height))){
GUI.backgroundColor = Color.white;
return true;
}
}
GUI.backgroundColor = Color.white;
return false;
}
#endregion
#region 2d effect
public static void DrawSeparatorLine(int padding=0){
EditorGUILayout.Space();
DrawLine(Color.gray, padding);
EditorGUILayout.Space();
}
private static void DrawLine(Color color,int padding=0){
GUILayout.Space(10);
Rect lastRect = GUILayoutUtility.GetLastRect();
GUI.color = color;
GUI.DrawTexture(new Rect(padding, lastRect.yMax -lastRect.height/2f, Screen.width, 1f), EditorGUIUtility.whiteTexture);
GUI.color = Color.white;
}
#endregion
#region Texture
private static Rect DrawGradient(int padding, int width, int height=35){
GUILayout.Space(height);
Rect lastRect = GUILayoutUtility.GetLastRect();
lastRect.yMin = lastRect.yMin + 7;
lastRect.yMax = lastRect.yMax - 7;
lastRect.width = Screen.width;
GUI.DrawTexture(new Rect(padding,lastRect.yMin+1,width, lastRect.yMax- lastRect.yMin), GetGradientTexture());
return lastRect;
}
private static Texture2D GetGradientTexture(){
if (gradientTexture==null){
gradientTexture = CreateGradientTexture();
}
return gradientTexture;
}
private static Texture2D CreateGradientTexture(){
int height =18;
Texture2D myTexture = new Texture2D(1, height);
myTexture.hideFlags = HideFlags.HideInInspector;
myTexture.hideFlags = HideFlags.DontSave;
myTexture.filterMode = FilterMode.Bilinear;
Color startColor= new Color(0.4f,0.4f,0.4f);
Color endColor= new Color(0.6f,0.6f,0.6f);
float stepR = (endColor.r - startColor.r)/18f;
float stepG = (endColor.g - startColor.g)/18f;
float stepB = (endColor.b - startColor.b)/18f;
Color pixColor = startColor;
for (int i = 1; i < height-1; i++)
{
pixColor = new Color(pixColor.r + stepR,pixColor.g + stepG , pixColor.b + stepB);
myTexture.SetPixel(0, i, pixColor);
}
myTexture.SetPixel(0, 0, new Color(0,0,0));
myTexture.SetPixel(0, 17, new Color(1,1,1));
myTexture.Apply();
return myTexture;
}
#endregion
}
/*
public static Texture2D gradientTextureStyle;
public static Texture2D checkerTexture;
// Title
// FoldOut
public static bool FoldOut( ref bool foldOut,string text, bool addButton=false, string buttonText="+"){
GUIStyle foldOutStyle = new GUIStyle( EditorStyles.foldout);
foldOutStyle.fontStyle = FontStyle.Bold;
foldOutStyle.fontSize = 12;
foldOutStyle.stretchWidth = false;
Color textColor = Color.white;
int offsety=2;
foldOutStyle.onActive.textColor = textColor;
foldOutStyle.onFocused.textColor = textColor;
foldOutStyle.onHover.textColor = textColor;
foldOutStyle.onNormal.textColor = textColor;
foldOutStyle.active.textColor = textColor;
foldOutStyle.focused.textColor = textColor;
foldOutStyle.hover.textColor = textColor;;
foldOutStyle.normal.textColor = textColor;
int width=Screen.width;
if (addButton)
width = Screen.width-37;
Rect lastRect = DrawTitleGradient(0,width);
GUI.backgroundColor = Color.black;
GUIContent foldContent = new GUIContent();
foldContent.text = " " + text;
foldOut = EditorGUI.Foldout(new Rect(lastRect.x + 3, lastRect.y+offsety, width , lastRect.height),foldOut,foldContent,true,foldOutStyle);
GUI.backgroundColor = Color.white;
if (addButton){
GUI.backgroundColor = Color.green;
if (GUI.Button( new Rect(Screen.width-37, lastRect.y, 20 , lastRect.height),buttonText)){
GUI.backgroundColor = Color.white;
return true;
}
GUI.backgroundColor = Color.white;
}
return false;
}
public static Rect DrawTitleChapter(string text,int size, bool bold, int style, int width)
{
Rect lastRect = DrawTitleGradient(0,width);
GUIStyle labelStyle = new GUIStyle( EditorStyles.label);
if (bold){
labelStyle.fontStyle = FontStyle.Bold;
}
labelStyle.fontSize = size;
Color textColor = Color.white;
labelStyle.onActive.textColor = textColor;
labelStyle.onFocused.textColor = textColor;
labelStyle.onHover.textColor = textColor;
labelStyle.onNormal.textColor = textColor;
labelStyle.active.textColor = textColor;
labelStyle.focused.textColor = textColor;
labelStyle.hover.textColor = textColor;;
labelStyle.normal.textColor = textColor;
int offsety = 2;
if (style==2) offsety=0;
//GUI.Label(new Rect(lastRect.x + 3, lastRect.y+offsety, lastRect.width - 5, lastRect.height), text,labelStyle);
GUI.Label(new Rect(lastRect.x + 3, lastRect.y+offsety, width, lastRect.height), text,labelStyle);
return lastRect;
}
public static bool ChildFoldOut(bool foldOut,string text, Color color, int width){
string label="[+] " + text;
if (foldOut) label="[-] " + text;
if (HTGuiTools.Button(label,color,width,true)){
foldOut = !foldOut;
}
return foldOut;
}
// Vector2
public static Vector2 Vector2Field(string label,Vector2 vector){
Rect r = EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(label);
r.y-= 18;
r.x = 50;
vector = EditorGUI.Vector2Field(r,"",vector);
EditorGUILayout.EndHorizontal();
return vector;
}
// Depth control
static public int GuiDepth(int depth){
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Gui depth");
if (GUILayout.Button("Back",GUILayout.Width(50))){
depth--;
}
depth =EditorGUILayout.IntField(depth,GUILayout.Width(32));
if (GUILayout.Button("Front",GUILayout.Width(50))){
depth++;
}
EditorGUILayout.EndHorizontal();
return depth;
}
// Picture
public static void DrawTexturePreview( Rect rect, Texture tex){
DrawTileTexture( rect, HTGuiTools.GetCheckerTexture());
if (tex!=null){
GUI.DrawTexture( rect, tex,ScaleMode.ScaleToFit);
}
}
public static void DrawTextureRectPreview( Rect rect, Rect textureRect, Texture2D tex, Color color){
GUI.color = color;
GUI.DrawTexture( rect, EditorGUIUtility.whiteTexture);
GUI.color = Color.white;
rect = new Rect(rect.x+3,rect.y+3,rect.width-6,rect.height-6);
DrawTileTexture( rect, HTGuiTools.GetCheckerTexture());
if (tex!=null){
GUI.DrawTextureWithTexCoords( rect, tex,textureRect );
}
}
// Draw separator line
public static void DrawSeparatorLine(int padding=0)
{
DrawSeparatorLine(Color.gray, padding);
}
public static void DrawSeparatorLine(Color color,int padding=0)
{
GUILayout.Space(10);
Rect lastRect = GUILayoutUtility.GetLastRect();
GUI.color = color;
GUI.DrawTexture(new Rect(padding, lastRect.yMax -lastRect.height/2f, Screen.width, 1f), EditorGUIUtility.whiteTexture);
GUI.color = Color.white;
}
public static void DrawTileTexture (Rect rect, Texture tex)
{
GUI.BeginGroup(rect);
{
int width = Mathf.RoundToInt(rect.width);
int height = Mathf.RoundToInt(rect.height);
for (int y = 0; y < height; y += tex.height)
{
for (int x = 0; x < width; x += tex.width)
{
GUI.DrawTexture(new Rect(x, y, tex.width, tex.height), tex);
}
}
}
GUI.EndGroup();
}
public static void DrawLine(float x1,float y1,float x2,float y2, Color color){
GUI.color = color;
GUI.DrawTexture( new Rect(x1,y1,x2-x1,y2-y1), EditorGUIUtility.whiteTexture);
GUI.color = Color.white;
}
// Gradient
private static Rect DrawTitleGradient(int padding, int width)
{
int space=35;
GUILayout.Space(space);
Rect lastRect = GUILayoutUtility.GetLastRect();
lastRect.yMin = lastRect.yMin + 7;
lastRect.yMax = lastRect.yMax - 7;
lastRect.width = Screen.width;
if (width==-1)
GUI.DrawTexture(new Rect(padding,lastRect.yMin+1,Screen.width, lastRect.yMax- lastRect.yMin), GetGradientTexture());
else
GUI.DrawTexture(new Rect(padding,lastRect.yMin+1,width, lastRect.yMax- lastRect.yMin), GetGradientTexture());
return lastRect;
}
private static Texture2D GetGradientTexture(){
if (HTGuiTools.gradientTextureStyle==null){
HTGuiTools.gradientTextureStyle = CreateGradientTexture();
}
return gradientTextureStyle;
}
private static Texture2D CreateGradientTexture()
{
// new texture
int height =18;
Texture2D myTexture = new Texture2D(1, height);
myTexture.hideFlags = HideFlags.HideInInspector;
myTexture.hideFlags = HideFlags.DontSave;
myTexture.filterMode = FilterMode.Bilinear;
Color startColor= new Color(0.4f,0.4f,0.4f);
Color endColor= new Color(0.6f,0.6f,0.6f);
float stepR = (endColor.r - startColor.r)/18f;
float stepG = (endColor.g - startColor.g)/18f;
float stepB = (endColor.b - startColor.b)/18f;
Color pixColor = startColor;
for (int i = 1; i < height-1; i++)
{
pixColor = new Color(pixColor.r + stepR,pixColor.g + stepG , pixColor.b + stepB);
myTexture.SetPixel(0, i, pixColor);
}
myTexture.SetPixel(0, 0, new Color(0,0,0));
myTexture.SetPixel(0, 17, new Color(1,1,1));
myTexture.Apply();
return myTexture;
}
// Checker
private static Texture2D GetCheckerTexture(){
if (HTGuiTools.checkerTexture==null){
HTGuiTools.checkerTexture = CreateCheckerTexture();
}
return checkerTexture;
}
private static Texture2D CreateCheckerTexture(){
Texture2D myTexture = new Texture2D(16, 16);
myTexture.hideFlags = HideFlags.DontSave;
Color color1 = new Color(0.5f,0.5f,0.5f);
for( int x=0;x<8;x++){
for( int y=0;y<8;y++){
myTexture.SetPixel(x, y, color1);
myTexture.SetPixel(x+8, y+8, color1);
}
}
color1 = new Color(0.3f,0.3f,0.3f);
for( int x=0;x<8;x++){
for( int y=0;y<8;y++){
myTexture.SetPixel(x+8, y, color1);
myTexture.SetPixel(x, y+8, color1);
}
}
myTexture.Apply();
return myTexture;
}
#region AssetDatabase tool
public static bool CreateAssetDirectory(string rootPath,string name){
string directory = rootPath + "/" + name;
if (!System.IO.Directory.Exists(directory)){
AssetDatabase.CreateFolder(rootPath,name);
AssetDatabase.Refresh();
return true;
}
return false;
}
public static string GetAssetRootPath( string path){
string[] tokens = path.Split('/');
path="";
for (int i=0;i<tokens.Length-1;i++){
path+= tokens[i] +"/";
}
return path;
}
#endregion
*/
| |
//-----------------------------------------------------------------------------
// Filename: SIPResponse.cs
//
// Description: SIP Response.
//
// History:
// 17 Sep 2005 Aaron Clauson Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2006 Aaron Clauson ([email protected]), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com)
// 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 SIP Sorcery PTY LTD.
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using SIPSorcery.Sys;
using log4net;
#if UNITTEST
using NUnit.Framework;
#endif
namespace SIPSorcery.SIP
{
public enum SIPResponseParserError
{
None = 0,
TooLarge = 1,
}
/// <bnf>
/// SIP-Version SP Status-Code SP Reason-Phrase CRLF
/// *message-header
/// CRLF
/// [ message-body ]
/// </bnf>
/// <summary>
/// Status Codes:
/// 1xx: Provisional -- request received, continuing to process the request;
/// 2xx: Success -- the action was successfully received, understood, and accepted;
/// 3xx: Redirection -- further action needs to be taken in order to complete the request;
/// 4xx: Client Error -- the request contains bad syntax or cannot be fulfilled at this server;
/// 5xx: Server Error -- the server failed to fulfill an apparently valid request;
/// 6xx: Global Failure -- the request cannot be fulfilled at any server.
///
/// </summary>
public class SIPResponse
{
private static ILog logger = AssemblyState.logger;
private static string m_CRLF = SIPConstants.CRLF;
private static string m_sipVersion = SIPConstants.SIP_FULLVERSION_STRING;
public string SIPVersion;
public SIPResponseStatusCodesEnum Status;
public int StatusCode;
public string ReasonPhrase;
public string Body;
public SIPHeader Header = new SIPHeader();
public DateTime Created = DateTime.Now;
public SIPEndPoint RemoteSIPEndPoint; // The remote IP socket the response was received from or sent to.
public SIPEndPoint LocalSIPEndPoint; // The local SIP socket the response was received on or sent from.
private SIPResponse()
{}
public SIPResponse(SIPResponseStatusCodesEnum responseType, string reasonPhrase, SIPEndPoint localSIPEndPoint)
{
SIPVersion = m_sipVersion;
StatusCode = (int)responseType;
Status = responseType;
ReasonPhrase = reasonPhrase;
ReasonPhrase = responseType.ToString();
LocalSIPEndPoint = localSIPEndPoint;
}
public static SIPResponse ParseSIPResponse(SIPMessage sipMessage)
{
try
{
SIPResponse sipResponse = new SIPResponse();
sipResponse.LocalSIPEndPoint = sipMessage.LocalSIPEndPoint;
sipResponse.RemoteSIPEndPoint = sipMessage.RemoteSIPEndPoint;
string statusLine = sipMessage.FirstLine;
int firstSpacePosn = statusLine.IndexOf(" ");
sipResponse.SIPVersion = statusLine.Substring(0, firstSpacePosn).Trim();
statusLine = statusLine.Substring(firstSpacePosn).Trim();
sipResponse.StatusCode = Convert.ToInt32(statusLine.Substring(0, 3));
sipResponse.Status = SIPResponseStatusCodes.GetStatusTypeForCode(sipResponse.StatusCode);
sipResponse.ReasonPhrase = statusLine.Substring(3).Trim();
sipResponse.Header = SIPHeader.ParseSIPHeaders(sipMessage.SIPHeaders);
sipResponse.Body = sipMessage.Body;
return sipResponse;
}
catch (SIPValidationException)
{
throw;
}
catch (Exception excp)
{
logger.Error("Exception ParseSIPResponse. " + excp.Message);
logger.Error(sipMessage.RawMessage);
throw new SIPValidationException(SIPValidationFieldsEnum.Response, "Error parsing SIP Response");
}
}
public static SIPResponse ParseSIPResponse(string sipMessageStr)
{
try
{
SIPMessage sipMessage = SIPMessage.ParseSIPMessage(sipMessageStr, null, null);
return SIPResponse.ParseSIPResponse(sipMessage);
}
catch (SIPValidationException)
{
throw;
}
catch (Exception excp)
{
logger.Error("Exception ParseSIPResponse. " + excp.Message);
logger.Error(sipMessageStr);
throw new SIPValidationException(SIPValidationFieldsEnum.Response, "Error parsing SIP Response");
}
}
public new string ToString()
{
string reasonPhrase = (!ReasonPhrase.IsNullOrBlank()) ? " " + ReasonPhrase : null;
string message =
SIPVersion + " " + StatusCode + reasonPhrase + m_CRLF +
this.Header.ToString();
if(Body != null)
{
message += m_CRLF + Body;
}
else
{
message += m_CRLF;
}
return message;
}
/// <summary>
/// Creates an identical copy of the SIP Response for the caller.
/// </summary>
/// <returns>New copy of the SIPResponse.</returns>
public SIPResponse Copy()
{
return ParseSIPResponse(this.ToString());
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class SIPResponseUnitTest
{
[TestFixtureSetUp]
public void Init()
{
}
[TestFixtureTearDown]
public void Dispose()
{
}
[Test]
public void SampleTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
Assert.IsTrue(true, "True was false.");
Console.WriteLine("-----------------------------------------");
}
[Test]
public void ParseAsteriskTRYINGUnitTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string sipMsg =
"SIP/2.0 100 Trying" + m_CRLF +
"Via: SIP/2.0/UDP 213.168.225.135:5060;branch=z9hG4bKD+ta2mJ+C+VV/L50aPO1lFJnrag=" + m_CRLF +
"Via: SIP/2.0/UDP 192.168.1.2:5065;received=220.240.255.198:64193;branch=z9hG4bKB86FC8D2431F49E9862D1EE439C78AD8" + m_CRLF +
"From: bluesipd <sip:bluesipd@bluesipd:5065>;tag=3272744142" + m_CRLF +
"To: <sip:303@bluesipd>" + m_CRLF +
"Call-ID: [email protected]" + m_CRLF +
"CSeq: 45560 INVITE" + m_CRLF +
"User-Agent: asterisk" + m_CRLF +
"Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY" + m_CRLF +
"Contact: <sip:[email protected]>" + m_CRLF +
"Content-Length: 0" + m_CRLF + m_CRLF;
SIPMessage sipMessage = SIPMessage.ParseSIPMessage(Encoding.UTF8.GetBytes(sipMsg), null, null);
SIPResponse tryingResp = SIPResponse.ParseSIPResponse(sipMessage);
Assert.IsTrue(tryingResp.Status == SIPResponseStatusCodesEnum.Trying, "The SIP response status was not parsed correctly.");
Console.WriteLine("-----------------------------------------");
}
[Test]
public void ParseAsteriskOKUnitTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string sipMsg =
"SIP/2.0 200 OK" + m_CRLF +
"Via: SIP/2.0/UDP 213.168.225.135:5060;branch=z9hG4bKT36BdhXPlT5cqPFQQr81yMmZ37U=" + m_CRLF +
"Via: SIP/2.0/UDP 192.168.1.2:5065;received=220.240.255.198:64216;branch=z9hG4bK7D8B6549580844AEA104BD4A837049DD" + m_CRLF +
"From: bluesipd <sip:bluesipd@bluesipd:5065>;tag=630217013" + m_CRLF +
"To: <sip:303@bluesipd>;tag=as46f418e9" + m_CRLF +
"Call-ID: [email protected]" + m_CRLF +
"CSeq: 27481 INVITE" + m_CRLF +
"User-Agent: asterisk" + m_CRLF +
"Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY" + m_CRLF +
"Contact: <sip:[email protected]>" + m_CRLF +
"Content-Type: application/sdp" + m_CRLF +
"Content-Length: 352" + m_CRLF +
m_CRLF +
"v=0" + m_CRLF +
"o=root 24710 24712 IN IP4 213.168.225.133" + m_CRLF +
"s=session" + m_CRLF +
"c=IN IP4 213.168.225.133" + m_CRLF +
"t=0 0" + m_CRLF +
"m=audio 18656 RTP/AVP 0 8 18 3 97 111 101" + m_CRLF +
"a=rtpmap:0 PCMU/8000" + m_CRLF +
"a=rtpmap:8 PCMA/8000" + m_CRLF +
"a=rtpmap:18 G729/8000" + m_CRLF +
"a=rtpmap:3 GSM/8000" + m_CRLF +
"a=rtpmap:97 iLBC/8000" + m_CRLF +
"a=rtpmap:111 G726-32/8000" + m_CRLF +
"a=rtpmap:101 telephone-event/8000" + m_CRLF +
"a=fmtp:101 0-16" + m_CRLF +
"a=silenceSupp:off - - - -" + m_CRLF;
SIPMessage sipMessage = SIPMessage.ParseSIPMessage(Encoding.UTF8.GetBytes(sipMsg), null, null);
SIPResponse okResp = SIPResponse.ParseSIPResponse(sipMessage);
Assert.IsTrue(okResp.Status == SIPResponseStatusCodesEnum.Ok, "The SIP response status was not parsed correctly.");
Assert.IsTrue(okResp.Body.Length == 352, "The SIP response body length was not correct.");
Console.WriteLine("-----------------------------------------");
}
[Test]
public void ParseOptionsBodyResponse()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string sipMsg = "SIP/2.0 200 OK" + m_CRLF +
"Via: SIP/2.0/UDP 213.168.225.133:5060;branch=z9hG4bK10a1fab0" + m_CRLF +
"From: \"Unknown\" <sip:[email protected]>;tag=as18338373" + m_CRLF +
"To: <sip:[email protected]>;tag=OLg-20481" + m_CRLF +
"Call-ID: [email protected]" + m_CRLF +
"CSeq: 102 OPTIONS" + m_CRLF +
"content-type: application/sdp" + m_CRLF +
"Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, INFO, REFER, NOTIFY" + m_CRLF +
"Content-Length: 217" + m_CRLF +
m_CRLF +
"v=0" + m_CRLF +
"o=0 5972727 56415 IN IP4 0.0.0.0" + m_CRLF +
"s=SIP Call" + m_CRLF +
"c=IN IP4 0.0.0.0" + m_CRLF +
"t=0 0" + m_CRLF +
"m=audio 0 RTP/AVP 18 0 8 4 2" + m_CRLF +
"a=rtpmap:18 G729/8000" + m_CRLF +
"a=rtpmap:0 pcmu/8000" + m_CRLF +
"a=rtpmap:8 pcma/8000" + m_CRLF +
"a=rtpmap:4 g723/8000" + m_CRLF +
"a=rtpmap:2 g726/8000" + m_CRLF;
SIPMessage sipMessage = SIPMessage.ParseSIPMessage(Encoding.UTF8.GetBytes(sipMsg), null, null);
SIPResponse okResp = SIPResponse.ParseSIPResponse(sipMessage);
Assert.IsTrue(okResp.Status == SIPResponseStatusCodesEnum.Ok, "The SIP response status was not parsed correctly.");
Assert.IsTrue(okResp.Body.Length == 217, "The SIP response body length was not correct.");
Console.WriteLine("-----------------------------------------");
}
[Test]
public void ParseForbiddenResponse()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string sipMsg = "SIP/2.0 403 Forbidden" + m_CRLF +
"Via: SIP/2.0/UDP 192.168.1.1;branch=z9hG4bKbcb78f72d221beec" + m_CRLF +
"From: <sip:sip.blueface.ie>;tag=9a4c86234adcc297" + m_CRLF +
"To: <sip:sip.blueface.ie>;tag=as6900b876" + m_CRLF +
"Call-ID: [email protected]" + m_CRLF +
"CSeq: 100 REGISTER" + m_CRLF +
"User-Agent: asterisk" + m_CRLF +
"Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY" + m_CRLF +
"Contact: <sip:[email protected]>" + m_CRLF +
"Content-Length: 0" + m_CRLF + m_CRLF;
SIPMessage sipMessage = SIPMessage.ParseSIPMessage(Encoding.UTF8.GetBytes(sipMsg), null, null);
SIPResponse forbiddenResp = SIPResponse.ParseSIPResponse(sipMessage);
Assert.IsTrue(forbiddenResp.Status == SIPResponseStatusCodesEnum.Forbidden, "The SIP response status was not parsed correctly.");
Console.WriteLine("-----------------------------------------");
}
[Test]
public void ParseOptionsResponse()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string sipMsg =
"SIP/2.0 200 OK" + m_CRLF +
"Via: SIP/2.0/UDP 194.213.29.11:5060;branch=z9hG4bK330f55c874" + m_CRLF +
"From: Anonymous <sip:194.213.29.11:5060>;tag=6859154930" + m_CRLF +
"To: <sip:[email protected]:10062>;tag=0013c339acec0fe007b80bbf-30071da3" + m_CRLF +
"Call-ID: [email protected]" + m_CRLF +
"Date: Mon, 01 May 2006 13:47:24 GMT" + m_CRLF +
"CSeq: 915 OPTIONS" + m_CRLF +
"Server: CSCO/7" + m_CRLF +
"Content-Type: application/sdp" + m_CRLF +
"Content-Length: 247" + m_CRLF +
"Allow: OPTIONS,INVITE,BYE,CANCEL,REGISTER,ACK,NOTIFY,REFER" + m_CRLF +
m_CRLF +
"v=0" + m_CRLF +
"o=Cisco-SIPUA (null) (null) IN IP4 192.168.1.100" + m_CRLF +
"s=SIP Call" + m_CRLF +
"c=IN IP4 192.168.1.100" + m_CRLF +
"t=0 0" + m_CRLF +
"m=audio 1 RTP/AVP 0 8 18 101" + m_CRLF +
"a=rtpmap:0 PCMU/8000" + m_CRLF +
"a=rtpmap:8 PCMA/8000" + m_CRLF +
"a=rtpmap:18 G729/8000" + m_CRLF +
"a=rtpmap:101 telephone-event/8000" + m_CRLF +
"a=fmtp:101 0-15" + m_CRLF + m_CRLF;
SIPMessage sipMessage = SIPMessage.ParseSIPMessage(Encoding.UTF8.GetBytes(sipMsg), null, null);
SIPResponse optionsResp = SIPResponse.ParseSIPResponse(sipMessage);
Assert.IsTrue(optionsResp.Status == SIPResponseStatusCodesEnum.Ok, "The SIP response status was not parsed correctly.");
Console.WriteLine("-----------------------------------------");
}
[Test]
public void ParseMissingCSeqOptionsResponse()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string sipMsg =
"SIP/2.0 200 OK" + m_CRLF +
"To: <sip:[email protected]:5060>;tag=eba877fbb8dd284bi0" + m_CRLF +
"From: <sip:213.168.225.133:5060>;tag=5880003940" + m_CRLF +
"Call-ID: [email protected]" + m_CRLF +
"Via: SIP/2.0/UDP 213.168.225.133:5060;branch=z9hG4bK1702000048" + m_CRLF +
"Server: Linksys/RT31P2-2.0.10(LIc)" + m_CRLF +
"Content-Length: 0" + m_CRLF +
"Allow: ACK, BYE, CANCEL, INFO, INVITE, NOTIFY, OPTIONS, REFER" + m_CRLF +
"Supported: x-sipura" + m_CRLF + m_CRLF;
SIPMessage sipMessage = SIPMessage.ParseSIPMessage(Encoding.UTF8.GetBytes(sipMsg), null, null);
SIPResponse optionsResp = SIPResponse.ParseSIPResponse(sipMessage);
Console.WriteLine("CSeq=" + optionsResp.Header.CSeq + ".");
Console.WriteLine("CSeq Method=" + optionsResp.Header.CSeqMethod + ".");
Assert.IsTrue(optionsResp.Header.CSeq == -1, "Response CSeq was incorrect.");
Assert.IsTrue(optionsResp.Header.CSeqMethod == SIPMethodsEnum.NONE, "Response CSeq method was incorrect.");
Console.WriteLine("-----------------------------------------");
}
[Test]
public void ParseMSCOkResponse()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string sipMsg =
"SIP/2.0 200 OK" + m_CRLF +
"From: Blue Face<sip:[email protected]>;tag=as5fd53de7" + m_CRLF +
"To: sip:[email protected];tag=MTHf2-ol1Yn0" + m_CRLF +
"Call-ID: [email protected]:5061" + m_CRLF +
"CSeq: 102 INVITE" + m_CRLF +
"Via: SIP/2.0/UDP 213.168.225.133:5060;branch=z9hG4bKG+WGOVwLyT6vOW9s" + m_CRLF +
"Via: SIP/2.0/UDP 213.168.225.133:5061;branch=z9hG4bK09db9c73" + m_CRLF +
"Contact: +3535xxx<sip:[email protected]:5061>" + m_CRLF +
"User-Agent: MSC/VC510 Build-Date Nov 7 2005" + m_CRLF +
"Allow: INVITE,BYE,CANCEL,OPTIONS,PRACK,NOTIFY,UPDATE,REFER" + m_CRLF +
"Supported: timer,replaces" + m_CRLF +
"Record-Route: <sip:213.168.225.133:5060;lr>,<sip:213.168.225.133:5061;lr>" + m_CRLF +
"Content-Type: application/sdp" + m_CRLF +
"Content-Length: 182" + m_CRLF +
m_CRLF +
"v=0" + m_CRLF +
"o=xxxxxxxxx 75160 1 IN IP4 127.127.127.30" + m_CRLF +
"s=-" + m_CRLF +
"c=IN IP4 127.127.127.30" + m_CRLF +
"t=0 0" + m_CRLF +
"m=audio 8002 RTP/AVP 0 101" + m_CRLF +
"a=rtpmap:0 PCMU/8000" + m_CRLF +
"a=rtpmap:101 telephone-event/8000" + m_CRLF +
"a=ptime:20";
SIPMessage sipMessage = SIPMessage.ParseSIPMessage(Encoding.UTF8.GetBytes(sipMsg), null, null);
SIPResponse okResp = SIPResponse.ParseSIPResponse(sipMessage);
Console.WriteLine("To: " + okResp.Header.To.ToString());
Assert.AreEqual(SIPResponseStatusCodesEnum.Ok, okResp.Status, "Response should have been ok.");
Assert.AreEqual("127.0.0.1", okResp.Header.To.ToURI.Host, "To URI host was not parsed correctly.");
Console.WriteLine("-----------------------------------------");
}
[Test]
public void ParseMultipleContactsResponse()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string sipMsg =
"SIP/2.0 200 OK" + m_CRLF +
"Via: SIP/2.0/UDP 192.168.1.32:64226;branch=z9hG4bK-d87543-ac7a6a75bc519655-1--d87543-;rport=64226;received=89.100.104.191" + m_CRLF +
"To: \"253989\"<sip:[email protected]>;tag=cb2000b247d89723001a836145f3b053.5b6c" + m_CRLF +
"From: \"253989\"<sip:[email protected]>;tag=9812dd2f" + m_CRLF +
"Call-ID: ODllYWY1NDJiNGMwYmQ1MjVmZmViMmEyMDViMGM0Y2Y." + m_CRLF +
"CSeq: 2 REGISTER" + m_CRLF +
"Date: Fri, 17 Nov 2006 17:15:35 GMT" + m_CRLF +
"Contact: <sip:[email protected]>;q=0.1;expires=3298, \"Joe Bloggs\"<sip:[email protected]:64226;rinstance=5720c5fed8cbcd34>;q=0.1;expires=3600" + m_CRLF +
"Content-Length: 0" + m_CRLF + m_CRLF;
SIPMessage sipMessage = SIPMessage.ParseSIPMessage(Encoding.UTF8.GetBytes(sipMsg), null, null);
SIPResponse okResp = SIPResponse.ParseSIPResponse(sipMessage);
Console.WriteLine("To: " + okResp.Header.To.ToString());
Assert.AreEqual(SIPResponseStatusCodesEnum.Ok, okResp.Status, "Response should have been ok.");
Assert.AreEqual(okResp.Header.Contact.Count, 2, "Response should have had two contacts.");
Assert.AreEqual(okResp.Header.Contact[0].ContactURI.ToString(), "sip:[email protected]", "The contact URI for the first contact header was incorrect.");
Assert.AreEqual(okResp.Header.Contact[0].Expires, 3298, "The expires value for the first contact header was incorrect.");
Assert.AreEqual(okResp.Header.Contact[0].Q, "0.1", "The q value for the first contact header was incorrect.");
Assert.AreEqual(okResp.Header.Contact[1].ContactName, "Joe Bloggs", "The contact name for the first contact header was incorrect.");
Assert.AreEqual(okResp.Header.Contact[1].ContactURI.ToString(), "sip:[email protected]:64226;rinstance=5720c5fed8cbcd34", "The contact URI for the first contact header was incorrect.");
Assert.AreEqual(okResp.Header.Contact[1].Expires, 3600, "The expires value for the second contact header was incorrect.");
Assert.AreEqual(okResp.Header.Contact[1].Q, "0.1", "The q value for the second contact header was incorrect.");
Console.WriteLine("-----------------------------------------");
}
[Test]
public void ParseMultiLineRecordRouteResponse()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string sipMsg =
"SIP/2.0 200 OK" + m_CRLF +
"Via: SIP/2.0/UDP 10.0.0.100:5060;rport=61540;branch=z9hG4bK40661a8b4a2d4973ae75fa52f1940383" + m_CRLF +
"From: <sip:[email protected]>;tag=1014391101" + m_CRLF +
"To: <sip:[email protected]>;tag=gj-2k5-490f768a-00005cf1-00002e1aR2f0f2383.b" + m_CRLF +
"Call-ID: 1960514b216a465fb900e2966d30e9bb" + m_CRLF +
"CSeq: 2 INVITE" + m_CRLF +
"Record-Route: <sip:77.75.25.44:5060;lr=on>" + m_CRLF +
"Record-Route: <sip:77.75.25.45:5060;lr=on;ftag=1014391101>" + m_CRLF +
"Accept: application/sdp, application/isup, application/dtmf, application/dtmf-relay, multipart/mixed" + m_CRLF +
"Contact: <sip:[email protected]:5060>" + m_CRLF +
"Allow: INVITE,ACK,CANCEL,BYE,REGISTER,REFER,INFO,SUBSCRIBE,NOTIFY,PRACK,UPDATE,OPTIONS" + m_CRLF +
"Supported: timer" + m_CRLF +
"Session-Expires: 600;refresher=uas" + m_CRLF +
"Content-Length: 232" + m_CRLF +
"Content-Disposition: session; handling=required" + m_CRLF +
"Content-Type: application/sdp" + m_CRLF +
m_CRLF +
"v=0" + m_CRLF +
"o=Sonus_UAC 4125 3983 IN IP4 64.152.60.78" + m_CRLF +
"s=SIP Media Capabilities" + m_CRLF +
"c=IN IP4 64.152.60.164" + m_CRLF +
"t=0 0" + m_CRLF +
"m=audio 19144 RTP/AVP 0 101" + m_CRLF +
"a=rtpmap:0 PCMU/8000" + m_CRLF +
"a=rtpmap:101 telephone-event/8000" + m_CRLF +
"a=fmtp:101 0-15" + m_CRLF +
"a=sendrecv" + m_CRLF +
"a=ptime:20" + m_CRLF;
SIPMessage sipMessage = SIPMessage.ParseSIPMessage(Encoding.UTF8.GetBytes(sipMsg), null, null);
SIPResponse okResp = SIPResponse.ParseSIPResponse(sipMessage);
Assert.IsTrue(okResp.Header.RecordRoutes.Length == 2, "The wrong number of Record-Route headers were present in the parsed response.");
Assert.IsTrue(okResp.Header.RecordRoutes.PopRoute().ToString() == "<sip:77.75.25.44:5060;lr=on>", "The top Record-Route header was incorrect.");
SIPRoute nextRoute = okResp.Header.RecordRoutes.PopRoute();
Assert.IsTrue(nextRoute.ToString() == "<sip:77.75.25.45:5060;lr=on;ftag=1014391101>", "The second Record-Route header was incorrect, " + nextRoute.ToString() + ".");
Console.WriteLine("-----------------------------------------");
}
[Test]
public void ParseMultiLineViaResponse()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string sipMsg =
"SIP/2.0 200 OK" + m_CRLF +
"Via: SIP/2.0/UDP 194.213.29.100:5060;branch=z9hG4bK5feb18267ce40fb05969b4ba843681dbfc9ffcff, SIP/2.0/UDP 194.213.29.54:5061;branch=z9hG4bK52b6a8b7" + m_CRLF +
"Record-Route: <sip:194.213.29.100:5060;lr>" + m_CRLF +
"From: Unknown <sip:[email protected]:5061>;tag=as58cbdbd1" + m_CRLF +
"To: <sip:[email protected]:5060>;tag=1144090013" + m_CRLF +
"Call-ID: [email protected]" + m_CRLF +
"CSeq: 102 INVITE" + m_CRLF +
"Contact: <sip:[email protected]:5060>" + m_CRLF +
"Server: Patton SN4634 3BIS 00A0BA04469B R5.3 2009-01-15 H323 SIP BRI M5T SIP Stack/4.0.28.28" + m_CRLF +
"Supported: replaces" + m_CRLF +
"Content-Type: application/sdp" + m_CRLF +
"Content-Length: 298" + m_CRLF +
m_CRLF +
"v=0" + m_CRLF +
"o=MxSIP 0 56 IN IP4 10.10.10.155" + m_CRLF +
"s=SIP Call" + m_CRLF +
"c=IN IP4 10.10.10.155" + m_CRLF +
"t=0 0" + m_CRLF +
"m=audio 4974 RTP/AVP 0 18 8 101" + m_CRLF +
"a=rtpmap:0 PCMU/8000" + m_CRLF +
"a=rtpmap:18 G729/8000" + m_CRLF +
"a=rtpmap:8 PCMA/8000" + m_CRLF +
"a=rtpmap:101 telephone-event/8000" + m_CRLF +
"a=fmtp:18 annexb=no" + m_CRLF +
"a=fmtp:101 0-16" + m_CRLF +
"a=sendrecv" + m_CRLF +
"m=video 0 RTP/AVP 31 34 103 99";
SIPMessage sipMessage = SIPMessage.ParseSIPMessage(Encoding.UTF8.GetBytes(sipMsg), null, null);
SIPResponse okResp = SIPResponse.ParseSIPResponse(sipMessage);
Assert.IsTrue(okResp.Header.Vias.Length == 2, "The wrong number of Record-Route headers were present in the parsed response.");
Assert.IsTrue(okResp.Header.Vias.TopViaHeader.ContactAddress == "194.213.29.100:5060", "The top via contact address was not ocrrectly parsed.");
Console.WriteLine("-----------------------------------------");
}
}
#endif
#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.IO;
using Xunit;
namespace System.Net.NetworkInformation.Tests
{
public class StatisticsParsingTests : FileCleanupTestBase
{
[Fact]
public void Icmpv4Parsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("snmp", fileName);
Icmpv4StatisticsTable table = StringParsingHelpers.ParseIcmpv4FromSnmpFile(fileName);
Assert.Equal(1, table.InMsgs);
Assert.Equal(2, table.InErrors);
Assert.Equal(3, table.InCsumErrors);
Assert.Equal(4, table.InDestUnreachs);
Assert.Equal(5, table.InTimeExcds);
Assert.Equal(6, table.InParmProbs);
Assert.Equal(7, table.InSrcQuenchs);
Assert.Equal(8, table.InRedirects);
Assert.Equal(9, table.InEchos);
Assert.Equal(10, table.InEchoReps);
Assert.Equal(20, table.InTimestamps);
Assert.Equal(30, table.InTimeStampReps);
Assert.Equal(40, table.InAddrMasks);
Assert.Equal(50, table.InAddrMaskReps);
Assert.Equal(60, table.OutMsgs);
Assert.Equal(70, table.OutErrors);
Assert.Equal(80, table.OutDestUnreachs);
Assert.Equal(90, table.OutTimeExcds);
Assert.Equal(100, table.OutParmProbs);
Assert.Equal(255, table.OutSrcQuenchs);
Assert.Equal(1024, table.OutRedirects);
Assert.Equal(256, table.OutEchos);
Assert.Equal(9001, table.OutEchoReps);
Assert.Equal(42, table.OutTimestamps);
Assert.Equal(4100414, table.OutTimestampReps);
Assert.Equal(2147483647, table.OutAddrMasks);
Assert.Equal(0, table.OutAddrMaskReps);
}
[Fact]
public void Icmpv6Parsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("snmp6", fileName);
Icmpv6StatisticsTable table = StringParsingHelpers.ParseIcmpv6FromSnmp6File(fileName);
Assert.Equal(1, table.InMsgs);
Assert.Equal(2, table.InErrors);
Assert.Equal(3, table.OutMsgs);
Assert.Equal(4, table.OutErrors);
Assert.Equal(6, table.InDestUnreachs);
Assert.Equal(7, table.InPktTooBigs);
Assert.Equal(8, table.InTimeExcds);
Assert.Equal(9, table.InParmProblems);
Assert.Equal(10, table.InEchos);
Assert.Equal(11, table.InEchoReplies);
Assert.Equal(12, table.InGroupMembQueries);
Assert.Equal(13, table.InGroupMembResponses);
Assert.Equal(14, table.InGroupMembReductions);
Assert.Equal(15, table.InRouterSolicits);
Assert.Equal(16, table.InRouterAdvertisements);
Assert.Equal(17, table.InNeighborSolicits);
Assert.Equal(18, table.InNeighborAdvertisements);
Assert.Equal(19, table.InRedirects);
Assert.Equal(21, table.OutDestUnreachs);
Assert.Equal(22, table.OutPktTooBigs);
Assert.Equal(23, table.OutTimeExcds);
Assert.Equal(24, table.OutParmProblems);
Assert.Equal(25, table.OutEchos);
Assert.Equal(26, table.OutEchoReplies);
Assert.Equal(27, table.OutInGroupMembQueries);
Assert.Equal(28, table.OutGroupMembResponses);
Assert.Equal(29, table.OutGroupMembReductions);
Assert.Equal(30, table.OutRouterSolicits);
Assert.Equal(31, table.OutRouterAdvertisements);
Assert.Equal(32, table.OutNeighborSolicits);
Assert.Equal(33, table.OutNeighborAdvertisements);
Assert.Equal(34, table.OutRedirects);
}
[Fact]
public void TcpGlobalStatisticsParsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("snmp", fileName);
TcpGlobalStatisticsTable table = StringParsingHelpers.ParseTcpGlobalStatisticsFromSnmpFile(fileName);
Assert.Equal(1, table.RtoAlgorithm);
Assert.Equal(200, table.RtoMin);
Assert.Equal(120000, table.RtoMax);
Assert.Equal(-1, table.MaxConn);
Assert.Equal(359, table.ActiveOpens);
Assert.Equal(28, table.PassiveOpens);
Assert.Equal(2, table.AttemptFails);
Assert.Equal(53, table.EstabResets);
Assert.Equal(4, table.CurrEstab);
Assert.Equal(21368, table.InSegs);
Assert.Equal(20642, table.OutSegs);
Assert.Equal(19, table.RetransSegs);
Assert.Equal(0, table.InErrs);
Assert.Equal(111, table.OutRsts);
Assert.Equal(0, table.InCsumErrors);
}
[Fact]
public void Udpv4GlobalStatisticsParsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("snmp", fileName);
UdpGlobalStatisticsTable table = StringParsingHelpers.ParseUdpv4GlobalStatisticsFromSnmpFile(fileName);
Assert.Equal(7181, table.InDatagrams);
Assert.Equal(150, table.NoPorts);
Assert.Equal(0, table.InErrors);
Assert.Equal(4386, table.OutDatagrams);
Assert.Equal(0, table.RcvbufErrors);
Assert.Equal(0, table.SndbufErrors);
Assert.Equal(1, table.InCsumErrors);
}
[Fact]
public void Udpv6GlobalStatisticsParsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("snmp6", fileName);
UdpGlobalStatisticsTable table = StringParsingHelpers.ParseUdpv6GlobalStatisticsFromSnmp6File(fileName);
Assert.Equal(19, table.InDatagrams);
Assert.Equal(0, table.NoPorts);
Assert.Equal(0, table.InErrors);
Assert.Equal(21, table.OutDatagrams);
Assert.Equal(99999, table.RcvbufErrors);
Assert.Equal(11011011, table.SndbufErrors);
Assert.Equal(0, table.InCsumErrors);
}
[Fact]
public void Ipv4GlobalStatisticsParsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("snmp", fileName);
IPGlobalStatisticsTable table = StringParsingHelpers.ParseIPv4GlobalStatisticsFromSnmpFile(fileName);
Assert.Equal(false, table.Forwarding);
Assert.Equal(64, table.DefaultTtl);
Assert.Equal(28121, table.InReceives);
Assert.Equal(0, table.InHeaderErrors);
Assert.Equal(2, table.InAddressErrors);
Assert.Equal(0, table.ForwardedDatagrams);
Assert.Equal(0, table.InUnknownProtocols);
Assert.Equal(0, table.InDiscards);
Assert.Equal(28117, table.InDelivers);
Assert.Equal(24616, table.OutRequests);
Assert.Equal(48, table.OutDiscards);
Assert.Equal(0, table.OutNoRoutes);
Assert.Equal(0, table.ReassemblyTimeout);
Assert.Equal(0, table.ReassemblyRequireds);
Assert.Equal(1, table.ReassemblyOKs);
Assert.Equal(2, table.ReassemblyFails);
Assert.Equal(14, table.FragmentOKs);
Assert.Equal(0, table.FragmentFails);
Assert.Equal(92, table.FragmentCreates);
}
[Fact]
public void Ipv6GlobalStatisticsParsing()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("snmp6", fileName);
IPGlobalStatisticsTable table = StringParsingHelpers.ParseIPv6GlobalStatisticsFromSnmp6File(fileName);
Assert.Equal(189, table.InReceives);
Assert.Equal(0, table.InHeaderErrors);
Assert.Equal(2000, table.InAddressErrors);
Assert.Equal(42, table.InUnknownProtocols);
Assert.Equal(0, table.InDiscards);
Assert.Equal(189, table.InDelivers);
Assert.Equal(55, table.ForwardedDatagrams);
Assert.Equal(199, table.OutRequests);
Assert.Equal(0, table.OutDiscards);
Assert.Equal(53, table.OutNoRoutes);
Assert.Equal(2121, table.ReassemblyTimeout);
Assert.Equal(1, table.ReassemblyRequireds);
Assert.Equal(2, table.ReassemblyOKs);
Assert.Equal(4, table.ReassemblyFails);
Assert.Equal(8, table.FragmentOKs);
Assert.Equal(16, table.FragmentFails);
Assert.Equal(32, table.FragmentCreates);
}
[Fact]
public void IpInterfaceStatisticsParsingFirst()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("dev", fileName);
IPInterfaceStatisticsTable table = StringParsingHelpers.ParseInterfaceStatisticsTableFromFile(fileName, "wlan0");
Assert.Equal(26622u, table.BytesReceived);
Assert.Equal(394u, table.PacketsReceived);
Assert.Equal(2u, table.ErrorsReceived);
Assert.Equal(4u, table.IncomingPacketsDropped);
Assert.Equal(6u, table.FifoBufferErrorsReceived);
Assert.Equal(8u, table.PacketFramingErrorsReceived);
Assert.Equal(10u, table.CompressedPacketsReceived);
Assert.Equal(12u, table.MulticastFramesReceived);
Assert.Equal(27465u, table.BytesTransmitted);
Assert.Equal(208u, table.PacketsTransmitted);
Assert.Equal(1u, table.ErrorsTransmitted);
Assert.Equal(2u, table.OutgoingPacketsDropped);
Assert.Equal(3u, table.FifoBufferErrorsTransmitted);
Assert.Equal(4u, table.CollisionsDetected);
Assert.Equal(5u, table.CarrierLosses);
Assert.Equal(6u, table.CompressedPacketsTransmitted);
}
[Fact]
public void IpInterfaceStatisticsParsingLast()
{
string fileName = GetTestFilePath();
FileUtil.NormalizeLineEndings("dev", fileName);
IPInterfaceStatisticsTable table = StringParsingHelpers.ParseInterfaceStatisticsTableFromFile(fileName, "lo");
Assert.Equal(uint.MaxValue, table.BytesReceived);
Assert.Equal(302u, table.PacketsReceived);
Assert.Equal(0u, table.ErrorsReceived);
Assert.Equal(0u, table.IncomingPacketsDropped);
Assert.Equal(0u, table.FifoBufferErrorsReceived);
Assert.Equal(0u, table.PacketFramingErrorsReceived);
Assert.Equal(0u, table.CompressedPacketsReceived);
Assert.Equal(0u, table.MulticastFramesReceived);
Assert.Equal(30008u, table.BytesTransmitted);
Assert.Equal(302u, table.PacketsTransmitted);
Assert.Equal(0u, table.ErrorsTransmitted);
Assert.Equal(0u, table.OutgoingPacketsDropped);
Assert.Equal(0u, table.FifoBufferErrorsTransmitted);
Assert.Equal(0u, table.CollisionsDetected);
Assert.Equal(0u, table.CarrierLosses);
Assert.Equal(0u, table.CompressedPacketsTransmitted);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ToolStripDropTargetManager.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System;
using System.ComponentModel;
using System.Drawing;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using System.Security;
using System.Globalization;
/// <devdoc>
/// Why do we have this class? Well it seems that RegisterDropTarget
/// requires an HWND to back it's IDropTargets. Since some ToolStripItems
/// do not have HWNDS, this guy's got to figure out who the event was
/// really supposed to go to and pass it on to it.
/// </devdoc>
internal class ToolStripDropTargetManager : IDropTarget {
private IDropTarget lastDropTarget;
private ToolStrip owner;
#if DEBUG
private bool dropTargetIsEntered;
#endif
#if DEBUG
internal static readonly TraceSwitch DragDropDebug = new TraceSwitch("DragDropDebug", "Debug ToolStrip DragDrop code");
#else
internal static readonly TraceSwitch DragDropDebug;
#endif
/// <devdoc>
/// Summary of ToolStripDropTargetManager.
/// </devdoc>
/// <param name=owner></param>
public ToolStripDropTargetManager(ToolStrip owner) {
this.owner = owner;
if (owner == null) {
throw new ArgumentNullException("owner");
}
}
/// <devdoc>
/// Summary of EnsureRegistered.
/// </devdoc>
/// <param name=dropTarget></param>
public void EnsureRegistered(IDropTarget dropTarget) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Ensuring drop target registered");
SetAcceptDrops(true);
}
/// <devdoc>
/// Summary of EnsureUnRegistered.
/// </devdoc>
/// <param name=dropTarget></param>
public void EnsureUnRegistered(IDropTarget dropTarget) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Attempting to unregister droptarget");
for (int i = 0; i < owner.Items.Count; i++) {
if (owner.Items[i].AllowDrop) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "An item still has allowdrop set to true - cant unregister");
return; // can't unregister this as a drop target unless everyone is done.
}
}
if (owner.AllowDrop || owner.AllowItemReorder) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "The ToolStrip has AllowDrop or AllowItemReorder set to true - cant unregister");
return; // can't unregister this as a drop target if ToolStrip is still accepting drops
}
SetAcceptDrops(false);
owner.DropTargetManager = null;
}
/// <devdoc>
/// Takes a screen point and converts it into an item. May return null.
/// </devdoc>
/// <param name=x></param>
/// <param name=y></param>
private ToolStripItem FindItemAtPoint(int x, int y) {
return owner.GetItemAt(owner.PointToClient(new Point(x,y)));
}
/// <devdoc>
/// Summary of OnDragEnter.
/// </devdoc>
/// <param name=e></param>
public void OnDragEnter(DragEventArgs e) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "[DRAG ENTER] ==============");
// If we are supporting Item Reordering
// and this is a ToolStripItem - snitch it.
if (owner.AllowItemReorder && e.Data.GetDataPresent(typeof(ToolStripItem))) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ItemReorderTarget taking this...");
lastDropTarget = owner.ItemReorderDropTarget;
}
else {
ToolStripItem item = FindItemAtPoint(e.X, e.Y);
if ((item != null) && (item.AllowDrop)) {
// the item wants this event
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ToolStripItem taking this: " + item.ToString());
lastDropTarget = ((IDropTarget)item);
}
else if (owner.AllowDrop) {
// the winbar wants this event
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ToolStrip taking this because AllowDrop set to true.");
lastDropTarget = ((IDropTarget)owner);
}
else {
// There could be one item that says "AllowDrop == true" which would turn
// on this drop target manager. If we're not over that particular item - then
// just null out the last drop target manager.
// the other valid reason for being here is that we've done an AllowItemReorder
// and we dont have a ToolStripItem contain within the data (say someone drags a link
// from IE over the ToolStrip)
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "No one wanted it.");
lastDropTarget = null;
}
}
if (lastDropTarget != null) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Calling OnDragEnter on target...");
#if DEBUG
dropTargetIsEntered=true;
#endif
lastDropTarget.OnDragEnter(e);
}
}
/// <devdoc>
/// Summary of OnDragOver.
/// </devdoc>
/// <param name=e></param>
public void OnDragOver(DragEventArgs e) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "[DRAG OVER] ==============");
IDropTarget newDropTarget = null;
// If we are supporting Item Reordering
// and this is a ToolStripItem - snitch it.
if (owner.AllowItemReorder && e.Data.GetDataPresent(typeof(ToolStripItem))) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ItemReorderTarget taking this...");
newDropTarget = owner.ItemReorderDropTarget;
}
else {
ToolStripItem item = FindItemAtPoint(e.X, e.Y);
if ((item != null) && (item.AllowDrop)) {
// the item wants this event
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ToolStripItem taking this: " + item.ToString());
newDropTarget = ((IDropTarget)item);
}
else if (owner.AllowDrop) {
// the winbar wants this event
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "ToolStrip taking this because AllowDrop set to true.");
newDropTarget = ((IDropTarget)owner);
}
else {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "No one wanted it.");
newDropTarget = null;
}
}
// if we've switched drop targets - then
// we need to create drag enter and leave events
if (newDropTarget != lastDropTarget) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "NEW DROP TARGET!");
UpdateDropTarget(newDropTarget, e);
}
// now call drag over
if (lastDropTarget != null) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Calling OnDragOver on target...");
lastDropTarget.OnDragOver(e);
}
}
/// <devdoc>
/// Summary of OnDragLeave.
/// </devdoc>
/// <param name=e></param>
public void OnDragLeave(System.EventArgs e) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "[DRAG LEAVE] ==============");
if (lastDropTarget != null) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Calling OnDragLeave on current target...");
#if DEBUG
dropTargetIsEntered=false;
#endif
lastDropTarget.OnDragLeave(e);
}
#if DEBUG
else {
Debug.Assert(!dropTargetIsEntered, "Why do we have an entered droptarget and NO lastDropTarget?");
}
#endif
lastDropTarget = null;
}
/// <devdoc>
/// Summary of OnDragDrop.
/// </devdoc>
/// <param name=e></param>
public void OnDragDrop(DragEventArgs e) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "[DRAG DROP] ==============");
if (lastDropTarget != null) {
Debug.WriteLineIf(DragDropDebug.TraceVerbose, "Calling OnDragDrop on current target...");
lastDropTarget.OnDragDrop(e);
}
else {
Debug.Assert(false, "Why is lastDropTarget null?");
}
lastDropTarget = null;
}
/// <devdoc>
/// Used to actually register the control as a drop target.
/// </devdoc>
/// <internalonly/>
/// <param name=accept></param>
private void SetAcceptDrops(bool accept) {
if (owner.AllowDrop && accept) {
// if the owner has set AllowDrop to true then demand Clipboard permissions.
// else its us, and we can assert them.
IntSecurity.ClipboardRead.Demand();
}
if (accept && owner.IsHandleCreated) {
try
{
if (Application.OleRequired() != System.Threading.ApartmentState.STA)
{
throw new ThreadStateException(SR.GetString(SR.ThreadMustBeSTA));
}
if (accept)
{
Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "Registering as drop target: " + owner.Handle.ToString());
// Register
int n = UnsafeNativeMethods.RegisterDragDrop(new HandleRef(owner, owner.Handle), (UnsafeNativeMethods.IOleDropTarget)(new DropTarget(this)));
Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, " ret:" + n.ToString(CultureInfo.InvariantCulture));
if (n != 0 && n != NativeMethods.DRAGDROP_E_ALREADYREGISTERED)
{
throw new Win32Exception(n);
}
}
else
{
IntSecurity.ClipboardRead.Assert();
try
{
Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, "Revoking drop target: " + owner.Handle.ToString());
// Revoke
int n = UnsafeNativeMethods.RevokeDragDrop(new HandleRef(owner, owner.Handle));
Debug.WriteLineIf(CompModSwitches.DragDrop.TraceInfo, " ret:" + n.ToString(CultureInfo.InvariantCulture));
if (n != 0 && n != NativeMethods.DRAGDROP_E_NOTREGISTERED)
{
throw new Win32Exception(n);
}
}
finally
{
CodeAccessPermission.RevertAssert();
}
}
}
catch (Exception e)
{
throw new InvalidOperationException(SR.GetString(SR.DragDropRegFailed), e);
}
}
}
/// <devdoc>
/// if we have a new active item, fire drag leave and
/// enter. This corresponds to the case where you
/// are dragging between items and havent actually
/// left the ToolStrip's client area.
/// </devdoc>
/// <param name=newTarget></param>
/// <param name=e></param>
private void UpdateDropTarget(IDropTarget newTarget, DragEventArgs e) {
if (newTarget != lastDropTarget) {
// tell the last drag target you've left
if (lastDropTarget != null) {
OnDragLeave(new EventArgs());
}
lastDropTarget = newTarget;
if (newTarget != null) {
DragEventArgs dragEnterArgs = new DragEventArgs(e.Data, e.KeyState, e.X, e.Y, e.AllowedEffect, e.Effect);
dragEnterArgs.Effect = DragDropEffects.None;
// tell the next drag target you've entered
OnDragEnter(dragEnterArgs);
}
}
}
}
}
| |
// 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.
using UnityEngine;
using System.Collections.Generic;
namespace DaydreamElements.ClickMenu {
/// The Painter manages a collection of paint strokes and is responsible
/// for creating, modifying, and removing the strokes.
public class Painter : MonoBehaviour {
private const float PENCIL_THICKNESS = 0.004f;
private const float PEN_THICKNESS = 0.005f;
private const float MARKER_THICKNESS = 0.015f;
private const float ROLLER_THICKNESS = 0.08f;
private const float MIN_VERTEX_DISPLACEMENT = 0.003f;
public class Stroke {
public GameObject obj;
public List<Vector3> vertices = new List<Vector3>();
public List<int> indices = new List<int>();
public Material savedMat;
}
private Vector3 lastPoint;
private List<Stroke> strokes;
private List<Stroke> savedStrokes;
private Stroke curStroke;
private Mesh curMesh;
private MeshRenderer curMeshRenderer;
private float brushThickness;
private bool useControllerAngle;
private Material paintMaterial;
public bool IsEraser { get; private set; }
private MaterialPropertyBlock propertyBlock;
public ClickMenuRoot menuRoot;
public GvrLaserPointer laserPointer;
public MeshRenderer reticle;
public Material red;
public Material orange;
public Material yellow;
public Material green;
public Material blue;
public Material purple;
public Material white;
public Material black;
public Material cursorPencil;
public Material cursorPen;
public Material cursorHighlighter;
public Material cursorRoller;
public Material cursorEraser;
private Material initialReticleMaterial;
private Material currentBrushMaterial;
public void UseInitialMaterial() {
reticle.sharedMaterial = initialReticleMaterial;
}
public void UseBrushMaterial() {
reticle.sharedMaterial = currentBrushMaterial;
}
public void SetMaterial(Material material) {
paintMaterial = material;
if (material && !IsEraser) {
reticle.GetPropertyBlock(propertyBlock);
propertyBlock.SetColor("_Color", paintMaterial.color);
reticle.SetPropertyBlock(propertyBlock);
}
}
private void SetReticleMaterial(Material material, Color color) {
reticle.sharedMaterial = material;
currentBrushMaterial = material;
reticle.GetPropertyBlock(propertyBlock);
propertyBlock.SetColor("_Color", color);
reticle.SetPropertyBlock(propertyBlock);
}
public void SetBrushPencil() {
SetReticleMaterial(cursorPencil, paintMaterial.color);
brushThickness = PENCIL_THICKNESS;
useControllerAngle = false;
IsEraser = false;
}
public void SetBrushPen() {
SetReticleMaterial(cursorPen, paintMaterial.color);
brushThickness = PEN_THICKNESS;
useControllerAngle = true;
IsEraser = false;
}
public void SetBrushMarker() {
SetReticleMaterial(cursorHighlighter, paintMaterial.color);
brushThickness = MARKER_THICKNESS;
useControllerAngle = false;
IsEraser = false;
}
public void SetBrushRoller() {
SetReticleMaterial(cursorRoller, paintMaterial.color);
brushThickness = ROLLER_THICKNESS;
useControllerAngle = true;
IsEraser = false;
}
public void SetBrushEraser() {
SetReticleMaterial(cursorEraser, Color.white);
brushThickness = 0.0f;
useControllerAngle = false;
IsEraser = true;
}
public void Undo() {
curStroke = null;
if (strokes.Count > 0) {
Destroy(strokes[strokes.Count - 1].obj);
strokes.RemoveAt(strokes.Count - 1);
}
System.GC.Collect();
}
public void Clear() {
foreach (Stroke stroke in strokes) {
Destroy(stroke.obj);
}
strokes.Clear();
System.GC.Collect();
}
public void RemoveStroke(Stroke stroke) {
Debug.Log("RemoveStroke");
if (strokes.Remove(stroke)) {
Destroy(stroke.obj);
Debug.Log("DestroyStroke");
}
}
public void Save() {
savedStrokes = new List<Stroke>();
for (int i = 0; i < strokes.Count; ++i) {
Stroke strokeCopy = new Stroke();
strokeCopy.indices = new List<int>(strokes[i].indices);
strokeCopy.vertices = new List<Vector3>(strokes[i].vertices);
strokeCopy.savedMat = strokes[i].obj.GetComponent<MeshRenderer>().sharedMaterial;
savedStrokes.Add(strokeCopy);
}
}
public void Load() {
if (savedStrokes != null) {
Clear();
for (int i = 0; i < savedStrokes.Count; ++i) {
CreateCurrentStroke();
curMeshRenderer.sharedMaterial = savedStrokes[i].savedMat;
curStroke.indices = new List<int>(savedStrokes[i].indices);
curStroke.vertices = new List<Vector3>(savedStrokes[i].vertices);
UpdateCurMesh();
strokes.Add(curStroke);
}
curStroke = null;
}
}
void Awake() {
propertyBlock = new MaterialPropertyBlock();
initialReticleMaterial = reticle.sharedMaterial;
strokes = new List<Stroke>();
paintMaterial = blue;
SetBrushPencil();
menuRoot.OnItemSelected += OnItemSelected;
}
private void OnItemSelected(ClickMenuItem item) {
int id = (item ? item.id : -1);
switch (id) {
// Brushes
case 1:
SetBrushPencil();
break;
case 2:
SetBrushPen();
break;
case 3:
SetBrushMarker();
break;
case 4:
SetBrushRoller();
break;
case 5:
SetBrushEraser();
break;
// Colors
case 10:
SetMaterial(red);
break;
case 11:
SetMaterial(orange);
break;
case 12:
SetMaterial(yellow);
break;
case 13:
SetMaterial(green);
break;
case 14:
SetMaterial(blue);
break;
case 15:
SetMaterial(purple);
break;
case 16:
SetMaterial(white);
break;
case 17:
SetMaterial(black);
break;
// Undo
case 20:
Undo();
break;
// Painting
case 30:
Save();
break;
case 31:
Load();
break;
case 32:
Clear();
break;
}
}
void Update() {
// It is expected that this object will be positioned at the same location as the
// parent of the camera.
Transform cameraParent = Camera.main.transform.parent;
transform.position = cameraParent.position;
transform.rotation = cameraParent.rotation;
// Do not allow painting if the menu system is open
if (menuRoot.IsMenuOpen()) {
EndStroke();
return;
}
// Start, stop, or continue painting
if (GvrControllerInput.ClickButtonDown) {
StartStroke();
} else if (GvrControllerInput.ClickButtonUp) {
EndStroke();
} else if (GvrControllerInput.ClickButton) {
ContinueStroke();
}
}
void OnDestory() {
Clear();
}
private void CreateCurrentStroke() {
curStroke = new Stroke();
curStroke.obj = new GameObject("Stroke " + strokes.Count);
curStroke.obj.transform.SetParent(transform, false);
curStroke.obj.AddComponent<PainterStroke>().Init(this, curStroke);
curMesh = curStroke.obj.GetComponent<MeshFilter>().sharedMesh;
curMeshRenderer = curStroke.obj.GetComponent<MeshRenderer>();
curMeshRenderer.sharedMaterial = paintMaterial;
}
private void StartStroke() {
if (!IsEraser) {
lastPoint = GetBrushPosition();
CreateCurrentStroke();
strokes.Add(curStroke);
}
}
private void EndStroke() {
curStroke = null;
}
private void ContinueStroke() {
if (!IsEraser && curStroke != null) {
AddNextVertex();
}
}
private Vector3 GetBrushPosition() {
GvrLaserPointer pointer = GvrPointerInputModule.Pointer as GvrLaserPointer;
if (pointer == null) {
return Vector3.zero;
}
Vector3 pointerEndPoint;
if (pointer.CurrentRaycastResult.gameObject != null) {
pointerEndPoint = pointer.CurrentRaycastResult.worldPosition;
} else {
pointerEndPoint = pointer.GetPointAlongPointer(pointer.defaultReticleDistance);
}
Vector3 result = transform.InverseTransformPoint(pointerEndPoint);
return result;
}
private void UpdateCurMesh() {
curMesh.vertices = curStroke.vertices.ToArray();
curMesh.SetIndices(curStroke.indices.ToArray(), MeshTopology.Triangles, 0);
curMesh.RecalculateBounds();
}
private void AddNextVertex() {
// Check if enough movement has occurred
Vector3 newPoint = GetBrushPosition();
Vector3 delta = newPoint - lastPoint;
if (delta.magnitude < MIN_VERTEX_DISPLACEMENT) {
return;
}
// If this is the first time here, add, the base-vertex
if (curStroke.vertices.Count == 0) {
Vector3 perpLast = GetPerpVector(delta, lastPoint);
curStroke.vertices.Add(lastPoint + perpLast);
curStroke.vertices.Add(lastPoint - perpLast);
}
// Add the next vertex
Vector3 perp = GetPerpVector(delta, newPoint);
curStroke.vertices.Add(lastPoint + perp);
curStroke.vertices.Add(lastPoint - perp);
// Add the next triangles
int vIndex = curStroke.vertices.Count;
curStroke.indices.Add(vIndex - 1);
curStroke.indices.Add(vIndex - 2);
curStroke.indices.Add(vIndex - 3);
curStroke.indices.Add(vIndex - 4);
curStroke.indices.Add(vIndex - 3);
curStroke.indices.Add(vIndex - 2);
if (useControllerAngle) {
curStroke.indices.Add(vIndex - 3);
curStroke.indices.Add(vIndex - 2);
curStroke.indices.Add(vIndex - 1);
curStroke.indices.Add(vIndex - 2);
curStroke.indices.Add(vIndex - 3);
curStroke.indices.Add(vIndex - 4);
}
// Update the mesh
UpdateCurMesh();
// Update the last point
lastPoint = newPoint;
}
private Vector3 GetPerpVector(Vector3 delta, Vector3 point) {
Vector3 sideDir = useControllerAngle ? GvrControllerInput.Orientation * Vector3.up : delta;
return Vector3.Cross(sideDir, point).normalized * brushThickness;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
using Mono.Data.Sqlite;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Data.SQLite
{
/// <summary>
/// An Inventory Interface to the SQLite database
/// </summary>
public class SQLiteInventoryStore : SQLiteUtil, IInventoryDataPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const string invItemsSelect = "select * from inventoryitems";
private const string invFoldersSelect = "select * from inventoryfolders";
private SqliteConnection conn;
private DataSet ds;
private SqliteDataAdapter invItemsDa;
private SqliteDataAdapter invFoldersDa;
public void Initialise()
{
m_log.Info("[SQLiteInventoryData]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
/// <summary>
/// <list type="bullet">
/// <item>Initialises Inventory interface</item>
/// <item>Loads and initialises a new SQLite connection and maintains it.</item>
/// <item>use default URI if connect string string is empty.</item>
/// </list>
/// </summary>
/// <param name="dbconnect">connect string</param>
public void Initialise(string dbconnect)
{
if (dbconnect == string.Empty)
{
dbconnect = "URI=file:inventoryStore.db,version=3";
}
m_log.Info("[INVENTORY DB]: Sqlite - connecting: " + dbconnect);
conn = new SqliteConnection(dbconnect);
conn.Open();
Assembly assem = GetType().Assembly;
Migration m = new Migration(conn, assem, "InventoryStore");
m.Update();
SqliteCommand itemsSelectCmd = new SqliteCommand(invItemsSelect, conn);
invItemsDa = new SqliteDataAdapter(itemsSelectCmd);
// SqliteCommandBuilder primCb = new SqliteCommandBuilder(primDa);
SqliteCommand foldersSelectCmd = new SqliteCommand(invFoldersSelect, conn);
invFoldersDa = new SqliteDataAdapter(foldersSelectCmd);
ds = new DataSet();
ds.Tables.Add(createInventoryFoldersTable());
invFoldersDa.Fill(ds.Tables["inventoryfolders"]);
setupFoldersCommands(invFoldersDa, conn);
CreateDataSetMapping(invFoldersDa, "inventoryfolders");
m_log.Info("[INVENTORY DB]: Populated Inventory Folders Definitions");
ds.Tables.Add(createInventoryItemsTable());
invItemsDa.Fill(ds.Tables["inventoryitems"]);
setupItemsCommands(invItemsDa, conn);
CreateDataSetMapping(invItemsDa, "inventoryitems");
m_log.Info("[INVENTORY DB]: Populated Inventory Items Definitions");
ds.AcceptChanges();
}
/// <summary>
/// Closes the inventory interface
/// </summary>
public void Dispose()
{
if (conn != null)
{
conn.Close();
conn = null;
}
if (invItemsDa != null)
{
invItemsDa.Dispose();
invItemsDa = null;
}
if (invFoldersDa != null)
{
invFoldersDa.Dispose();
invFoldersDa = null;
}
if (ds != null)
{
ds.Dispose();
ds = null;
}
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public InventoryItemBase buildItem(DataRow row)
{
InventoryItemBase item = new InventoryItemBase();
item.ID = new UUID((string) row["UUID"]);
item.AssetID = new UUID((string) row["assetID"]);
item.AssetType = Convert.ToInt32(row["assetType"]);
item.InvType = Convert.ToInt32(row["invType"]);
item.Folder = new UUID((string) row["parentFolderID"]);
item.Owner = new UUID((string) row["avatarID"]);
item.CreatorId = (string)row["creatorsID"];
item.Name = (string) row["inventoryName"];
item.Description = (string) row["inventoryDescription"];
item.NextPermissions = Convert.ToUInt32(row["inventoryNextPermissions"]);
item.CurrentPermissions = Convert.ToUInt32(row["inventoryCurrentPermissions"]);
item.BasePermissions = Convert.ToUInt32(row["inventoryBasePermissions"]);
item.EveryOnePermissions = Convert.ToUInt32(row["inventoryEveryOnePermissions"]);
item.GroupPermissions = Convert.ToUInt32(row["inventoryGroupPermissions"]);
// new fields
if (!Convert.IsDBNull(row["salePrice"]))
item.SalePrice = Convert.ToInt32(row["salePrice"]);
if (!Convert.IsDBNull(row["saleType"]))
item.SaleType = Convert.ToByte(row["saleType"]);
if (!Convert.IsDBNull(row["creationDate"]))
item.CreationDate = Convert.ToInt32(row["creationDate"]);
if (!Convert.IsDBNull(row["groupID"]))
item.GroupID = new UUID((string)row["groupID"]);
if (!Convert.IsDBNull(row["groupOwned"]))
item.GroupOwned = Convert.ToBoolean(row["groupOwned"]);
if (!Convert.IsDBNull(row["Flags"]))
item.Flags = Convert.ToUInt32(row["Flags"]);
return item;
}
/// <summary>
/// Fill a database row with item data
/// </summary>
/// <param name="row"></param>
/// <param name="item"></param>
private static void fillItemRow(DataRow row, InventoryItemBase item)
{
row["UUID"] = item.ID.ToString();
row["assetID"] = item.AssetID.ToString();
row["assetType"] = item.AssetType;
row["invType"] = item.InvType;
row["parentFolderID"] = item.Folder.ToString();
row["avatarID"] = item.Owner.ToString();
row["creatorsID"] = item.CreatorId.ToString();
row["inventoryName"] = item.Name;
row["inventoryDescription"] = item.Description;
row["inventoryNextPermissions"] = item.NextPermissions;
row["inventoryCurrentPermissions"] = item.CurrentPermissions;
row["inventoryBasePermissions"] = item.BasePermissions;
row["inventoryEveryOnePermissions"] = item.EveryOnePermissions;
row["inventoryGroupPermissions"] = item.GroupPermissions;
// new fields
row["salePrice"] = item.SalePrice;
row["saleType"] = item.SaleType;
row["creationDate"] = item.CreationDate;
row["groupID"] = item.GroupID.ToString();
row["groupOwned"] = item.GroupOwned;
row["flags"] = item.Flags;
}
/// <summary>
/// Add inventory folder
/// </summary>
/// <param name="folder">Folder base</param>
/// <param name="add">true=create folder. false=update existing folder</param>
/// <remarks>nasty</remarks>
private void addFolder(InventoryFolderBase folder, bool add)
{
lock (ds)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString());
if (inventoryRow == null)
{
if (! add)
m_log.ErrorFormat("Interface Misuse: Attempting to Update non-existant inventory folder: {0}", folder.ID);
inventoryRow = inventoryFolderTable.NewRow();
fillFolderRow(inventoryRow, folder);
inventoryFolderTable.Rows.Add(inventoryRow);
}
else
{
if (add)
m_log.ErrorFormat("Interface Misuse: Attempting to Add inventory folder that already exists: {0}", folder.ID);
fillFolderRow(inventoryRow, folder);
}
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/// <summary>
/// Move an inventory folder
/// </summary>
/// <param name="folder">folder base</param>
private void moveFolder(InventoryFolderBase folder)
{
lock (ds)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString());
if (inventoryRow == null)
{
inventoryRow = inventoryFolderTable.NewRow();
fillFolderRow(inventoryRow, folder);
inventoryFolderTable.Rows.Add(inventoryRow);
}
else
{
moveFolderRow(inventoryRow, folder);
}
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/// <summary>
/// add an item in inventory
/// </summary>
/// <param name="item">the item</param>
/// <param name="add">true=add item ; false=update existing item</param>
private void addItem(InventoryItemBase item, bool add)
{
lock (ds)
{
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
DataRow inventoryRow = inventoryItemTable.Rows.Find(item.ID.ToString());
if (inventoryRow == null)
{
if (!add)
m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Update non-existant inventory item: {0}", item.ID);
inventoryRow = inventoryItemTable.NewRow();
fillItemRow(inventoryRow, item);
inventoryItemTable.Rows.Add(inventoryRow);
}
else
{
if (add)
m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Add inventory item that already exists: {0}", item.ID);
fillItemRow(inventoryRow, item);
}
invItemsDa.Update(ds, "inventoryitems");
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
inventoryRow = inventoryFolderTable.Rows.Find(item.Folder.ToString());
if (inventoryRow != null) //MySQL doesn't throw an exception here, so sqlite shouldn't either.
inventoryRow["version"] = (int)inventoryRow["version"] + 1;
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/// <summary>
/// TODO : DataSet commit
/// </summary>
public void Shutdown()
{
// TODO: DataSet commit
}
/// <summary>
/// The name of this DB provider
/// </summary>
/// <returns>Name of DB provider</returns>
public string Name
{
get { return "SQLite Inventory Data Interface"; }
}
/// <summary>
/// Returns the version of this DB provider
/// </summary>
/// <returns>A string containing the DB provider version</returns>
public string Version
{
get
{
Module module = GetType().Module;
// string dllName = module.Assembly.ManifestModule.Name;
Version dllVersion = module.Assembly.GetName().Version;
return
string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
dllVersion.Revision);
}
}
/// <summary>
/// Returns a list of inventory items contained within the specified folder
/// </summary>
/// <param name="folderID">The UUID of the target folder</param>
/// <returns>A List of InventoryItemBase items</returns>
public List<InventoryItemBase> getInventoryInFolder(UUID folderID)
{
lock (ds)
{
List<InventoryItemBase> retval = new List<InventoryItemBase>();
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
string selectExp = "parentFolderID = '" + folderID + "'";
DataRow[] rows = inventoryItemTable.Select(selectExp);
foreach (DataRow row in rows)
{
retval.Add(buildItem(row));
}
return retval;
}
}
/// <summary>
/// Returns a list of the root folders within a users inventory
/// </summary>
/// <param name="user">The user whos inventory is to be searched</param>
/// <returns>A list of folder objects</returns>
public List<InventoryFolderBase> getUserRootFolders(UUID user)
{
return new List<InventoryFolderBase>();
}
// see InventoryItemBase.getUserRootFolder
public InventoryFolderBase getUserRootFolder(UUID user)
{
lock (ds)
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "agentID = '" + user + "' AND parentID = '" + UUID.Zero + "'";
DataRow[] rows = inventoryFolderTable.Select(selectExp);
foreach (DataRow row in rows)
{
folders.Add(buildFolder(row));
}
// There should only ever be one root folder for a user. However, if there's more
// than one we'll simply use the first one rather than failing. It would be even
// nicer to print some message to this effect, but this feels like it's too low a
// to put such a message out, and it's too minor right now to spare the time to
// suitably refactor.
if (folders.Count > 0)
{
return folders[0];
}
return null;
}
}
/// <summary>
/// Append a list of all the child folders of a parent folder
/// </summary>
/// <param name="folders">list where folders will be appended</param>
/// <param name="parentID">ID of parent</param>
protected void getInventoryFolders(ref List<InventoryFolderBase> folders, UUID parentID)
{
lock (ds)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "parentID = '" + parentID + "'";
DataRow[] rows = inventoryFolderTable.Select(selectExp);
foreach (DataRow row in rows)
{
folders.Add(buildFolder(row));
}
}
}
/// <summary>
/// Returns a list of inventory folders contained in the folder 'parentID'
/// </summary>
/// <param name="parentID">The folder to get subfolders for</param>
/// <returns>A list of inventory folders</returns>
public List<InventoryFolderBase> getInventoryFolders(UUID parentID)
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
getInventoryFolders(ref folders, parentID);
return folders;
}
/// <summary>
/// See IInventoryDataPlugin
/// </summary>
/// <param name="parentID"></param>
/// <returns></returns>
public List<InventoryFolderBase> getFolderHierarchy(UUID parentID)
{
/* Note: There are subtle changes between this implementation of getFolderHierarchy and the previous one
* - We will only need to hit the database twice instead of n times.
* - We assume the database is well-formed - no stranded/dangling folders, all folders in heirarchy owned
* by the same person, each user only has 1 inventory heirarchy
* - The returned list is not ordered, instead of breadth-first ordered
There are basically 2 usage cases for getFolderHeirarchy:
1) Getting the user's entire inventory heirarchy when they log in
2) Finding a subfolder heirarchy to delete when emptying the trash.
This implementation will pull all inventory folders from the database, and then prune away any folder that
is not part of the requested sub-heirarchy. The theory is that it is cheaper to make 1 request from the
database than to make n requests. This pays off only if requested heirarchy is large.
By making this choice, we are making the worst case better at the cost of making the best case worse
- Francis
*/
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
DataRow[] folderRows = null, parentRow;
InventoryFolderBase parentFolder = null;
lock (ds)
{
/* Fetch the parent folder from the database to determine the agent ID.
* Then fetch all inventory folders for that agent from the agent ID.
*/
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "UUID = '" + parentID + "'";
parentRow = inventoryFolderTable.Select(selectExp); // Assume at most 1 result
if (parentRow.GetLength(0) >= 1) // No result means parent folder does not exist
{
parentFolder = buildFolder(parentRow[0]);
UUID agentID = parentFolder.Owner;
selectExp = "agentID = '" + agentID + "'";
folderRows = inventoryFolderTable.Select(selectExp);
}
if (folderRows != null && folderRows.GetLength(0) >= 1) // No result means parent folder does not exist
{ // or has no children
/* if we're querying the root folder, just return an unordered list of all folders in the user's
* inventory
*/
if (parentFolder.ParentID == UUID.Zero)
{
foreach (DataRow row in folderRows)
{
InventoryFolderBase curFolder = buildFolder(row);
if (curFolder.ID != parentID) // Return all folders except the parent folder of heirarchy
folders.Add(buildFolder(row));
}
} // If requesting root folder
/* else we are querying a non-root folder. We currently have a list of all of the user's folders,
* we must construct a list of all folders in the heirarchy below parentID.
* Our first step will be to construct a hash table of all folders, indexed by parent ID.
* Once we have constructed the hash table, we will do a breadth-first traversal on the tree using the
* hash table to find child folders.
*/
else
{ // Querying a non-root folder
// Build a hash table of all user's inventory folders, indexed by each folder's parent ID
Dictionary<UUID, List<InventoryFolderBase>> hashtable =
new Dictionary<UUID, List<InventoryFolderBase>>(folderRows.GetLength(0));
foreach (DataRow row in folderRows)
{
InventoryFolderBase curFolder = buildFolder(row);
if (curFolder.ParentID != UUID.Zero) // Discard root of tree - not needed
{
if (hashtable.ContainsKey(curFolder.ParentID))
{
// Current folder already has a sibling - append to sibling list
hashtable[curFolder.ParentID].Add(curFolder);
}
else
{
List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>();
siblingList.Add(curFolder);
// Current folder has no known (yet) siblings
hashtable.Add(curFolder.ParentID, siblingList);
}
}
} // For all inventory folders
// Note: Could release the ds lock here - we don't access folderRows or the database anymore.
// This is somewhat of a moot point as the callers of this function usually lock db anyways.
if (hashtable.ContainsKey(parentID)) // if requested folder does have children
folders.AddRange(hashtable[parentID]);
// BreadthFirstSearch build inventory tree **Note: folders.Count is *not* static
for (int i = 0; i < folders.Count; i++)
if (hashtable.ContainsKey(folders[i].ID))
folders.AddRange(hashtable[folders[i].ID]);
} // if requesting a subfolder heirarchy
} // if folder parentID exists and has children
} // lock ds
return folders;
}
/// <summary>
/// Returns an inventory item by its UUID
/// </summary>
/// <param name="item">The UUID of the item to be returned</param>
/// <returns>A class containing item information</returns>
public InventoryItemBase getInventoryItem(UUID item)
{
lock (ds)
{
DataRow row = ds.Tables["inventoryitems"].Rows.Find(item.ToString());
if (row != null)
{
return buildItem(row);
}
else
{
return null;
}
}
}
/// <summary>
/// Returns a specified inventory folder by its UUID
/// </summary>
/// <param name="folder">The UUID of the folder to be returned</param>
/// <returns>A class containing folder information</returns>
public InventoryFolderBase getInventoryFolder(UUID folder)
{
// TODO: Deep voodoo here. If you enable this code then
// multi region breaks. No idea why, but I figured it was
// better to leave multi region at this point. It does mean
// that you don't get to see system textures why creating
// clothes and the like. :(
lock (ds)
{
DataRow row = ds.Tables["inventoryfolders"].Rows.Find(folder.ToString());
if (row != null)
{
return buildFolder(row);
}
else
{
return null;
}
}
}
/// <summary>
/// Creates a new inventory item based on item
/// </summary>
/// <param name="item">The item to be created</param>
public void addInventoryItem(InventoryItemBase item)
{
addItem(item, true);
}
/// <summary>
/// Updates an inventory item with item (updates based on ID)
/// </summary>
/// <param name="item">The updated item</param>
public void updateInventoryItem(InventoryItemBase item)
{
addItem(item, false);
}
/// <summary>
/// Delete an inventory item
/// </summary>
/// <param name="item">The item UUID</param>
public void deleteInventoryItem(UUID itemID)
{
lock (ds)
{
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
DataRow inventoryRow = inventoryItemTable.Rows.Find(itemID.ToString());
if (inventoryRow != null)
{
inventoryRow.Delete();
}
invItemsDa.Update(ds, "inventoryitems");
}
}
public InventoryItemBase queryInventoryItem(UUID itemID)
{
return getInventoryItem(itemID);
}
public InventoryFolderBase queryInventoryFolder(UUID folderID)
{
return getInventoryFolder(folderID);
}
/// <summary>
/// Delete all items in the specified folder
/// </summary>
/// <param name="folderId">id of the folder, whose item content should be deleted</param>
/// <todo>this is horribly inefficient, but I don't want to ruin the overall structure of this implementation</todo>
private void deleteItemsInFolder(UUID folderId)
{
List<InventoryItemBase> items = getInventoryInFolder(folderId);
foreach (InventoryItemBase i in items)
deleteInventoryItem(i.ID);
}
/// <summary>
/// Adds a new folder specified by folder
/// </summary>
/// <param name="folder">The inventory folder</param>
public void addInventoryFolder(InventoryFolderBase folder)
{
addFolder(folder, true);
}
/// <summary>
/// Updates a folder based on its ID with folder
/// </summary>
/// <param name="folder">The inventory folder</param>
public void updateInventoryFolder(InventoryFolderBase folder)
{
addFolder(folder, false);
}
/// <summary>
/// Moves a folder based on its ID with folder
/// </summary>
/// <param name="folder">The inventory folder</param>
public void moveInventoryFolder(InventoryFolderBase folder)
{
moveFolder(folder);
}
/// <summary>
/// Delete a folder
/// </summary>
/// <remarks>
/// This will clean-up any child folders and child items as well
/// </remarks>
/// <param name="folderID">the folder UUID</param>
public void deleteInventoryFolder(UUID folderID)
{
lock (ds)
{
List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID);
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow;
//Delete all sub-folders
foreach (InventoryFolderBase f in subFolders)
{
inventoryRow = inventoryFolderTable.Rows.Find(f.ID.ToString());
if (inventoryRow != null)
{
deleteItemsInFolder(f.ID);
inventoryRow.Delete();
}
}
//Delete the actual row
inventoryRow = inventoryFolderTable.Rows.Find(folderID.ToString());
if (inventoryRow != null)
{
deleteItemsInFolder(folderID);
inventoryRow.Delete();
}
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/***********************************************************************
*
* Data Table definitions
*
**********************************************************************/
protected void CreateDataSetMapping(IDataAdapter da, string tableName)
{
ITableMapping dbMapping = da.TableMappings.Add(tableName, tableName);
foreach (DataColumn col in ds.Tables[tableName].Columns)
{
dbMapping.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
}
/// <summary>
/// Create the "inventoryitems" table
/// </summary>
private static DataTable createInventoryItemsTable()
{
DataTable inv = new DataTable("inventoryitems");
createCol(inv, "UUID", typeof (String)); //inventoryID
createCol(inv, "assetID", typeof (String));
createCol(inv, "assetType", typeof (Int32));
createCol(inv, "invType", typeof (Int32));
createCol(inv, "parentFolderID", typeof (String));
createCol(inv, "avatarID", typeof (String));
createCol(inv, "creatorsID", typeof (String));
createCol(inv, "inventoryName", typeof (String));
createCol(inv, "inventoryDescription", typeof (String));
// permissions
createCol(inv, "inventoryNextPermissions", typeof (Int32));
createCol(inv, "inventoryCurrentPermissions", typeof (Int32));
createCol(inv, "inventoryBasePermissions", typeof (Int32));
createCol(inv, "inventoryEveryOnePermissions", typeof (Int32));
createCol(inv, "inventoryGroupPermissions", typeof (Int32));
// sale info
createCol(inv, "salePrice", typeof(Int32));
createCol(inv, "saleType", typeof(Byte));
// creation date
createCol(inv, "creationDate", typeof(Int32));
// group info
createCol(inv, "groupID", typeof(String));
createCol(inv, "groupOwned", typeof(Boolean));
// Flags
createCol(inv, "flags", typeof(UInt32));
inv.PrimaryKey = new DataColumn[] { inv.Columns["UUID"] };
return inv;
}
/// <summary>
/// Creates the "inventoryfolders" table
/// </summary>
/// <returns></returns>
private static DataTable createInventoryFoldersTable()
{
DataTable fol = new DataTable("inventoryfolders");
createCol(fol, "UUID", typeof (String)); //folderID
createCol(fol, "name", typeof (String));
createCol(fol, "agentID", typeof (String));
createCol(fol, "parentID", typeof (String));
createCol(fol, "type", typeof (Int32));
createCol(fol, "version", typeof (Int32));
fol.PrimaryKey = new DataColumn[] {fol.Columns["UUID"]};
return fol;
}
/// <summary>
///
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn)
{
lock (ds)
{
da.InsertCommand = createInsertCommand("inventoryitems", ds.Tables["inventoryitems"]);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("inventoryitems", "UUID=:UUID", ds.Tables["inventoryitems"]);
da.UpdateCommand.Connection = conn;
SqliteCommand delete = new SqliteCommand("delete from inventoryitems where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}
}
/// <summary>
///
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupFoldersCommands(SqliteDataAdapter da, SqliteConnection conn)
{
lock (ds)
{
da.InsertCommand = createInsertCommand("inventoryfolders", ds.Tables["inventoryfolders"]);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("inventoryfolders", "UUID=:UUID", ds.Tables["inventoryfolders"]);
da.UpdateCommand.Connection = conn;
SqliteCommand delete = new SqliteCommand("delete from inventoryfolders where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
private static InventoryFolderBase buildFolder(DataRow row)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = new UUID((string) row["UUID"]);
folder.Name = (string) row["name"];
folder.Owner = new UUID((string) row["agentID"]);
folder.ParentID = new UUID((string) row["parentID"]);
folder.Type = Convert.ToInt16(row["type"]);
folder.Version = Convert.ToUInt16(row["version"]);
return folder;
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <param name="folder"></param>
private static void fillFolderRow(DataRow row, InventoryFolderBase folder)
{
row["UUID"] = folder.ID.ToString();
row["name"] = folder.Name;
row["agentID"] = folder.Owner.ToString();
row["parentID"] = folder.ParentID.ToString();
row["type"] = folder.Type;
row["version"] = folder.Version;
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <param name="folder"></param>
private static void moveFolderRow(DataRow row, InventoryFolderBase folder)
{
row["UUID"] = folder.ID.ToString();
row["parentID"] = folder.ParentID.ToString();
}
public List<InventoryItemBase> fetchActiveGestures (UUID avatarID)
{
lock (ds)
{
List<InventoryItemBase> items = new List<InventoryItemBase>();
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
string selectExp
= "avatarID = '" + avatarID + "' AND assetType = " + (int)AssetType.Gesture + " AND flags = 1";
//m_log.DebugFormat("[SQL]: sql = " + selectExp);
DataRow[] rows = inventoryItemTable.Select(selectExp);
foreach (DataRow row in rows)
{
items.Add(buildItem(row));
}
return items;
}
}
}
}
| |
// 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.IO;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Xml.Schema;
using System.ComponentModel;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml.Extensions;
using XmlSchema = System.ServiceModel.Dispatcher.XmlSchemaConstants;
///<internalonly/>
public abstract class XmlSerializationWriter : XmlSerializationGeneratedCode
{
private XmlWriter _w;
private XmlSerializerNamespaces _namespaces;
private int _tempNamespacePrefix;
private HashSet<int> _usedPrefixes;
private HashSet<object> _objectsInUse;
private string _aliasBase = "q";
private bool _escapeName = true;
// this method must be called before any generated serialization methods are called
internal void Init(XmlWriter w, XmlSerializerNamespaces namespaces, string encodingStyle, string idBase)
{
_w = w;
_namespaces = namespaces;
}
// this method must be called before any generated serialization methods are called
internal void Init(XmlWriter w, XmlSerializerNamespaces namespaces, string encodingStyle, string idBase, TempAssembly tempAssembly)
{
Init(w, namespaces, encodingStyle, idBase);
Init(tempAssembly);
}
protected bool EscapeName
{
get
{
return _escapeName;
}
set
{
_escapeName = value;
}
}
protected XmlWriter Writer
{
get
{
return _w;
}
set
{
_w = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected IList XmlNamespaces
{
get
{
return _namespaces == null ? null : _namespaces.NamespaceList;
}
set
{
if (value == null)
{
_namespaces = null;
}
else
{
Array array = Array.CreateInstance(typeof(XmlQualifiedName), value.Count);
value.CopyTo(array, 0);
XmlQualifiedName[] qnames = (XmlQualifiedName[])array;
_namespaces = new XmlSerializerNamespaces(qnames);
}
}
}
protected static byte[] FromByteArrayBase64(byte[] value)
{
// Unlike other "From" functions that one is just a place holder for automatic code generation.
// The reason is performance and memory consumption for (potentially) big 64base-encoded chunks
// And it is assumed that the caller generates the code that will distinguish between byte[] and string return types
//
return value;
}
protected static string FromByteArrayHex(byte[] value)
{
return XmlCustomFormatter.FromByteArrayHex(value);
}
protected static string FromDateTime(DateTime value)
{
return XmlCustomFormatter.FromDateTime(value);
}
protected static string FromDate(DateTime value)
{
return XmlCustomFormatter.FromDate(value);
}
protected static string FromTime(DateTime value)
{
return XmlCustomFormatter.FromTime(value);
}
protected static string FromChar(char value)
{
return XmlCustomFormatter.FromChar(value);
}
protected static string FromEnum(long value, string[] values, long[] ids)
{
return XmlCustomFormatter.FromEnum(value, values, ids, null);
}
protected static string FromEnum(long value, string[] values, long[] ids, string typeName)
{
return XmlCustomFormatter.FromEnum(value, values, ids, typeName);
}
protected static string FromXmlName(string name)
{
return XmlCustomFormatter.FromXmlName(name);
}
protected static string FromXmlNCName(string ncName)
{
return XmlCustomFormatter.FromXmlNCName(ncName);
}
protected static string FromXmlNmToken(string nmToken)
{
return XmlCustomFormatter.FromXmlNmToken(nmToken);
}
protected static string FromXmlNmTokens(string nmTokens)
{
return XmlCustomFormatter.FromXmlNmTokens(nmTokens);
}
protected void WriteXsiType(string name, string ns)
{
WriteAttribute("type", XmlSchema.InstanceNamespace, GetQualifiedName(name, ns));
}
private XmlQualifiedName GetPrimitiveTypeName(Type type)
{
return GetPrimitiveTypeName(type, true);
}
private XmlQualifiedName GetPrimitiveTypeName(Type type, bool throwIfUnknown)
{
XmlQualifiedName qname = GetPrimitiveTypeNameInternal(type);
if (throwIfUnknown && qname == null)
throw CreateUnknownTypeException(type);
return qname;
}
internal static XmlQualifiedName GetPrimitiveTypeNameInternal(Type type)
{
string typeName;
string typeNs = XmlSchema.Namespace;
switch (type.GetTypeCode())
{
case TypeCode.String: typeName = "string"; break;
case TypeCode.Int32: typeName = "int"; break;
case TypeCode.Boolean: typeName = "boolean"; break;
case TypeCode.Int16: typeName = "short"; break;
case TypeCode.Int64: typeName = "long"; break;
case TypeCode.Single: typeName = "float"; break;
case TypeCode.Double: typeName = "double"; break;
case TypeCode.Decimal: typeName = "decimal"; break;
case TypeCode.DateTime: typeName = "dateTime"; break;
case TypeCode.Byte: typeName = "unsignedByte"; break;
case TypeCode.SByte: typeName = "byte"; break;
case TypeCode.UInt16: typeName = "unsignedShort"; break;
case TypeCode.UInt32: typeName = "unsignedInt"; break;
case TypeCode.UInt64: typeName = "unsignedLong"; break;
case TypeCode.Char:
typeName = "char";
typeNs = UrtTypes.Namespace;
break;
default:
if (type == typeof(XmlQualifiedName)) typeName = "QName";
else if (type == typeof(byte[])) typeName = "base64Binary";
else if (type == typeof(Guid))
{
typeName = "guid";
typeNs = UrtTypes.Namespace;
}
else if (type == typeof (TimeSpan))
{
typeName = "TimeSpan";
typeNs = UrtTypes.Namespace;
}
else if (type == typeof (XmlNode[]))
{
typeName = Soap.UrType;
}
else
return null;
break;
}
return new XmlQualifiedName(typeName, typeNs);
}
protected void WriteTypedPrimitive(string name, string ns, object o, bool xsiType)
{
string value = null;
string type;
string typeNs = XmlSchema.Namespace;
bool writeRaw = true;
bool writeDirect = false;
Type t = o.GetType();
bool wroteStartElement = false;
switch (t.GetTypeCode())
{
case TypeCode.String:
value = (string)o;
type = "string";
writeRaw = false;
break;
case TypeCode.Int32:
value = XmlConvert.ToString((int)o);
type = "int";
break;
case TypeCode.Boolean:
value = XmlConvert.ToString((bool)o);
type = "boolean";
break;
case TypeCode.Int16:
value = XmlConvert.ToString((short)o);
type = "short";
break;
case TypeCode.Int64:
value = XmlConvert.ToString((long)o);
type = "long";
break;
case TypeCode.Single:
value = XmlConvert.ToString((float)o);
type = "float";
break;
case TypeCode.Double:
value = XmlConvert.ToString((double)o);
type = "double";
break;
case TypeCode.Decimal:
value = XmlConvert.ToString((decimal)o);
type = "decimal";
break;
case TypeCode.DateTime:
value = FromDateTime((DateTime)o);
type = "dateTime";
break;
case TypeCode.Char:
value = FromChar((char)o);
type = "char";
typeNs = UrtTypes.Namespace;
break;
case TypeCode.Byte:
value = XmlConvert.ToString((byte)o);
type = "unsignedByte";
break;
case TypeCode.SByte:
value = XmlConvert.ToString((sbyte)o);
type = "byte";
break;
case TypeCode.UInt16:
value = XmlConvert.ToString((UInt16)o);
type = "unsignedShort";
break;
case TypeCode.UInt32:
value = XmlConvert.ToString((UInt32)o);
type = "unsignedInt";
break;
case TypeCode.UInt64:
value = XmlConvert.ToString((UInt64)o);
type = "unsignedLong";
break;
default:
if (t == typeof(XmlQualifiedName))
{
type = "QName";
// need to write start element ahead of time to establish context
// for ns definitions by FromXmlQualifiedName
wroteStartElement = true;
if (name == null)
_w.WriteStartElement(type, typeNs);
else
_w.WriteStartElement(name, ns);
value = FromXmlQualifiedName((XmlQualifiedName)o, false);
}
else if (t == typeof(byte[]))
{
value = String.Empty;
writeDirect = true;
type = "base64Binary";
}
else if (t == typeof(Guid))
{
value = XmlConvert.ToString((Guid)o);
type = "guid";
typeNs = UrtTypes.Namespace;
}
else if (t == typeof(TimeSpan))
{
value = XmlConvert.ToString((TimeSpan)o);
type = "TimeSpan";
typeNs = UrtTypes.Namespace;
}
else if (typeof(XmlNode[]).IsAssignableFrom(t))
{
if (name == null)
_w.WriteStartElement(Soap.UrType, XmlSchema.Namespace);
else
_w.WriteStartElement(name, ns);
XmlNode[] xmlNodes = (XmlNode[])o;
for (int i = 0; i < xmlNodes.Length; i++)
{
if (xmlNodes[i] == null)
continue;
xmlNodes[i].WriteTo(_w);
}
_w.WriteEndElement();
return;
}
else
throw CreateUnknownTypeException(t);
break;
}
if (!wroteStartElement)
{
if (name == null)
_w.WriteStartElement(type, typeNs);
else
_w.WriteStartElement(name, ns);
}
if (xsiType) WriteXsiType(type, typeNs);
if (value == null)
{
_w.WriteAttributeString("nil", XmlSchema.InstanceNamespace, "true");
}
else if (writeDirect)
{
// only one type currently writes directly to XML stream
XmlCustomFormatter.WriteArrayBase64(_w, (byte[])o, 0, ((byte[])o).Length);
}
else if (writeRaw)
{
_w.WriteRaw(value);
}
else
_w.WriteString(value);
_w.WriteEndElement();
}
private string GetQualifiedName(string name, string ns)
{
if (ns == null || ns.Length == 0) return name;
string prefix = _w.LookupPrefix(ns);
if (prefix == null)
{
if (ns == XmlReservedNs.NsXml)
{
prefix = "xml";
}
else
{
prefix = NextPrefix();
WriteAttribute("xmlns", prefix, null, ns);
}
}
else if (prefix.Length == 0)
{
return name;
}
return prefix + ":" + name;
}
protected string FromXmlQualifiedName(XmlQualifiedName xmlQualifiedName)
{
return FromXmlQualifiedName(xmlQualifiedName, true);
}
protected string FromXmlQualifiedName(XmlQualifiedName xmlQualifiedName, bool ignoreEmpty)
{
if (xmlQualifiedName == null) return null;
if (xmlQualifiedName.IsEmpty && ignoreEmpty) return null;
return GetQualifiedName(EscapeName ? XmlConvert.EncodeLocalName(xmlQualifiedName.Name) : xmlQualifiedName.Name, xmlQualifiedName.Namespace);
}
protected void WriteStartElement(string name)
{
WriteStartElement(name, null, null, false, null);
}
protected void WriteStartElement(string name, string ns)
{
WriteStartElement(name, ns, null, false, null);
}
protected void WriteStartElement(string name, string ns, bool writePrefixed)
{
WriteStartElement(name, ns, null, writePrefixed, null);
}
protected void WriteStartElement(string name, string ns, object o)
{
WriteStartElement(name, ns, o, false, null);
}
protected void WriteStartElement(string name, string ns, object o, bool writePrefixed)
{
WriteStartElement(name, ns, o, writePrefixed, null);
}
protected void WriteStartElement(string name, string ns, object o, bool writePrefixed, XmlSerializerNamespaces xmlns)
{
if (o != null && _objectsInUse != null)
{
if (!_objectsInUse.Add(o))
throw new InvalidOperationException(SR.Format(SR.XmlCircularReference, o.GetType().FullName));
}
string prefix = null;
bool needEmptyDefaultNamespace = false;
if (_namespaces != null)
{
foreach (string alias in _namespaces.Namespaces.Keys)
{
string aliasNs = (string)_namespaces.Namespaces[alias];
if (alias.Length > 0 && aliasNs == ns)
prefix = alias;
if (alias.Length == 0)
{
if (aliasNs == null || aliasNs.Length == 0)
needEmptyDefaultNamespace = true;
if (ns != aliasNs)
writePrefixed = true;
}
}
_usedPrefixes = ListUsedPrefixes(_namespaces.Namespaces, _aliasBase);
}
if (writePrefixed && prefix == null && ns != null && ns.Length > 0)
{
prefix = _w.LookupPrefix(ns);
if (prefix == null || prefix.Length == 0)
{
prefix = NextPrefix();
}
}
if (prefix == null && xmlns != null)
{
prefix = xmlns.LookupPrefix(ns);
}
if (needEmptyDefaultNamespace && prefix == null && ns != null && ns.Length != 0)
prefix = NextPrefix();
_w.WriteStartElement(prefix, name, ns);
if (_namespaces != null)
{
foreach (string alias in _namespaces.Namespaces.Keys)
{
string aliasNs = (string)_namespaces.Namespaces[alias];
if (alias.Length == 0 && (aliasNs == null || aliasNs.Length == 0))
continue;
if (aliasNs == null || aliasNs.Length == 0)
{
if (alias.Length > 0)
throw new InvalidOperationException(SR.Format(SR.XmlInvalidXmlns, alias));
WriteAttribute("xmlns", alias, null, aliasNs);
}
else
{
if (_w.LookupPrefix(aliasNs) == null)
{
// write the default namespace declaration only if we have not written it already, over wise we just ignore one provided by the user
if (prefix == null && alias.Length == 0)
break;
WriteAttribute("xmlns", alias, null, aliasNs);
}
}
}
}
WriteNamespaceDeclarations(xmlns);
}
private HashSet<int> ListUsedPrefixes(Dictionary<string, string> nsList, string prefix)
{
var qnIndexes = new HashSet<int>();
int prefixLength = prefix.Length;
const string MaxInt32 = "2147483647";
foreach (string alias in _namespaces.Namespaces.Keys)
{
string name;
if (alias.Length > prefixLength)
{
name = alias;
if (name.Length > prefixLength && name.Length <= prefixLength + MaxInt32.Length && name.StartsWith(prefix, StringComparison.Ordinal))
{
bool numeric = true;
for (int j = prefixLength; j < name.Length; j++)
{
if (!Char.IsDigit(name, j))
{
numeric = false;
break;
}
}
if (numeric)
{
Int64 index = Int64.Parse(name.Substring(prefixLength), NumberStyles.Integer, CultureInfo.InvariantCulture);
if (index <= Int32.MaxValue)
{
Int32 newIndex = (Int32)index;
qnIndexes.Add(newIndex);
}
}
}
}
}
if (qnIndexes.Count > 0)
{
return qnIndexes;
}
return null;
}
protected void WriteNullTagEncoded(string name)
{
WriteNullTagEncoded(name, null);
}
protected void WriteNullTagEncoded(string name, string ns)
{
if (name == null || name.Length == 0)
return;
WriteStartElement(name, ns, null, true);
_w.WriteAttributeString("nil", XmlSchema.InstanceNamespace, "true");
_w.WriteEndElement();
}
protected void WriteNullTagLiteral(string name)
{
WriteNullTagLiteral(name, null);
}
protected void WriteNullTagLiteral(string name, string ns)
{
if (name == null || name.Length == 0)
return;
WriteStartElement(name, ns, null, false);
_w.WriteAttributeString("nil", XmlSchema.InstanceNamespace, "true");
_w.WriteEndElement();
}
protected void WriteEmptyTag(string name)
{
WriteEmptyTag(name, null);
}
protected void WriteEmptyTag(string name, string ns)
{
if (name == null || name.Length == 0)
return;
WriteStartElement(name, ns, null, false);
_w.WriteEndElement();
}
protected void WriteEndElement()
{
_w.WriteEndElement();
}
protected void WriteEndElement(object o)
{
_w.WriteEndElement();
if (o != null && _objectsInUse != null)
{
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
if (!_objectsInUse.Contains(o)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "missing stack object of type " + o.GetType().FullName));
#endif
_objectsInUse.Remove(o);
}
}
protected void WriteSerializable(IXmlSerializable serializable, string name, string ns, bool isNullable)
{
WriteSerializable(serializable, name, ns, isNullable, true);
}
protected void WriteSerializable(IXmlSerializable serializable, string name, string ns, bool isNullable, bool wrapped)
{
if (serializable == null)
{
if (isNullable) WriteNullTagLiteral(name, ns);
return;
}
if (wrapped)
{
_w.WriteStartElement(name, ns);
}
serializable.WriteXml(_w);
if (wrapped)
{
_w.WriteEndElement();
}
}
protected void WriteNullableStringEncoded(string name, string ns, string value, XmlQualifiedName xsiType)
{
if (value == null)
WriteNullTagEncoded(name, ns);
else
WriteElementString(name, ns, value, xsiType);
}
protected void WriteNullableStringLiteral(string name, string ns, string value)
{
if (value == null)
WriteNullTagLiteral(name, ns);
else
WriteElementString(name, ns, value, null);
}
protected void WriteNullableStringEncodedRaw(string name, string ns, string value, XmlQualifiedName xsiType)
{
if (value == null)
WriteNullTagEncoded(name, ns);
else
WriteElementStringRaw(name, ns, value, xsiType);
}
protected void WriteNullableStringEncodedRaw(string name, string ns, byte[] value, XmlQualifiedName xsiType)
{
if (value == null)
WriteNullTagEncoded(name, ns);
else
WriteElementStringRaw(name, ns, value, xsiType);
}
protected void WriteNullableStringLiteralRaw(string name, string ns, string value)
{
if (value == null)
WriteNullTagLiteral(name, ns);
else
WriteElementStringRaw(name, ns, value, null);
}
protected void WriteNullableStringLiteralRaw(string name, string ns, byte[] value)
{
if (value == null)
WriteNullTagLiteral(name, ns);
else
WriteElementStringRaw(name, ns, value, null);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected void WriteNullableQualifiedNameEncoded(string name, string ns, XmlQualifiedName value, XmlQualifiedName xsiType)
{
if (value == null)
WriteNullTagEncoded(name, ns);
else
WriteElementQualifiedName(name, ns, value, xsiType);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected void WriteNullableQualifiedNameLiteral(string name, string ns, XmlQualifiedName value)
{
if (value == null)
WriteNullTagLiteral(name, ns);
else
WriteElementQualifiedName(name, ns, value, null);
}
protected void WriteElementLiteral(XmlNode node, string name, string ns, bool isNullable, bool any)
{
if (node == null)
{
if (isNullable) WriteNullTagLiteral(name, ns);
return;
}
WriteElement(node, name, ns, isNullable, any);
}
private void WriteElement(XmlNode node, string name, string ns, bool isNullable, bool any)
{
if (typeof(XmlAttribute).IsAssignableFrom(node.GetType()))
throw new InvalidOperationException(SR.XmlNoAttributeHere);
if (node is XmlDocument)
{
node = ((XmlDocument)node).DocumentElement;
if (node == null)
{
if (isNullable) WriteNullTagEncoded(name, ns);
return;
}
}
if (any)
{
if (node is XmlElement && name != null && name.Length > 0)
{
// need to check against schema
if (node.LocalName != name || node.NamespaceURI != ns)
throw new InvalidOperationException(SR.Format(SR.XmlElementNameMismatch, node.LocalName, node.NamespaceURI, name, ns));
}
}
else
_w.WriteStartElement(name, ns);
node.WriteTo(_w);
if (!any)
_w.WriteEndElement();
}
protected Exception CreateUnknownTypeException(object o)
{
return CreateUnknownTypeException(o.GetType());
}
protected Exception CreateUnknownTypeException(Type type)
{
if (typeof(IXmlSerializable).IsAssignableFrom(type)) return new InvalidOperationException(SR.Format(SR.XmlInvalidSerializable, type.FullName));
TypeDesc typeDesc = new TypeScope().GetTypeDesc(type);
if (!typeDesc.IsStructLike) return new InvalidOperationException(SR.Format(SR.XmlInvalidUseOfType, type.FullName));
return new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, type.FullName));
}
protected Exception CreateMismatchChoiceException(string value, string elementName, string enumValue)
{
// Value of {0} mismatches the type of {1}, you need to set it to {2}.
return new InvalidOperationException(SR.Format(SR.XmlChoiceMismatchChoiceException, elementName, value, enumValue));
}
protected Exception CreateUnknownAnyElementException(string name, string ns)
{
return new InvalidOperationException(SR.Format(SR.XmlUnknownAnyElement, name, ns));
}
protected Exception CreateInvalidChoiceIdentifierValueException(string type, string identifier)
{
return new InvalidOperationException(SR.Format(SR.XmlInvalidChoiceIdentifierValue, type, identifier));
}
protected Exception CreateChoiceIdentifierValueException(string value, string identifier, string name, string ns)
{
// XmlChoiceIdentifierMismatch=Value '{0}' of the choice identifier '{1}' does not match element '{2}' from namespace '{3}'.
return new InvalidOperationException(SR.Format(SR.XmlChoiceIdentifierMismatch, value, identifier, name, ns));
}
protected Exception CreateInvalidEnumValueException(object value, string typeName)
{
return new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, value, typeName));
}
protected Exception CreateInvalidAnyTypeException(object o)
{
return CreateInvalidAnyTypeException(o.GetType());
}
protected Exception CreateInvalidAnyTypeException(Type type)
{
return new InvalidOperationException(SR.Format(SR.XmlIllegalAnyElement, type.FullName));
}
protected void WriteXmlAttribute(XmlNode node)
{
WriteXmlAttribute(node, null);
}
protected void WriteXmlAttribute(XmlNode node, object container)
{
XmlAttribute attr = node as XmlAttribute;
if (attr == null) throw new InvalidOperationException(SR.XmlNeedAttributeHere);
if (attr.Value != null)
{
if (attr.NamespaceURI == Wsdl.Namespace && attr.LocalName == Wsdl.ArrayType)
{
string dims;
XmlQualifiedName qname = TypeScope.ParseWsdlArrayType(attr.Value, out dims, (container is XmlSchemaObject) ? (XmlSchemaObject)container : null);
string value = FromXmlQualifiedName(qname, true) + dims;
//<xsd:attribute xmlns:q3="s0" wsdl:arrayType="q3:FoosBase[]" xmlns:q4="http://schemas.xmlsoap.org/soap/encoding/" ref="q4:arrayType" />
WriteAttribute(Wsdl.ArrayType, Wsdl.Namespace, value);
}
else
{
WriteAttribute(attr.Name, attr.NamespaceURI, attr.Value);
}
}
}
protected void WriteAttribute(string localName, string ns, string value)
{
if (value == null) return;
if (localName == "xmlns" || localName.StartsWith("xmlns:", StringComparison.Ordinal))
{
;
}
else
{
int colon = localName.IndexOf(':');
if (colon < 0)
{
if (ns == XmlReservedNs.NsXml)
{
string prefix = _w.LookupPrefix(ns);
if (prefix == null || prefix.Length == 0)
prefix = "xml";
_w.WriteAttributeString(prefix, localName, ns, value);
}
else
{
_w.WriteAttributeString(localName, ns, value);
}
}
else
{
string prefix = localName.Substring(0, colon);
_w.WriteAttributeString(prefix, localName.Substring(colon + 1), ns, value);
}
}
}
protected void WriteAttribute(string localName, string ns, byte[] value)
{
if (value == null) return;
if (localName == "xmlns" || localName.StartsWith("xmlns:", StringComparison.Ordinal))
{
;
}
else
{
int colon = localName.IndexOf(':');
if (colon < 0)
{
if (ns == XmlReservedNs.NsXml)
{
string prefix = _w.LookupPrefix(ns);
if (prefix == null || prefix.Length == 0)
prefix = "xml";
_w.WriteStartAttribute("xml", localName, ns);
}
else
{
_w.WriteStartAttribute(null, localName, ns);
}
}
else
{
string prefix = _w.LookupPrefix(ns);
_w.WriteStartAttribute(prefix, localName.Substring(colon + 1), ns);
}
XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length);
_w.WriteEndAttribute();
}
}
protected void WriteAttribute(string localName, string value)
{
if (value == null) return;
_w.WriteAttributeString(localName, null, value);
}
protected void WriteAttribute(string localName, byte[] value)
{
if (value == null) return;
_w.WriteStartAttribute(null, localName, (string)null);
XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length);
_w.WriteEndAttribute();
}
protected void WriteAttribute(string prefix, string localName, string ns, string value)
{
if (value == null) return;
_w.WriteAttributeString(prefix, localName, null, value);
}
protected void WriteValue(string value)
{
if (value == null) return;
_w.WriteString(value);
}
protected void WriteValue(byte[] value)
{
if (value == null) return;
XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length);
}
protected void WriteStartDocument()
{
if (_w.WriteState == WriteState.Start)
{
_w.WriteStartDocument();
}
}
protected void WriteElementString(String localName, String value)
{
WriteElementString(localName, null, value, null);
}
protected void WriteElementString(String localName, String ns, String value)
{
WriteElementString(localName, ns, value, null);
}
protected void WriteElementString(String localName, String value, XmlQualifiedName xsiType)
{
WriteElementString(localName, null, value, xsiType);
}
protected void WriteElementString(String localName, String ns, String value, XmlQualifiedName xsiType)
{
if (value == null) return;
if (xsiType == null)
_w.WriteElementString(localName, ns, value);
else
{
_w.WriteStartElement(localName, ns);
WriteXsiType(xsiType.Name, xsiType.Namespace);
_w.WriteString(value);
_w.WriteEndElement();
}
}
protected void WriteElementStringRaw(String localName, String value)
{
WriteElementStringRaw(localName, null, value, null);
}
protected void WriteElementStringRaw(String localName, byte[] value)
{
WriteElementStringRaw(localName, null, value, null);
}
protected void WriteElementStringRaw(String localName, String ns, String value)
{
WriteElementStringRaw(localName, ns, value, null);
}
protected void WriteElementStringRaw(String localName, String ns, byte[] value)
{
WriteElementStringRaw(localName, ns, value, null);
}
protected void WriteElementStringRaw(String localName, String value, XmlQualifiedName xsiType)
{
WriteElementStringRaw(localName, null, value, xsiType);
}
protected void WriteElementStringRaw(String localName, byte[] value, XmlQualifiedName xsiType)
{
WriteElementStringRaw(localName, null, value, xsiType);
}
protected void WriteElementStringRaw(String localName, String ns, String value, XmlQualifiedName xsiType)
{
if (value == null) return;
_w.WriteStartElement(localName, ns);
if (xsiType != null)
WriteXsiType(xsiType.Name, xsiType.Namespace);
_w.WriteRaw(value);
_w.WriteEndElement();
}
protected void WriteElementStringRaw(String localName, String ns, byte[] value, XmlQualifiedName xsiType)
{
if (value == null) return;
_w.WriteStartElement(localName, ns);
if (xsiType != null)
WriteXsiType(xsiType.Name, xsiType.Namespace);
XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length);
_w.WriteEndElement();
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected void WriteElementQualifiedName(String localName, XmlQualifiedName value)
{
WriteElementQualifiedName(localName, null, value, null);
}
protected void WriteElementQualifiedName(string localName, XmlQualifiedName value, XmlQualifiedName xsiType)
{
WriteElementQualifiedName(localName, null, value, xsiType);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected void WriteElementQualifiedName(String localName, String ns, XmlQualifiedName value)
{
WriteElementQualifiedName(localName, ns, value, null);
}
protected void WriteElementQualifiedName(string localName, string ns, XmlQualifiedName value, XmlQualifiedName xsiType)
{
if (value == null) return;
if (value.Namespace == null || value.Namespace.Length == 0)
{
WriteStartElement(localName, ns, null, true);
WriteAttribute("xmlns", "");
}
else
_w.WriteStartElement(localName, ns);
if (xsiType != null)
WriteXsiType(xsiType.Name, xsiType.Namespace);
_w.WriteString(FromXmlQualifiedName(value, false));
_w.WriteEndElement();
}
protected abstract void InitCallbacks();
protected void TopLevelElement()
{
_objectsInUse = new HashSet<object>();
}
///<internalonly/>
protected void WriteNamespaceDeclarations(XmlSerializerNamespaces xmlns)
{
if (xmlns != null)
{
foreach (KeyValuePair<string, string> entry in xmlns.Namespaces)
{
string prefix = (string)entry.Key;
string ns = (string)entry.Value;
if (_namespaces != null)
{
string oldNs = _namespaces.Namespaces[prefix] as string;
if (oldNs != null && oldNs != ns)
{
throw new InvalidOperationException(SR.Format(SR.XmlDuplicateNs, prefix, ns));
}
}
string oldPrefix = (ns == null || ns.Length == 0) ? null : Writer.LookupPrefix(ns);
if (oldPrefix == null || oldPrefix != prefix)
{
WriteAttribute("xmlns", prefix, null, ns);
}
}
}
_namespaces = null;
}
private string NextPrefix()
{
if (_usedPrefixes == null)
{
return _aliasBase + (++_tempNamespacePrefix);
}
while (_usedPrefixes.Contains(++_tempNamespacePrefix)) {; }
return _aliasBase + _tempNamespacePrefix;
}
}
///<internalonly/>
public delegate void XmlSerializationWriteCallback(object o);
}
| |
using UnityEngine;
using System.Collections;
public class TempTestingCancel : MonoBehaviour {
public bool isTweening = false;
public bool tweenOverride = false;
private LTDescr tween;
// Use this for initialization
void Start () {
tween = LeanTween.move(gameObject, transform.position + Vector3.one*3f, Random.Range(2,2) ).setRepeat(-1).setLoopClamp ();
}
public void Update () {
if(tween != null){
isTweening = LeanTween.isTweening(gameObject);
if(tweenOverride){
// this next line works
//tween.cancel();
// this one doesn't
LeanTween.cancel(gameObject);
}
}
}
}
public class TestingEverything : MonoBehaviour {
public GameObject cube1;
public GameObject cube2;
public GameObject cube3;
public GameObject cube4;
private bool eventGameObjectWasCalled = false, eventGeneralWasCalled = false;
private LTDescr lt1;
private LTDescr lt2;
private LTDescr lt3;
private LTDescr lt4;
private LTDescr[] groupTweens;
private GameObject[] groupGOs;
private int groupTweensCnt;
private int rotateRepeat;
private int rotateRepeatAngle;
void Start () {
LeanTest.timeout = 7f;
LeanTest.expected = 24;
LeanTween.init(3 + 1200);
// add a listener
LeanTween.addListener(cube1, 0, eventGameObjectCalled);
LeanTest.expect(LeanTween.isTweening() == false, "NOTHING TWEEENING AT BEGINNING" );
LeanTest.expect(LeanTween.isTweening(cube1) == false, "OBJECT NOT TWEEENING AT BEGINNING" );
// dispatch event that is received
LeanTween.dispatchEvent(0);
LeanTest.expect( eventGameObjectWasCalled, "EVENT GAMEOBJECT RECEIVED" );
// do not remove listener
LeanTest.expect(LeanTween.removeListener(cube2, 0, eventGameObjectCalled)==false, "EVENT GAMEOBJECT NOT REMOVED" );
// remove listener
LeanTest.expect(LeanTween.removeListener(cube1, 0, eventGameObjectCalled), "EVENT GAMEOBJECT REMOVED" );
// add a listener
LeanTween.addListener(1, eventGeneralCalled);
// dispatch event that is received
LeanTween.dispatchEvent(1);
LeanTest.expect( eventGeneralWasCalled, "EVENT ALL RECEIVED" );
// remove listener
LeanTest.expect( LeanTween.removeListener( 1, eventGeneralCalled), "EVENT ALL REMOVED" );
lt1 = LeanTween.move( cube1, new Vector3(3f,2f,0.5f), 1.1f );
LeanTween.move( cube2, new Vector3(-3f,-2f,-0.5f), 1.1f );
LeanTween.reset();
// ping pong
// rotateAround, Repeat, DestroyOnComplete
rotateRepeat = rotateRepeatAngle = 0;
LeanTween.rotateAround(cube3, Vector3.forward, 360f, 0.1f).setRepeat(3).setOnComplete(rotateRepeatFinished).setOnCompleteOnRepeat(true).setDestroyOnComplete(true);
LeanTween.delayedCall(0.1f*8f, rotateRepeatAllFinished);
// test all onUpdates and onCompletes are removed when tween is initialized
StartCoroutine( timeBasedTesting() );
}
IEnumerator timeBasedTesting(){
yield return new WaitForEndOfFrame();
yield return new WaitForEndOfFrame();
Time.timeScale = 0.25f;
float tweenTime = 0.2f;
float start = Time.realtimeSinceStartup;
bool onUpdateWasCalled = false;
LeanTween.moveX(cube1, -5f, tweenTime).setOnUpdate( (float val)=>{
onUpdateWasCalled = true;
}).setOnComplete( ()=>{
float end = Time.realtimeSinceStartup;
float diff = end - start;
LeanTest.expect( Mathf.Abs( tweenTime * (1f/Time.timeScale) - diff) < 0.05f, "SCALED TIMING DIFFERENCE", "expected to complete in roughly 0.8f but completed in "+diff );
LeanTest.expect( Mathf.Approximately(cube1.transform.position.x, -5f), "SCALED ENDING POSITION", "expected to end at -5f, but it ended at "+cube1.transform.position.x);
LeanTest.expect( onUpdateWasCalled, "ON UPDATE FIRED" );
});
yield return new WaitForSeconds(1.0f);
Time.timeScale = 1f;
// Groups of tweens testing
groupTweens = new LTDescr[ 1200 ];
groupGOs = new GameObject[ groupTweens.Length ];
groupTweensCnt = 0;
int descriptionMatchCount = 0;
for(int i = 0; i < groupTweens.Length; i++){
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
Destroy( cube.GetComponent( typeof(BoxCollider) ) as Component );
cube.transform.position = new Vector3(0,0,i*3);
cube.name = "c"+i;
groupGOs[i] = cube;
groupTweens[i] = LeanTween.move(cube, transform.position + Vector3.one*3f, 0.6f ).setOnComplete(groupTweenFinished);
if(LeanTween.description(groupTweens[i].id).trans==groupTweens[i].trans)
descriptionMatchCount++;
}
LeanTween.delayedCall(gameObject, 0.82f, groupTweensFinished);
LeanTest.expect( descriptionMatchCount==groupTweens.Length, "GROUP IDS MATCH" );
LeanTest.expect( LeanTween.maxSearch<=groupTweens.Length+5, "MAX SEARCH OPTIMIZED", "maxSearch:"+LeanTween.maxSearch );
LeanTest.expect( LeanTween.isTweening() == true, "SOMETHING IS TWEENING" );
// resume item before calling pause should continue item along it's way
float previousXlt4 = cube4.transform.position.x;
lt4 = LeanTween.moveX( cube4, 5.0f, 1.1f).setOnComplete( ()=>{
LeanTest.expect( cube4!=null && previousXlt4!=cube4.transform.position.x, "RESUME OUT OF ORDER", "cube4:"+cube4+" previousXlt4:"+previousXlt4+" cube4.transform.position.x:"+(cube4!=null ? cube4.transform.position.x : 0));
});
lt4.resume();
yield return new WaitForSeconds(0.1f);
int countBeforeCancel = LeanTween.tweensRunning;
lt1.cancel();
LeanTest.expect( countBeforeCancel==LeanTween.tweensRunning, "CANCEL AFTER RESET SHOULD FAIL", "expected "+countBeforeCancel+" but got "+LeanTween.tweensRunning);
LeanTween.cancel(cube2);
int tweenCount = 0;
for(int i = 0; i < groupTweens.Length; i++){
if(LeanTween.isTweening( groupGOs[i] ))
tweenCount++;
if(i%3==0)
LeanTween.pause( groupGOs[i] );
else if(i%3==1)
groupTweens[i].pause();
else
LeanTween.pause( groupTweens[i].id );
}
LeanTest.expect( tweenCount==groupTweens.Length, "GROUP ISTWEENING", "expected "+groupTweens.Length+" tweens but got "+tweenCount );
yield return new WaitForEndOfFrame();
tweenCount = 0;
for(int i = 0; i < groupTweens.Length; i++){
if(i%3==0)
LeanTween.resume( groupGOs[i] );
else if(i%3==1)
groupTweens[i].resume();
else
LeanTween.resume( groupTweens[i].id );
if(i%2==0 ? LeanTween.isTweening( groupTweens[i].id ) : LeanTween.isTweening( groupGOs[i] ) )
tweenCount++;
}
LeanTest.expect( tweenCount==groupTweens.Length, "GROUP RESUME" );
LeanTest.expect( LeanTween.isTweening(cube1)==false, "CANCEL TWEEN LTDESCR" );
LeanTest.expect( LeanTween.isTweening(cube2)==false, "CANCEL TWEEN LEANTWEEN" );
int ltCount = 0;
GameObject[] allGos = FindObjectsOfType(typeof(GameObject)) as GameObject[];
foreach (GameObject go in allGos) {
if(go.name == "~LeanTween")
ltCount++;
}
LeanTest.expect( ltCount==1, "RESET CORRECTLY CLEANS UP" );
}
void rotateRepeatFinished(){
if( Mathf.Abs(cube3.transform.eulerAngles.z)<0.0001f )
rotateRepeatAngle++;
rotateRepeat++;
}
void rotateRepeatAllFinished(){
LeanTest.expect( rotateRepeatAngle==3, "ROTATE AROUND MULTIPLE", "expected 3 times received "+rotateRepeatAngle+" times" );
LeanTest.expect( rotateRepeat==3, "ROTATE REPEAT" );
LeanTest.expect( cube3==null, "DESTROY ON COMPLETE", "cube3:"+cube3 );
}
void groupTweenFinished(){
groupTweensCnt++;
}
void groupTweensFinished(){
LeanTest.expect( groupTweensCnt==groupTweens.Length, "GROUP FINISH", "expected "+groupTweens.Length+" tweens but got "+groupTweensCnt);
}
void eventGameObjectCalled( LTEvent e ){
eventGameObjectWasCalled = true;
}
void eventGeneralCalled( LTEvent e ){
eventGeneralWasCalled = true;
}
}
| |
namespace Nancy.Tests.Unit.ViewEngines
{
using System.Collections.Generic;
using System.Linq;
using FakeItEasy;
using Nancy.Configuration;
using Nancy.ViewEngines;
using Xunit;
using Xunit.Extensions;
public class DefaultViewLocatorFixture
{
private readonly DefaultViewLocator viewLocator;
private readonly INancyEnvironment environment;
public DefaultViewLocatorFixture()
{
this.environment = new DefaultNancyEnvironment();
this.environment.AddValue(ViewConfiguration.Default);
this.viewLocator = this.CreateViewLocator();
}
[Fact]
public void Should_return_null_if_locate_view_is_invoked_with_null_view_name()
{
// Given
string viewName = null;
// When
var result = this.viewLocator.LocateView(viewName, null);
// Then
result.ShouldBeNull();
}
[Fact]
public void Should_return_null_if_locate_view_is_invoked_with_empty_view_name()
{
// Given
var viewName = string.Empty;
// When
var result = this.viewLocator.LocateView(viewName, null);
// Then
result.ShouldBeNull();
}
[Fact]
public void Should_locate_view_when_only_name_is_provided()
{
// Given
var expectedView = new ViewLocationResult(string.Empty, "index", string.Empty, () => null);
var locator = this.CreateViewLocator(expectedView);
// When
var result = locator.LocateView("index", null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Theory]
[InlineData("INDEX")]
[InlineData("InDEx")]
public void Should_ignore_case_when_locating_view_based_on_name(string viewName)
{
// Given
var expectedView = new ViewLocationResult(string.Empty, "index", string.Empty, () => null);
var locator = this.CreateViewLocator(expectedView);
// When
var result = locator.LocateView(viewName, null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Fact]
public void Should_throw_ambiguousviewsexception_when_locating_view_by_name_returns_multiple_results()
{
// Given
var expectedView1 = new ViewLocationResult(string.Empty, "index", string.Empty, () => null);
var expectedView2 = new ViewLocationResult(string.Empty, "index", string.Empty, () => null);
var locator = this.CreateViewLocator(expectedView1, expectedView2);
// When
var exception = Record.Exception(() => locator.LocateView("index", null));
// Then
exception.ShouldBeOfType<AmbiguousViewsException>();
}
[Fact]
public void Should_throw_ambiguousviewsexception_when_locating_view_by_name_and_multiple_views_share_the_same_name_and_location_but_different_extensions()
{
// Given
var expectedView1 = new ViewLocationResult(string.Empty, "index", "spark", () => null);
var expectedView2 = new ViewLocationResult(string.Empty, "index", "html", () => null);
var locator = this.CreateViewLocator(expectedView1, expectedView2);
// When
var exception = Record.Exception(() => locator.LocateView("index", null));
// Then
exception.ShouldBeOfType<AmbiguousViewsException>();
}
[Fact]
public void Should_set_message_on_ambiguousviewexception()
{
// Given
var expectedView1 = new ViewLocationResult(string.Empty, "index", "spark", () => null);
var expectedView2 = new ViewLocationResult(string.Empty, "index", "html", () => null);
var locator = this.CreateViewLocator(expectedView1, expectedView2);
const string expectedMessage = "This exception was thrown because multiple views were found. 2 view(s):\r\n\t/index.spark\r\n\t/index.html";
// When
var exception = Record.Exception(() => locator.LocateView("index", null));
// Then
exception.Message.ShouldEqual(expectedMessage);
}
[Fact]
public void Should_return_null_when_view_cannot_be_located_using_name()
{
// Given
var expectedView = new ViewLocationResult(string.Empty, "index", string.Empty, () => null);
var locator = this.CreateViewLocator(expectedView);
// When
var result = locator.LocateView("main", null);
// Then
result.ShouldBeNull();
}
[Fact]
public void Should_locate_view_when_name_and_extension_are_provided()
{
// Given
var expectedView = new ViewLocationResult(string.Empty, "index", "cshtml", () => null);
var locator = this.CreateViewLocator(expectedView);
// When
var result = locator.LocateView("index.cshtml", null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Theory]
[InlineData("INDEX.CSHTML")]
[InlineData("InDEx.csHTml")]
public void Should_ignore_case_when_locating_view_based_on_name_and_extension(string viewName)
{
// Given
var expectedView = new ViewLocationResult(string.Empty, "index", "cshtml", () => null);
var locator = this.CreateViewLocator(expectedView);
// When
var result = locator.LocateView(viewName, null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Fact]
public void Should_return_null_when_view_cannot_be_located_using_name_and_extension()
{
// Given
var expectedView = new ViewLocationResult(string.Empty, "index", "spark", () => null);
var locator = this.CreateViewLocator(expectedView);
// When
var result = locator.LocateView("index.cshtml", null);
// Then
result.ShouldBeNull();
}
[Fact]
public void Should_locate_view_when_name_extension_and_location_are_provided()
{
// Given
var expectedView = new ViewLocationResult("views/sub", "index", "cshtml", () => null);
var locator = this.CreateViewLocator(expectedView);
// When
var result = locator.LocateView("views/sub/index.cshtml", null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Theory]
[InlineData("VIEWS/SUB/INDEX.CSHTML")]
[InlineData("viEWS/sUb/InDEx.csHTml")]
public void Should_ignore_case_when_locating_view_based_on_name_extension_and_location(string viewName)
{
// Given
var expectedView = new ViewLocationResult("views/sub", "index", "cshtml", () => null);
var locator = this.CreateViewLocator(expectedView);
// When
var result = locator.LocateView(viewName, null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Fact]
public void Should_return_null_when_view_cannot_be_located_using_name_extension_and_location()
{
// Given
var expectedView = new ViewLocationResult("views/sub", "index", "spark", () => null);
var locator = this.CreateViewLocator(expectedView);
// When
var result = locator.LocateView("views/feature/index.cshtml", null);
// Then
result.ShouldBeNull();
}
[Fact]
public void Should_be_able_to_locate_view_by_name_when_two_views_with_same_name_exists_at_different_locations()
{
// Given
var expectedView = new ViewLocationResult("views/sub", "index", string.Empty, () => null);
var additionalView = new ViewLocationResult("views", "index", string.Empty, () => null);
var locator = this.CreateViewLocator(expectedView, additionalView);
// When
var result = locator.LocateView("views/sub/index", null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Fact]
public void Should_be_able_to_locate_view_by_name_and_extension_when_two_view_with_same_name_but_different_extensions_exists_in_the_same_location()
{
// Given
var expectedView = new ViewLocationResult("views", "index", "cshtml", () => null);
var additionalView = new ViewLocationResult("views", "index", "spark", () => null);
var locator = this.CreateViewLocator(expectedView, additionalView);
// When
var result = locator.LocateView("views/index.cshtml", null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Fact]
public void Should_be_able_to_locate_view_by_name_when_two_views_with_same_name_and_extension_exists_at_different_locations()
{
// Given
var expectedView = new ViewLocationResult("views/sub", "index", "cshtml", () => null);
var additionalView = new ViewLocationResult("views", "index", "spark", () => null);
var locator = this.CreateViewLocator(expectedView, additionalView);
// When
var result = locator.LocateView("views/sub/index.cshtml", null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Fact]
public void Should_be_able_to_locate_view_by_name_when_the_viewname_occures_in_the_location()
{
// Given
var expectedView = new ViewLocationResult( "views/hello", "hello", "cshtml", () => null );
//var additionalView = new ViewLocationResult( "views", "index", "spark", () => null );
var locator = this.CreateViewLocator(expectedView);
// When
var result = locator.LocateView( "views/hello/hello", null );
// Then
result.ShouldBeSameAs( expectedView );
}
[Fact]
public void Should_get_located_views_from_view_location_providers_with_available_extensions_when_created()
{
// Given
var viewEngine1 = A.Fake<IViewEngine>();
A.CallTo(() => viewEngine1.Extensions).Returns(new[] { "html" });
var viewEngine2 = A.Fake<IViewEngine>();
A.CallTo(() => viewEngine2.Extensions).Returns(new[] { "spark" });
var viewLocationProvider = A.Fake<IViewLocationProvider>();
var expectedViewEngineExtensions = new[] { "html", "spark" };
var viewEngine = A.Fake<IViewEngine>();
A.CallTo(() => viewEngine.Extensions).Returns(expectedViewEngineExtensions);
// When
new DefaultViewLocator(viewLocationProvider, new[] { viewEngine }, this.environment);
// Then
A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>.That.Matches(
x => x.All(expectedViewEngineExtensions.Contains)))).MustHaveHappened();
}
private DefaultViewLocator CreateViewLocator(params ViewLocationResult[] results)
{
var viewLocationProvider = A.Fake<IViewLocationProvider>();
A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>._))
.Returns(results);
var viewEngine = A.Fake<IViewEngine>();
A.CallTo(() => viewEngine.Extensions).Returns(new[] { "liquid" });
var viewLocator = new DefaultViewLocator(viewLocationProvider, new[] { viewEngine }, this.environment);
return viewLocator;
}
}
}
| |
/*
Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* All code is written my me,Ben Ratzlaff and is available for any free use except where noted.
*I assume no responsibility for how anyone uses the information available*/
//uncomment this line to have the program save the emitted assembly to Test.dll
//#define SaveDLL
using System;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Reflection.Emit;
using System.Threading;
using System.Reflection;
namespace CustomPropGrid
{
/// <summary>
/// A property grid that dynamically generates a Type to conform to desired input
/// </summary>
public class CustomPropertyGrid : System.Windows.Forms.PropertyGrid
{
private Hashtable typeHash;
private string typeName="DefType";
private Settings settings;
private bool instantUpdate=true;
public CustomPropertyGrid()
{
initTypes();
}
[Description("Name of the type that will be internally created")]
[DefaultValue("DefType")]
public string TypeName
{
get{return typeName;}
set{typeName=value;}
}
[DefaultValue(true)]
[Description("If true, the Setting.Update() event will be called when a property changes")]
public bool InstantUpdate
{
get{return instantUpdate;}
set{instantUpdate=value;}
}
protected override void OnPropertyValueChanged(PropertyValueChangedEventArgs e)
{
base.OnPropertyValueChanged(e);
((Setting)settings[e.ChangedItem.Label]).Value=e.ChangedItem.Value;
if(instantUpdate)
((Setting)settings[e.ChangedItem.Label]).FireUpdate(e);
}
[Browsable(false)]
public Settings Settings
{
set
{
settings=value;
//Reflection.Emit code below copied and modified from http://longhorn.msdn.microsoft.com/lhsdk/ref/ns/system.reflection.emit/c/propertybuilder/propertybuilder.aspx
AppDomain myDomain = Thread.GetDomain();
AssemblyName myAsmName = new AssemblyName();
myAsmName.Name = "TempAssembly";
//Only save the custom-type dll while debugging
#if SaveDLL && DEBUG
AssemblyBuilder assemblyBuilder = myDomain.DefineDynamicAssembly(myAsmName,AssemblyBuilderAccess.RunAndSave);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("TempModule","Test.dll");
#else
AssemblyBuilder assemblyBuilder = myDomain.DefineDynamicAssembly(myAsmName,AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("TempModule");
#endif
//create our type
TypeBuilder newType = moduleBuilder.DefineType(typeName, TypeAttributes.Public);
//create the hashtable used to store property values
FieldBuilder hashField = newType.DefineField("table",typeof(Hashtable),FieldAttributes.Private);
createHashMethod(newType.DefineProperty("Hash",PropertyAttributes.None,typeof(Hashtable),new Type[] {}),
newType,hashField);
Hashtable h = new Hashtable();
foreach(string key in settings.Keys)
{
Setting s = settings[key];
h[key]=s.Value;
emitProperty(newType,hashField,s,key);
}
Type myType = newType.CreateType();
#if SaveDLL && DEBUG
assemblyBuilder.Save("Test.dll");
#endif
ConstructorInfo ci = myType.GetConstructor(new Type[]{});
object o = ci.Invoke(new Object[]{});
//set the object's hashtable - in the future i would like to do this in the emitted object's constructor
PropertyInfo pi = myType.GetProperty("Hash");
pi.SetValue(o,h,null);
SelectedObject=o;
}
}
private void createHashMethod(PropertyBuilder propBuild,TypeBuilder typeBuild,FieldBuilder hash)
{
// First, we'll define the behavior of the "get" property for Hash as a method.
MethodBuilder typeHashGet = typeBuild.DefineMethod("GetHash",
MethodAttributes.Public,
typeof(Hashtable),
new Type[] { });
ILGenerator ilg = typeHashGet.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Ldfld, hash);
ilg.Emit(OpCodes.Ret);
// Now, we'll define the behavior of the "set" property for Hash.
MethodBuilder typeHashSet = typeBuild.DefineMethod("SetHash",
MethodAttributes.Public,
null,
new Type[] { typeof(Hashtable) });
ilg = typeHashSet.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Ldarg_1);
ilg.Emit(OpCodes.Stfld, hash);
ilg.Emit(OpCodes.Ret);
// map the two methods created above to their property
propBuild.SetGetMethod(typeHashGet);
propBuild.SetSetMethod(typeHashSet);
//add the [Browsable(false)] property to the Hash property so it doesnt show up on the property list
ConstructorInfo ci = typeof(BrowsableAttribute).GetConstructor(new Type[]{typeof(bool)});
CustomAttributeBuilder cab = new CustomAttributeBuilder(ci,new object[]{false});
propBuild.SetCustomAttribute(cab);
}
/// <summary>
/// Initialize a private hashtable with type-opCode pairs so i dont have to write a long if/else statement when outputting msil
/// </summary>
private void initTypes()
{
typeHash=new Hashtable();
typeHash[typeof(sbyte)]=OpCodes.Ldind_I1;
typeHash[typeof(byte)]=OpCodes.Ldind_U1;
typeHash[typeof(char)]=OpCodes.Ldind_U2;
typeHash[typeof(short)]=OpCodes.Ldind_I2;
typeHash[typeof(ushort)]=OpCodes.Ldind_U2;
typeHash[typeof(int)]=OpCodes.Ldind_I4;
typeHash[typeof(uint)]=OpCodes.Ldind_U4;
typeHash[typeof(long)]=OpCodes.Ldind_I8;
typeHash[typeof(ulong)]=OpCodes.Ldind_I8;
typeHash[typeof(bool)]=OpCodes.Ldind_I1;
typeHash[typeof(double)]=OpCodes.Ldind_R8;
typeHash[typeof(float)]=OpCodes.Ldind_R4;
}
/// <summary>
/// emits a generic get/set property in which the result returned resides in a hashtable whos key is the name of the property
/// </summary>
/// <param name="pb">PropertyBuilder used to emit</param>
/// <param name="tb">TypeBuilder of the class</param>
/// <param name="hash">FieldBuilder of the hashtable used to store the object</param>
/// <param name="po">PropertyObject of this property</param>
private void emitProperty(TypeBuilder tb,FieldBuilder hash,Setting s,string name)
{
//to figure out what opcodes to emit, i would compile a small class having the functionality i wanted, and viewed it with ildasm.
//peverify is also kinda nice to use to see what errors there are.
//define the property first
PropertyBuilder pb = tb.DefineProperty(name,PropertyAttributes.None,s.Value.GetType(),new Type[] {});
Type objType = s.Value.GetType();
//now we define the get method for the property
MethodBuilder getMethod = tb.DefineMethod("get_"+name,MethodAttributes.Public,objType,new Type[]{});
ILGenerator ilg = getMethod.GetILGenerator();
ilg.DeclareLocal(objType);
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Ldfld,hash);
ilg.Emit(OpCodes.Ldstr,name);
ilg.EmitCall(OpCodes.Callvirt,typeof(Hashtable).GetMethod("get_Item"),null);
if(objType.IsValueType)
{
ilg.Emit(OpCodes.Unbox,objType);
if(typeHash[objType]!=null)
ilg.Emit((OpCode)typeHash[objType]);
else
ilg.Emit(OpCodes.Ldobj,objType);
}
else
ilg.Emit(OpCodes.Castclass,objType);
ilg.Emit(OpCodes.Stloc_0);
ilg.Emit(OpCodes.Br_S,(byte)0);
ilg.Emit(OpCodes.Ldloc_0);
ilg.Emit(OpCodes.Ret);
//now we generate the set method for the property
MethodBuilder setMethod = tb.DefineMethod("set_"+name,MethodAttributes.Public,null,new Type[]{objType});
ilg = setMethod.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Ldfld,hash);
ilg.Emit(OpCodes.Ldstr,name);
ilg.Emit(OpCodes.Ldarg_1);
if(objType.IsValueType)
ilg.Emit(OpCodes.Box,objType);
ilg.EmitCall(OpCodes.Callvirt,typeof(Hashtable).GetMethod("set_Item"),null);
ilg.Emit(OpCodes.Ret);
//put the get/set methods in with the property
pb.SetGetMethod(getMethod);
pb.SetSetMethod(setMethod);
//if we specified a description, we will now add the DescriptionAttribute to our property
if(s.Description!=null)
{
ConstructorInfo ci = typeof(DescriptionAttribute).GetConstructor(new Type[]{typeof(string)});
CustomAttributeBuilder cab = new CustomAttributeBuilder(ci,new object[]{s.Description});
pb.SetCustomAttribute(cab);
}
//add a CategoryAttribute if specified
if(s.Category!=null)
{
ConstructorInfo ci = typeof(CategoryAttribute).GetConstructor(new Type[]{typeof(string)});
CustomAttributeBuilder cab = new CustomAttributeBuilder(ci,new object[]{s.Category});
pb.SetCustomAttribute(cab);
}
}
}
}
| |
// 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.Linq;
using System.Text;
using System.Threading;
using Gallio.Common;
using Gallio.Framework;
using Gallio.Common.Reflection;
using Gallio.Framework.Pattern;
using Gallio.Runner.Reports.Schema;
using Gallio.Tests;
using MbUnit.Framework;
namespace MbUnit.Tests.Framework
{
[TestFixture]
[TestsOn(typeof(ParallelizableAttribute))]
[RunSample(typeof(Tests))]
[Explicit("Tests are timing sensitive and fail periodically on the build server.")]
public class ParallelizableTest : BaseTestWithSampleRunner
{
private int originalDegreeOfParalleism;
[FixtureSetUp]
public void IncreaseDegreeOfParallelism()
{
originalDegreeOfParalleism = TestAssemblyExecutionParameters.DegreeOfParallelism;
TestAssemblyExecutionParameters.DegreeOfParallelism = 16;
}
[FixtureTearDown]
public void ResetDegreeOfParallelism()
{
TestAssemblyExecutionParameters.DegreeOfParallelism = originalDegreeOfParalleism;
}
[Test]
public void ParallelizedTests()
{
Assert.IsTrue(
WasParallel("One") || WasParallel("Two") || WasParallel("Three") || WasParallel("Four"),
"Expected at least one of the set of parallelizable tests to run in parallel with another one.");
Assert.IsTrue(
WasParallel("Seven") || WasParallel("Eight") || WasParallel("Nine") || WasParallel("Ten"),
"Expected at least one of the set of parallelizable tests to run in parallel with another one.");
Assert.IsFalse(
WasParallel("Five") || WasParallel("Six") || WasParallel("Eleven"),
"Expected none of the non-parallelizable tests to run in parallel with any other ones.");
Assert.IsFalse(
WasParallel("Twelve"),
"Expected the parallelizable but standalone to run on its own since there are no other tests of the same order.");
}
[Test]
public void ExplicitOrderingShouldHaveBeenPreserved()
{
Pair<DateTime, DateTime> batch1 = GetEarliestAndLatestStartAndEndTimes("One", "Two", "Three", "Four");
Pair<DateTime, DateTime> batch2 = GetEarliestAndLatestStartAndEndTimes("Five");
Pair<DateTime, DateTime> batch3 = GetEarliestAndLatestStartAndEndTimes("Six");
Pair<DateTime, DateTime> batch4 = GetEarliestAndLatestStartAndEndTimes("Seven", "Eight", "Nine", "Ten");
Pair<DateTime, DateTime> batch5 = GetEarliestAndLatestStartAndEndTimes("Eleven");
Pair<DateTime, DateTime> batch6 = GetEarliestAndLatestStartAndEndTimes("Twelve");
Assert.LessThanOrEqualTo(batch1.Second, batch2.First);
Assert.LessThanOrEqualTo(batch2.Second, batch3.First);
Assert.LessThanOrEqualTo(batch3.Second, batch4.First);
Assert.LessThanOrEqualTo(batch4.Second, batch5.First);
Assert.LessThanOrEqualTo(batch5.Second, batch6.First);
}
private Pair<DateTime, DateTime> GetEarliestAndLatestStartAndEndTimes(params string[] testNames)
{
DateTime startTime = DateTime.MaxValue;
DateTime endTime = DateTime.MinValue;
foreach (string testName in testNames)
{
TestStepRun run = GetTestStepRun(testName);
if (run.StartTime < startTime)
startTime = run.StartTime;
if (run.EndTime > endTime)
endTime = run.EndTime;
}
return new Pair<DateTime, DateTime>(startTime, endTime);
}
private bool WasParallel(string testName)
{
return GetTestStepRun(testName).TestLog.ToString().Contains("Detected a parallel");
}
private TestStepRun GetTestStepRun(string testName)
{
IList<TestStepRun> runs = Runner.GetTestCaseRunsWithin(
CodeReference.CreateFromMember(typeof(Tests).GetMethod(testName)));
Assert.AreEqual(1, runs.Count, "Different number of runs than expected.");
return runs[0];
}
[Explicit("Sample")]
public class Tests
{
private int counter;
[SetUp]
public void IncrementAndWriteCounterOnEntry()
{
int newCount = Interlocked.Increment(ref counter);
TestLog.WriteLine(newCount);
if (newCount != 1)
TestLog.WriteLine("Detected a parallel test during SetUp.");
}
[TearDown]
public void DecrementAndWriteCounterOnExit()
{
Thread.Sleep(500);
int newCount = Interlocked.Decrement(ref counter);
TestLog.WriteLine(newCount);
if (newCount != 0)
TestLog.WriteLine("Detected a parallel test during TearDown.");
}
[Test, Parallelizable]
public void One()
{
TestLog.WriteLine("One");
}
[Test, Parallelizable]
public void Two()
{
TestLog.WriteLine("Two");
}
[Test, Parallelizable]
public void Three()
{
TestLog.WriteLine("Three");
}
[Test, Parallelizable]
public void Four()
{
TestLog.WriteLine("Four");
}
[Test]
public void Five()
{
TestLog.WriteLine("Five");
}
[Test, DependsOn("Five")]
public void Six()
{
TestLog.WriteLine("Six");
}
[Test(Order=1), Parallelizable]
public void Seven()
{
TestLog.WriteLine("Seven");
}
[Test(Order=1), Parallelizable]
public void Eight()
{
TestLog.WriteLine("Eight");
}
[Test(Order = 1), Parallelizable]
public void Nine()
{
TestLog.WriteLine("Nine");
}
[Test(Order = 1), Parallelizable]
public void Ten()
{
TestLog.WriteLine("Ten");
}
[Test(Order = 1)]
public void Eleven()
{
TestLog.WriteLine("Eleven");
}
[Test(Order = 2), Parallelizable]
public void Twelve()
{
TestLog.WriteLine("Twelve");
}
}
[Explicit("Sample")]
public class NestedParallelizableTests
{
[Test]
public void Test()
{
}
[Parallelizable(TestScope.All)]
public class Fixture1
{
[Test]
public void Test1()
{
}
[Test]
public void Test2()
{
}
[Test]
[Column(1, 2, 3, 4, 5)]
public void DataDrivenTest(int x)
{
}
}
[Parallelizable(TestScope.All)]
public class Fixture2
{
[Test]
public void Test1()
{
}
[Test]
public void Test2()
{
}
[Test]
[Column(1, 2, 3, 4, 5)]
public void DataDrivenTest(int x)
{
}
}
}
}
}
| |
// 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.Reflection;
using System.Collections.Generic;
namespace Internal.Reflection.Extensions.NonPortable
{
public static class MemberEnumerator
{
//
// Enumerates members, optionally filtered by a name, in the given class and its base classes (but not implemented interfaces.)
// Basically emulates the old Type.GetFoo(BindingFlags) api.
//
public static IEnumerable<M> GetMembers<M>(this Type type, Object nameFilterOrAnyName, BindingFlags bindingFlags) where M : MemberInfo
{
// Do all the up-front argument validation here so that the exception occurs on call rather than on the first move.
if (type == null)
{
throw new ArgumentNullException();
}
if (nameFilterOrAnyName == null)
{
throw new ArgumentNullException();
}
String optionalNameFilter;
if (nameFilterOrAnyName == AnyName)
{
optionalNameFilter = null;
}
else
{
optionalNameFilter = (String)nameFilterOrAnyName;
}
return GetMembersWorker<M>(type, optionalNameFilter, bindingFlags);
}
//
// The iterator worker for GetMember<M>()
//
private static IEnumerable<M> GetMembersWorker<M>(Type type, String optionalNameFilter, BindingFlags bindingFlags) where M : MemberInfo
{
Type reflectedType = type;
Type typeOfM = typeof(M);
Type typeOfEventInfo = typeof(EventInfo);
MemberPolicies<M> policies = MemberPolicies<M>.Default;
bindingFlags = policies.ModifyBindingFlags(bindingFlags);
LowLevelList<M> overridingMembers = new LowLevelList<M>();
StringComparison comparisonType = (0 != (bindingFlags & BindingFlags.IgnoreCase)) ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
bool inBaseClass = false;
bool nameFilterIsPrefix = false;
if (optionalNameFilter != null && optionalNameFilter.EndsWith("*", StringComparison.Ordinal))
{
nameFilterIsPrefix = true;
optionalNameFilter = optionalNameFilter.Substring(0, optionalNameFilter.Length - 1);
}
while (type != null)
{
TypeInfo typeInfo = type.GetTypeInfo();
foreach (M member in policies.GetDeclaredMembers(typeInfo))
{
if (optionalNameFilter != null)
{
if (nameFilterIsPrefix)
{
if (!member.Name.StartsWith(optionalNameFilter, comparisonType))
{
continue;
}
}
else if (!member.Name.Equals(optionalNameFilter, comparisonType))
{
continue;
}
}
MethodAttributes visibility;
bool isStatic;
bool isVirtual;
bool isNewSlot;
policies.GetMemberAttributes(member, out visibility, out isStatic, out isVirtual, out isNewSlot);
BindingFlags memberBindingFlags = (BindingFlags)0;
memberBindingFlags |= (isStatic ? BindingFlags.Static : BindingFlags.Instance);
memberBindingFlags |= ((visibility == MethodAttributes.Public) ? BindingFlags.Public : BindingFlags.NonPublic);
if ((bindingFlags & memberBindingFlags) != memberBindingFlags)
{
continue;
}
bool passesVisibilityScreen = true;
if (inBaseClass && visibility == MethodAttributes.Private)
{
passesVisibilityScreen = false;
}
bool passesStaticScreen = true;
if (inBaseClass && isStatic && (0 == (bindingFlags & BindingFlags.FlattenHierarchy)))
{
passesStaticScreen = false;
}
//
// Desktop compat: The order in which we do checks is important.
//
if (!passesVisibilityScreen)
{
continue;
}
if ((!passesStaticScreen) && !(typeOfM.Equals(typeOfEventInfo)))
{
continue;
}
bool isImplicitlyOverridden = false;
if (isVirtual)
{
if (isNewSlot)
{
// A new virtual member definition.
for (int i = 0; i < overridingMembers.Count; i++)
{
if (policies.AreNamesAndSignatureEqual(member, overridingMembers[i]))
{
// This member is overridden by a more derived class.
isImplicitlyOverridden = true;
overridingMembers.RemoveAt(i);
break;
}
}
}
else
{
for (int i = 0; i < overridingMembers.Count; i++)
{
if (policies.AreNamesAndSignatureEqual(overridingMembers[i], member))
{
// This member overrides another, *and* is overridden by yet another method.
isImplicitlyOverridden = true;
break;
}
}
if (!isImplicitlyOverridden)
{
// This member overrides another and is the most derived instance of it we've found.
overridingMembers.Add(member);
}
}
}
if (isImplicitlyOverridden)
{
continue;
}
if (!passesStaticScreen)
{
continue;
}
if (inBaseClass)
{
yield return policies.GetInheritedMemberInfo(member, reflectedType);
}
else
{
yield return member;
}
}
if (0 != (bindingFlags & BindingFlags.DeclaredOnly))
{
break;
}
inBaseClass = true;
type = typeInfo.BaseType;
}
}
//
// If member is a virtual member that implicitly overrides a member in a base class, return the overridden member.
// Otherwise, return null.
//
// - MethodImpls ignored. (I didn't say it made sense, this is just how the desktop api we're porting behaves.)
// - Implemented interfaces ignores. (I didn't say it made sense, this is just how the desktop api we're porting behaves.)
//
public static M GetImplicitlyOverriddenBaseClassMember<M>(this M member) where M : MemberInfo
{
MemberPolicies<M> policies = MemberPolicies<M>.Default;
MethodAttributes visibility;
bool isStatic;
bool isVirtual;
bool isNewSlot;
policies.GetMemberAttributes(member, out visibility, out isStatic, out isVirtual, out isNewSlot);
if (isNewSlot || !isVirtual)
{
return null;
}
String name = member.Name;
TypeInfo typeInfo = member.DeclaringType.GetTypeInfo();
for (; ;)
{
Type baseType = typeInfo.BaseType;
if (baseType == null)
{
return null;
}
typeInfo = baseType.GetTypeInfo();
foreach (M candidate in policies.GetDeclaredMembers(typeInfo))
{
if (candidate.Name != name)
{
continue;
}
MethodAttributes candidateVisibility;
bool isCandidateStatic;
bool isCandidateVirtual;
bool isCandidateNewSlot;
policies.GetMemberAttributes(member, out candidateVisibility, out isCandidateStatic, out isCandidateVirtual, out isCandidateNewSlot);
if (!isCandidateVirtual)
{
continue;
}
if (!policies.AreNamesAndSignatureEqual(member, candidate))
{
continue;
}
return candidate;
}
}
}
// Uniquely allocated sentinel "string"
// - can't use null as that may be an app-supplied null, which we have to throw ArgumentNullException for.
// - risky to use a proper String as the FX or toolchain can unexpectedly give you back a shared string
// even when you'd swear you were allocating a new one.
public static readonly Object AnyName = new Object();
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.DynamicProxy.Contributors
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using Castle.DynamicProxy.Generators.Emitters;
using Castle.DynamicProxy.Generators.Emitters.CodeBuilders;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using Castle.DynamicProxy.Internal;
using Castle.DynamicProxy.Tokens;
public class ClassProxyInstanceContributor : ProxyInstanceContributor
{
#if !SILVERLIGHT
private readonly bool delegateToBaseGetObjectData;
private readonly bool implementISerializable;
private ConstructorInfo serializationConstructor;
private readonly IList<FieldReference> serializedFields = new List<FieldReference>();
#endif
public ClassProxyInstanceContributor(Type targetType, IList<MethodInfo> methodsToSkip, Type[] interfaces,
string typeId)
: base(targetType, interfaces, typeId)
{
#if !SILVERLIGHT
if (targetType.IsSerializable)
{
implementISerializable = true;
delegateToBaseGetObjectData = VerifyIfBaseImplementsGetObjectData(targetType, methodsToSkip);
}
#endif
}
protected override Expression GetTargetReferenceExpression(ClassEmitter emitter)
{
return SelfReference.Self.ToExpression();
}
public override void Generate(ClassEmitter @class, ProxyGenerationOptions options)
{
var interceptors = @class.GetField("__interceptors");
#if !SILVERLIGHT
if (implementISerializable)
{
ImplementGetObjectData(@class);
Constructor(@class);
}
#endif
ImplementProxyTargetAccessor(@class, interceptors);
foreach (var attribute in targetType.GetNonInheritableAttributes())
{
@class.DefineCustomAttribute(attribute);
}
}
#if !SILVERLIGHT
protected override void AddAddValueInvocation(ArgumentReference serializationInfo, MethodEmitter getObjectData,
FieldReference field)
{
serializedFields.Add(field);
base.AddAddValueInvocation(serializationInfo, getObjectData, field);
}
protected override void CustomizeGetObjectData(AbstractCodeBuilder codebuilder, ArgumentReference serializationInfo,
ArgumentReference streamingContext, ClassEmitter emitter)
{
codebuilder.AddStatement(new ExpressionStatement(
new MethodInvocationExpression(
serializationInfo,
SerializationInfoMethods.AddValue_Bool,
new ConstReference("__delegateToBase").ToExpression(),
new ConstReference(delegateToBaseGetObjectData).
ToExpression())));
if (delegateToBaseGetObjectData == false)
{
EmitCustomGetObjectData(codebuilder, serializationInfo);
return;
}
EmitCallToBaseGetObjectData(codebuilder, serializationInfo, streamingContext);
}
private void EmitCustomGetObjectData(AbstractCodeBuilder codebuilder, ArgumentReference serializationInfo)
{
var members = codebuilder.DeclareLocal(typeof(MemberInfo[]));
var data = codebuilder.DeclareLocal(typeof(object[]));
var getSerializableMembers = new MethodInvocationExpression(
null,
FormatterServicesMethods.GetSerializableMembers,
new TypeTokenExpression(targetType));
codebuilder.AddStatement(new AssignStatement(members, getSerializableMembers));
// Sort to keep order on both serialize and deserialize side the same, c.f DYNPROXY-ISSUE-127
var callSort = new MethodInvocationExpression(
null,
TypeUtilMethods.Sort,
members.ToExpression());
codebuilder.AddStatement(new AssignStatement(members, callSort));
var getObjectData = new MethodInvocationExpression(
null,
FormatterServicesMethods.GetObjectData,
SelfReference.Self.ToExpression(),
members.ToExpression());
codebuilder.AddStatement(new AssignStatement(data, getObjectData));
var addValue = new MethodInvocationExpression(
serializationInfo,
SerializationInfoMethods.AddValue_Object,
new ConstReference("__data").ToExpression(),
data.ToExpression());
codebuilder.AddStatement(new ExpressionStatement(addValue));
}
private void EmitCallToBaseGetObjectData(AbstractCodeBuilder codebuilder, ArgumentReference serializationInfo,
ArgumentReference streamingContext)
{
var baseGetObjectData = targetType.GetMethod("GetObjectData",
new[] { typeof(SerializationInfo), typeof(StreamingContext) });
codebuilder.AddStatement(new ExpressionStatement(
new MethodInvocationExpression(baseGetObjectData,
serializationInfo.ToExpression(),
streamingContext.ToExpression())));
}
private void Constructor(ClassEmitter emitter)
{
if (!delegateToBaseGetObjectData)
{
return;
}
GenerateSerializationConstructor(emitter);
}
private void GenerateSerializationConstructor(ClassEmitter emitter)
{
var serializationInfo = new ArgumentReference(typeof(SerializationInfo));
var streamingContext = new ArgumentReference(typeof(StreamingContext));
var ctor = emitter.CreateConstructor(serializationInfo, streamingContext);
ctor.CodeBuilder.AddStatement(
new ConstructorInvocationStatement(serializationConstructor,
serializationInfo.ToExpression(),
streamingContext.ToExpression()));
foreach (var field in serializedFields)
{
var getValue = new MethodInvocationExpression(serializationInfo,
SerializationInfoMethods.GetValue,
new ConstReference(field.Reference.Name).ToExpression(),
new TypeTokenExpression(field.Reference.FieldType));
ctor.CodeBuilder.AddStatement(new AssignStatement(
field,
new ConvertExpression(field.Reference.FieldType,
typeof(object),
getValue)));
}
ctor.CodeBuilder.AddStatement(new ReturnStatement());
}
private bool VerifyIfBaseImplementsGetObjectData(Type baseType, IList<MethodInfo> methodsToSkip)
{
if (!typeof(ISerializable).IsAssignableFrom(baseType))
{
return false;
}
if (IsDelegate(baseType))
{
//working around bug in CLR which returns true for "does this type implement ISerializable" for delegates
return false;
}
// If base type implements ISerializable, we have to make sure
// the GetObjectData is marked as virtual
var getObjectDataMethod = baseType.GetInterfaceMap(typeof(ISerializable)).TargetMethods[0];
if (getObjectDataMethod.IsPrivate) //explicit interface implementation
{
return false;
}
if (!getObjectDataMethod.IsVirtual || getObjectDataMethod.IsFinal)
{
var message = String.Format("The type {0} implements ISerializable, but GetObjectData is not marked as virtual. " +
"Dynamic Proxy needs types implementing ISerializable to mark GetObjectData as virtual " +
"to ensure correct serialization process.",
baseType.FullName);
throw new ArgumentException(message);
}
methodsToSkip.Add(getObjectDataMethod);
serializationConstructor = baseType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic,
null,
new[] { typeof(SerializationInfo), typeof(StreamingContext) },
null);
if (serializationConstructor == null)
{
var message = String.Format("The type {0} implements ISerializable, " +
"but failed to provide a deserialization constructor",
baseType.FullName);
throw new ArgumentException(message);
}
return true;
}
private bool IsDelegate(Type baseType)
{
return baseType.BaseType == typeof(MulticastDelegate);
}
#endif
}
}
| |
// ZlibCodec.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2009-November-03 15:40:51>
//
// ------------------------------------------------------------------
//
// This module defines a Codec for ZLIB compression and
// decompression. This code extends code that was based the jzlib
// implementation of zlib, but this code is completely novel. The codec
// class is new, and encapsulates some behaviors that are new, and some
// that were present in other classes in the jzlib code base. In
// keeping with the license for jzlib, the copyright to the jzlib code
// is included below.
//
// ------------------------------------------------------------------
//
// Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the distribution.
//
// 3. The names of the authors may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
// INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
//
// -----------------------------------------------------------------------
//
// This program is based on zlib-1.1.3; credit to authors
// Jean-loup Gailly([email protected]) and Mark Adler([email protected])
// and contributors of zlib.
//
// -----------------------------------------------------------------------
using System;
using Interop=System.Runtime.InteropServices;
namespace Ionic.Zlib
{
/// <summary>
/// Encoder and Decoder for ZLIB and DEFLATE (IETF RFC1950 and RFC1951).
/// </summary>
///
/// <remarks>
/// This class compresses and decompresses data according to the Deflate algorithm
/// and optionally, the ZLIB format, as documented in <see
/// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950 - ZLIB</see> and <see
/// href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951 - DEFLATE</see>.
/// </remarks>
[Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000D")]
[Interop.ComVisible(true)]
#if !NETCF
[Interop.ClassInterface(Interop.ClassInterfaceType.AutoDispatch)]
#endif
sealed internal class ZlibCodec
{
/// <summary>
/// The buffer from which data is taken.
/// </summary>
public byte[] InputBuffer;
/// <summary>
/// An index into the InputBuffer array, indicating where to start reading.
/// </summary>
public int NextIn;
/// <summary>
/// The number of bytes available in the InputBuffer, starting at NextIn.
/// </summary>
/// <remarks>
/// Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call.
/// The class will update this number as calls to Inflate/Deflate are made.
/// </remarks>
public int AvailableBytesIn;
/// <summary>
/// Total number of bytes read so far, through all calls to Inflate()/Deflate().
/// </summary>
public long TotalBytesIn;
/// <summary>
/// Buffer to store output data.
/// </summary>
public byte[] OutputBuffer;
/// <summary>
/// An index into the OutputBuffer array, indicating where to start writing.
/// </summary>
public int NextOut;
/// <summary>
/// The number of bytes available in the OutputBuffer, starting at NextOut.
/// </summary>
/// <remarks>
/// Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call.
/// The class will update this number as calls to Inflate/Deflate are made.
/// </remarks>
public int AvailableBytesOut;
/// <summary>
/// Total number of bytes written to the output so far, through all calls to Inflate()/Deflate().
/// </summary>
public long TotalBytesOut;
/// <summary>
/// used for diagnostics, when something goes wrong!
/// </summary>
public System.String Message;
internal DeflateManager dstate;
internal InflateManager istate;
internal uint _Adler32;
/// <summary>
/// The compression level to use in this codec. Useful only in compression mode.
/// </summary>
public CompressionLevel CompressLevel = CompressionLevel.Default;
/// <summary>
/// The number of Window Bits to use.
/// </summary>
/// <remarks>
/// This gauges the size of the sliding window, and hence the
/// compression effectiveness as well as memory consumption. It's best to just leave this
/// setting alone if you don't know what it is. The maximum value is 15 bits, which implies
/// a 32k window.
/// </remarks>
public int WindowBits = ZlibConstants.WindowBitsDefault;
/// <summary>
/// The compression strategy to use.
/// </summary>
/// <remarks>
/// This is only effective in compression. The theory offered by ZLIB is that different
/// strategies could potentially produce significant differences in compression behavior
/// for different data sets. Unfortunately I don't have any good recommendations for how
/// to set it differently. When I tested changing the strategy I got minimally different
/// compression performance. It's best to leave this property alone if you don't have a
/// good feel for it. Or, you may want to produce a test harness that runs through the
/// different strategy options and evaluates them on different file types. If you do that,
/// let me know your results.
/// </remarks>
public CompressionStrategy Strategy = CompressionStrategy.Default;
/// <summary>
/// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this.
/// </summary>
public int Adler32 { get { return (int)_Adler32; } }
/// <summary>
/// Create a ZlibCodec.
/// </summary>
/// <remarks>
/// If you use this default constructor, you will later have to explicitly call
/// InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress
/// or decompress.
/// </remarks>
public ZlibCodec() { }
/// <summary>
/// Create a ZlibCodec that either compresses or decompresses.
/// </summary>
/// <param name="mode">
/// Indicates whether the codec should compress (deflate) or decompress (inflate).
/// </param>
public ZlibCodec(CompressionMode mode)
{
if (mode == CompressionMode.Compress)
{
int rc = InitializeDeflate();
if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for deflate.");
}
else if (mode == CompressionMode.Decompress)
{
int rc = InitializeInflate();
if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for inflate.");
}
else throw new ZlibException("Invalid ZlibStreamFlavor.");
}
/// <summary>
/// Initialize the inflation state.
/// </summary>
/// <remarks>
/// It is not necessary to call this before using the ZlibCodec to inflate data;
/// It is implicitly called when you call the constructor.
/// </remarks>
/// <returns>Z_OK if everything goes well.</returns>
public int InitializeInflate()
{
return InitializeInflate(this.WindowBits);
}
/// <summary>
/// Initialize the inflation state with an explicit flag to
/// govern the handling of RFC1950 header bytes.
/// </summary>
///
/// <remarks>
/// By default, the ZLIB header defined in <see
/// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</see> is expected. If
/// you want to read a zlib stream you should specify true for
/// expectRfc1950Header. If you have a deflate stream, you will want to specify
/// false. It is only necessary to invoke this initializer explicitly if you
/// want to specify false.
/// </remarks>
///
/// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte
/// pair when reading the stream of data to be inflated.</param>
///
/// <returns>Z_OK if everything goes well.</returns>
public int InitializeInflate(bool expectRfc1950Header)
{
return InitializeInflate(this.WindowBits, expectRfc1950Header);
}
/// <summary>
/// Initialize the ZlibCodec for inflation, with the specified number of window bits.
/// </summary>
/// <param name="windowBits">The number of window bits to use. If you need to ask what that is,
/// then you shouldn't be calling this initializer.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeInflate(int windowBits)
{
this.WindowBits = windowBits;
return InitializeInflate(windowBits, true);
}
/// <summary>
/// Initialize the inflation state with an explicit flag to govern the handling of
/// RFC1950 header bytes.
/// </summary>
///
/// <remarks>
/// If you want to read a zlib stream you should specify true for
/// expectRfc1950Header. In this case, the library will expect to find a ZLIB
/// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
/// 1950</see>, in the compressed stream. If you will be reading a DEFLATE or
/// GZIP stream, which does not have such a header, you will want to specify
/// false.
/// </remarks>
///
/// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte pair when reading
/// the stream of data to be inflated.</param>
/// <param name="windowBits">The number of window bits to use. If you need to ask what that is,
/// then you shouldn't be calling this initializer.</param>
/// <returns>Z_OK if everything goes well.</returns>
public int InitializeInflate(int windowBits, bool expectRfc1950Header)
{
this.WindowBits = windowBits;
if (dstate != null) throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate().");
istate = new InflateManager(expectRfc1950Header);
return istate.Initialize(this, windowBits);
}
/// <summary>
/// Inflate the data in the InputBuffer, placing the result in the OutputBuffer.
/// </summary>
/// <remarks>
/// You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and
/// AvailableBytesOut before calling this method.
/// </remarks>
/// <example>
/// <code>
/// private void InflateBuffer()
/// {
/// int bufferSize = 1024;
/// byte[] buffer = new byte[bufferSize];
/// ZlibCodec decompressor = new ZlibCodec();
///
/// Console.WriteLine("\n============================================");
/// Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length);
/// MemoryStream ms = new MemoryStream(DecompressedBytes);
///
/// int rc = decompressor.InitializeInflate();
///
/// decompressor.InputBuffer = CompressedBytes;
/// decompressor.NextIn = 0;
/// decompressor.AvailableBytesIn = CompressedBytes.Length;
///
/// decompressor.OutputBuffer = buffer;
///
/// // pass 1: inflate
/// do
/// {
/// decompressor.NextOut = 0;
/// decompressor.AvailableBytesOut = buffer.Length;
/// rc = decompressor.Inflate(FlushType.None);
///
/// if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
/// throw new Exception("inflating: " + decompressor.Message);
///
/// ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut);
/// }
/// while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
///
/// // pass 2: finish and flush
/// do
/// {
/// decompressor.NextOut = 0;
/// decompressor.AvailableBytesOut = buffer.Length;
/// rc = decompressor.Inflate(FlushType.Finish);
///
/// if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
/// throw new Exception("inflating: " + decompressor.Message);
///
/// if (buffer.Length - decompressor.AvailableBytesOut > 0)
/// ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut);
/// }
/// while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
///
/// decompressor.EndInflate();
/// }
///
/// </code>
/// </example>
/// <param name="flush">The flush to use when inflating.</param>
/// <returns>Z_OK if everything goes well.</returns>
public int Inflate(FlushType flush)
{
if (istate == null)
throw new ZlibException("No Inflate State!");
return istate.Inflate(flush);
}
/// <summary>
/// Ends an inflation session.
/// </summary>
/// <remarks>
/// Call this after successively calling Inflate(). This will cause all buffers to be flushed.
/// After calling this you cannot call Inflate() without a intervening call to one of the
/// InitializeInflate() overloads.
/// </remarks>
/// <returns>Z_OK if everything goes well.</returns>
public int EndInflate()
{
if (istate == null)
throw new ZlibException("No Inflate State!");
int ret = istate.End();
istate = null;
return ret;
}
/// <summary>
/// I don't know what this does!
/// </summary>
/// <returns>Z_OK if everything goes well.</returns>
public int SyncInflate()
{
if (istate == null)
throw new ZlibException("No Inflate State!");
return istate.Sync();
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation.
/// </summary>
/// <remarks>
/// The codec will use the MAX window bits and the default level of compression.
/// </remarks>
/// <example>
/// <code>
/// int bufferSize = 40000;
/// byte[] CompressedBytes = new byte[bufferSize];
/// byte[] DecompressedBytes = new byte[bufferSize];
///
/// ZlibCodec compressor = new ZlibCodec();
///
/// compressor.InitializeDeflate(CompressionLevel.Default);
///
/// compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);
/// compressor.NextIn = 0;
/// compressor.AvailableBytesIn = compressor.InputBuffer.Length;
///
/// compressor.OutputBuffer = CompressedBytes;
/// compressor.NextOut = 0;
/// compressor.AvailableBytesOut = CompressedBytes.Length;
///
/// while (compressor.TotalBytesIn != TextToCompress.Length && compressor.TotalBytesOut < bufferSize)
/// {
/// compressor.Deflate(FlushType.None);
/// }
///
/// while (true)
/// {
/// int rc= compressor.Deflate(FlushType.Finish);
/// if (rc == ZlibConstants.Z_STREAM_END) break;
/// }
///
/// compressor.EndDeflate();
///
/// </code>
/// </example>
/// <returns>Z_OK if all goes well. You generally don't need to check the return code.</returns>
public int InitializeDeflate()
{
return _InternalInitializeDeflate(true);
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel.
/// </summary>
/// <remarks>
/// The codec will use the maximum window bits (15) and the specified
/// CompressionLevel. It will emit a ZLIB stream as it compresses.
/// </remarks>
/// <param name="level">The compression level for the codec.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeDeflate(CompressionLevel level)
{
this.CompressLevel = level;
return _InternalInitializeDeflate(true);
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
/// and the explicit flag governing whether to emit an RFC1950 header byte pair.
/// </summary>
/// <remarks>
/// The codec will use the maximum window bits (15) and the specified CompressionLevel.
/// If you want to generate a zlib stream, you should specify true for
/// wantRfc1950Header. In this case, the library will emit a ZLIB
/// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
/// 1950</see>, in the compressed stream.
/// </remarks>
/// <param name="level">The compression level for the codec.</param>
/// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeDeflate(CompressionLevel level, bool wantRfc1950Header)
{
this.CompressLevel = level;
return _InternalInitializeDeflate(wantRfc1950Header);
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
/// and the specified number of window bits.
/// </summary>
/// <remarks>
/// The codec will use the specified number of window bits and the specified CompressionLevel.
/// </remarks>
/// <param name="level">The compression level for the codec.</param>
/// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeDeflate(CompressionLevel level, int bits)
{
this.CompressLevel = level;
this.WindowBits = bits;
return _InternalInitializeDeflate(true);
}
/// <summary>
/// Initialize the ZlibCodec for deflation operation, using the specified
/// CompressionLevel, the specified number of window bits, and the explicit flag
/// governing whether to emit an RFC1950 header byte pair.
/// </summary>
///
/// <param name="level">The compression level for the codec.</param>
/// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param>
/// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param>
/// <returns>Z_OK if all goes well.</returns>
public int InitializeDeflate(CompressionLevel level, int bits, bool wantRfc1950Header)
{
this.CompressLevel = level;
this.WindowBits = bits;
return _InternalInitializeDeflate(wantRfc1950Header);
}
private int _InternalInitializeDeflate(bool wantRfc1950Header)
{
if (istate != null) throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate().");
dstate = new DeflateManager();
dstate.WantRfc1950HeaderBytes = wantRfc1950Header;
return dstate.Initialize(this, this.CompressLevel, this.WindowBits, this.Strategy);
}
/// <summary>
/// Deflate one batch of data.
/// </summary>
/// <remarks>
/// You must have set InputBuffer and OutputBuffer before calling this method.
/// </remarks>
/// <example>
/// <code>
/// private void DeflateBuffer(CompressionLevel level)
/// {
/// int bufferSize = 1024;
/// byte[] buffer = new byte[bufferSize];
/// ZlibCodec compressor = new ZlibCodec();
///
/// Console.WriteLine("\n============================================");
/// Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length);
/// MemoryStream ms = new MemoryStream();
///
/// int rc = compressor.InitializeDeflate(level);
///
/// compressor.InputBuffer = UncompressedBytes;
/// compressor.NextIn = 0;
/// compressor.AvailableBytesIn = UncompressedBytes.Length;
///
/// compressor.OutputBuffer = buffer;
///
/// // pass 1: deflate
/// do
/// {
/// compressor.NextOut = 0;
/// compressor.AvailableBytesOut = buffer.Length;
/// rc = compressor.Deflate(FlushType.None);
///
/// if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
/// throw new Exception("deflating: " + compressor.Message);
///
/// ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut);
/// }
/// while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
///
/// // pass 2: finish and flush
/// do
/// {
/// compressor.NextOut = 0;
/// compressor.AvailableBytesOut = buffer.Length;
/// rc = compressor.Deflate(FlushType.Finish);
///
/// if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
/// throw new Exception("deflating: " + compressor.Message);
///
/// if (buffer.Length - compressor.AvailableBytesOut > 0)
/// ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
/// }
/// while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
///
/// compressor.EndDeflate();
///
/// ms.Seek(0, SeekOrigin.Begin);
/// CompressedBytes = new byte[compressor.TotalBytesOut];
/// ms.Read(CompressedBytes, 0, CompressedBytes.Length);
/// }
/// </code>
/// </example>
/// <param name="flush">whether to flush all data as you deflate. Generally you will want to
/// use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to
/// flush everything.
/// </param>
/// <returns>Z_OK if all goes well.</returns>
public int Deflate(FlushType flush)
{
if (dstate == null)
throw new ZlibException("No Deflate State!");
return dstate.Deflate(flush);
}
/// <summary>
/// End a deflation session.
/// </summary>
/// <remarks>
/// Call this after making a series of one or more calls to Deflate(). All buffers are flushed.
/// </remarks>
/// <returns>Z_OK if all goes well.</returns>
public int EndDeflate()
{
if (dstate == null)
throw new ZlibException("No Deflate State!");
// TODO: dinoch Tue, 03 Nov 2009 15:39 (test this)
//int ret = dstate.End();
dstate = null;
return ZlibConstants.Z_OK; //ret;
}
/// <summary>
/// Reset a codec for another deflation session.
/// </summary>
/// <remarks>
/// Call this to reset the deflation state. For example if a thread is deflating
/// non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first
/// block and before the next Deflate(None) of the second block.
/// </remarks>
/// <returns>Z_OK if all goes well.</returns>
public void ResetDeflate()
{
if (dstate == null)
throw new ZlibException("No Deflate State!");
dstate.Reset();
}
/// <summary>
/// Set the CompressionStrategy and CompressionLevel for a deflation session.
/// </summary>
/// <param name="level">the level of compression to use.</param>
/// <param name="strategy">the strategy to use for compression.</param>
/// <returns>Z_OK if all goes well.</returns>
public int SetDeflateParams(CompressionLevel level, CompressionStrategy strategy)
{
if (dstate == null)
throw new ZlibException("No Deflate State!");
return dstate.SetParams(level, strategy);
}
/// <summary>
/// Set the dictionary to be used for either Inflation or Deflation.
/// </summary>
/// <param name="dictionary">The dictionary bytes to use.</param>
/// <returns>Z_OK if all goes well.</returns>
public int SetDictionary(byte[] dictionary)
{
if (istate != null)
return istate.SetDictionary(dictionary);
if (dstate != null)
return dstate.SetDictionary(dictionary);
throw new ZlibException("No Inflate or Deflate state!");
}
// Flush as much pending output as possible. All deflate() output goes
// through this function so some applications may wish to modify it
// to avoid allocating a large strm->next_out buffer and copying into it.
// (See also read_buf()).
internal void flush_pending()
{
int len = dstate.pendingCount;
if (len > AvailableBytesOut)
len = AvailableBytesOut;
if (len == 0)
return;
if (dstate.pending.Length <= dstate.nextPending ||
OutputBuffer.Length <= NextOut ||
dstate.pending.Length < (dstate.nextPending + len) ||
OutputBuffer.Length < (NextOut + len))
{
throw new ZlibException(String.Format("Invalid State. (pending.Length={0}, pendingCount={1})",
dstate.pending.Length, dstate.pendingCount));
}
Array.Copy(dstate.pending, dstate.nextPending, OutputBuffer, NextOut, len);
NextOut += len;
dstate.nextPending += len;
TotalBytesOut += len;
AvailableBytesOut -= len;
dstate.pendingCount -= len;
if (dstate.pendingCount == 0)
{
dstate.nextPending = 0;
}
}
// Read a new buffer from the current input stream, update the adler32
// and total number of bytes read. All deflate() input goes through
// this function so some applications may wish to modify it to avoid
// allocating a large strm->next_in buffer and copying from it.
// (See also flush_pending()).
internal int read_buf(byte[] buf, int start, int size)
{
int len = AvailableBytesIn;
if (len > size)
len = size;
if (len == 0)
return 0;
AvailableBytesIn -= len;
if (dstate.WantRfc1950HeaderBytes)
{
_Adler32 = Adler.Adler32(_Adler32, InputBuffer, NextIn, len);
}
Array.Copy(InputBuffer, NextIn, buf, start, len);
NextIn += len;
TotalBytesIn += len;
return len;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Globalization;
using System.Collections;
using System.Xml;
using System;
using Microsoft.Build.BuildEngine.Shared;
using Microsoft.Build.Framework;
namespace Microsoft.Build.BuildEngine
{
[Flags]
internal enum ParserOptions
{
None = 0x0,
AllowProperties = 0x1,
AllowItemLists = 0x2,
AllowPropertiesAndItemLists = AllowProperties | AllowItemLists,
AllowItemMetadata = 0x4,
AllowPropertiesAndItemMetadata = AllowProperties | AllowItemMetadata,
AllowAll = AllowProperties | AllowItemLists | AllowItemMetadata
};
/// <summary>
/// This class implements the grammar for complex conditionals.
///
/// The usage is:
/// Parser p = new Parser(CultureInfo);
/// ExpressionTree t = p.Parse(expression, XmlNode);
///
/// The expression tree can then be evaluated and re-evaluated as needed.
/// </summary>
internal sealed class Parser
{
private Scanner lexer;
private XmlAttribute conditionAttribute;
private ParserOptions options;
internal int errorPosition = 0; // useful for unit tests
#region REMOVE_COMPAT_WARNING
private bool warnedForExpression = false;
private BuildEventContext logBuildEventContext;
/// <summary>
/// Location contextual information which are attached to logging events to
/// say where they are in relation to the process, engine, project, target,task which is executing
/// </summary>
internal BuildEventContext LogBuildEventContext
{
get
{
return logBuildEventContext;
}
set
{
logBuildEventContext = value;
}
}
private EngineLoggingServices loggingServices;
/// <summary>
/// Engine Logging Service reference where events will be logged to
/// </summary>
internal EngineLoggingServices LoggingServices
{
set
{
this.loggingServices = value;
}
get
{
return this.loggingServices;
}
}
#endregion
internal Parser()
{
// nothing to see here, move along.
}
//
// Main entry point for parser.
// You pass in the expression you want to parse, and you get an
// ExpressionTree out the back end.
//
internal GenericExpressionNode Parse(string expression, XmlAttribute conditionAttributeRef, ParserOptions optionSettings)
{
// We currently have no support (and no scenarios) for disallowing property references
// in Conditions.
ErrorUtilities.VerifyThrow(0 != (optionSettings & ParserOptions.AllowProperties),
"Properties should always be allowed.");
this.conditionAttribute = conditionAttributeRef;
this.options = optionSettings;
lexer = new Scanner(expression, options);
if (!lexer.Advance())
{
errorPosition = lexer.GetErrorPosition();
ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, lexer.GetErrorResource(), expression, errorPosition, lexer.UnexpectedlyFound);
}
GenericExpressionNode node = Expr(expression);
if (!lexer.IsNext(Token.TokenType.EndOfInput))
{
errorPosition = lexer.GetErrorPosition();
ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, "UnexpectedTokenInCondition", expression, lexer.IsNextString(), errorPosition);
}
return node;
}
//
// Top node of grammar
// See grammar for how the following methods relate to each
// other.
//
private GenericExpressionNode Expr(string expression)
{
GenericExpressionNode node = BooleanTerm(expression);
if (!lexer.IsNext(Token.TokenType.EndOfInput))
{
node = ExprPrime(expression, node);
}
#region REMOVE_COMPAT_WARNING
// Check for potential change in behavior
if (LoggingServices != null && !warnedForExpression &&
node.PotentialAndOrConflict())
{
// We only want to warn once even if there multiple () sub expressions
warnedForExpression = true;
// Try to figure out where this expression was located
string projectFile = String.Empty;
int lineNumber = 0;
int columnNumber = 0;
if (this.conditionAttribute != null)
{
projectFile = XmlUtilities.GetXmlNodeFile(this.conditionAttribute, String.Empty /* no project file if XML is purely in-memory */);
XmlSearcher.GetLineColumnByNode(this.conditionAttribute, out lineNumber, out columnNumber);
}
// Log a warning regarding the fact the expression may have been evaluated
// incorrectly in earlier version of MSBuild
LoggingServices.LogWarning(logBuildEventContext,new BuildEventFileInfo(projectFile, lineNumber, columnNumber), "ConditionMaybeEvaluatedIncorrectly", expression);
}
#endregion
return node;
}
private GenericExpressionNode ExprPrime(string expression, GenericExpressionNode lhs)
{
if (Same(expression, Token.TokenType.EndOfInput))
{
return lhs;
}
else if (Same(expression, Token.TokenType.Or))
{
OperatorExpressionNode orNode = new OrExpressionNode();
GenericExpressionNode rhs = BooleanTerm(expression);
orNode.LeftChild = lhs;
orNode.RightChild = rhs;
return ExprPrime( expression, orNode );
}
else
{
// I think this is ok. ExprPrime always shows up at
// the rightmost side of the grammar rhs, the EndOfInput case
// takes care of things
return lhs;
}
}
private GenericExpressionNode BooleanTerm(string expression)
{
GenericExpressionNode node = RelationalExpr(expression);
if (null == node)
{
errorPosition = lexer.GetErrorPosition();
ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, "UnexpectedTokenInCondition", expression, lexer.IsNextString(), errorPosition);
}
if (!lexer.IsNext(Token.TokenType.EndOfInput))
{
node = BooleanTermPrime(expression, node);
}
return node;
}
private GenericExpressionNode BooleanTermPrime(string expression, GenericExpressionNode lhs)
{
if (lexer.IsNext(Token.TokenType.EndOfInput))
{
return lhs;
}
else if (Same(expression, Token.TokenType.And))
{
GenericExpressionNode rhs = RelationalExpr(expression);
if (null == rhs)
{
errorPosition = lexer.GetErrorPosition();
ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, "UnexpectedTokenInCondition", expression, lexer.IsNextString(), errorPosition);
}
OperatorExpressionNode andNode = new AndExpressionNode();
andNode.LeftChild = lhs;
andNode.RightChild = rhs;
return BooleanTermPrime(expression, andNode);
}
else
{
// Should this be error case?
return lhs;
}
}
private GenericExpressionNode RelationalExpr(string expression)
{
{
GenericExpressionNode lhs = Factor(expression);
if (null == lhs)
{
errorPosition = lexer.GetErrorPosition();
ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, "UnexpectedTokenInCondition", expression, lexer.IsNextString(), errorPosition);
}
OperatorExpressionNode node = RelationalOperation(expression);
if (node == null)
{
return lhs;
}
GenericExpressionNode rhs = Factor(expression);
node.LeftChild = lhs;
node.RightChild = rhs;
return node;
}
}
private OperatorExpressionNode RelationalOperation(string expression)
{
OperatorExpressionNode node = null;
if (Same(expression, Token.TokenType.LessThan))
{
node = new LessThanExpressionNode();
}
else if (Same(expression, Token.TokenType.GreaterThan))
{
node = new GreaterThanExpressionNode();
}
else if (Same(expression, Token.TokenType.LessThanOrEqualTo))
{
node = new LessThanOrEqualExpressionNode();
}
else if (Same(expression, Token.TokenType.GreaterThanOrEqualTo))
{
node = new GreaterThanOrEqualExpressionNode();
}
else if (Same(expression, Token.TokenType.EqualTo))
{
node = new EqualExpressionNode();
}
else if (Same(expression, Token.TokenType.NotEqualTo))
{
node = new NotEqualExpressionNode();
}
return node;
}
private GenericExpressionNode Factor(string expression)
{
// Checks for TokenTypes String, Numeric, Property, ItemMetadata, and ItemList.
GenericExpressionNode arg = this.Arg(expression);
// If it's one of those, return it.
if (arg != null)
{
return arg;
}
// If it's not one of those, check for other TokenTypes.
Token current = lexer.CurrentToken;
if (Same(expression, Token.TokenType.Function))
{
if (!Same(expression, Token.TokenType.LeftParenthesis))
{
errorPosition = lexer.GetErrorPosition();
ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, "UnexpectedTokenInCondition", lexer.IsNextString(), errorPosition);
return null;
}
ArrayList arglist = new ArrayList();
Arglist(expression, arglist);
if (!Same(expression, Token.TokenType.RightParenthesis))
{
errorPosition = lexer.GetErrorPosition();
ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, "UnexpectedTokenInCondition", expression, lexer.IsNextString(), errorPosition);
return null;
}
return new FunctionCallExpressionNode( current.String, arglist);
}
else if (Same(expression, Token.TokenType.LeftParenthesis))
{
GenericExpressionNode child = Expr(expression);
if (Same(expression, Token.TokenType.RightParenthesis))
return child;
else
{
errorPosition = lexer.GetErrorPosition();
ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, "UnexpectedTokenInCondition", expression, lexer.IsNextString(), errorPosition);
}
}
else if (Same(expression, Token.TokenType.Not))
{
OperatorExpressionNode notNode = new NotExpressionNode();
GenericExpressionNode expr = Factor(expression);
if (expr == null)
{
errorPosition = lexer.GetErrorPosition();
ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, "UnexpectedTokenInCondition", expression, lexer.IsNextString(), errorPosition);
}
notNode.LeftChild = expr;
return notNode;
}
else
{
errorPosition = lexer.GetErrorPosition();
ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, "UnexpectedTokenInCondition", expression, lexer.IsNextString(), errorPosition);
}
return null;
}
private void Arglist(string expression, ArrayList arglist)
{
if (!lexer.IsNext(Token.TokenType.RightParenthesis))
Args(expression, arglist);
}
private void Args(string expression, ArrayList arglist)
{
GenericExpressionNode arg = Arg(expression);
arglist.Add(arg);
if (Same(expression, Token.TokenType.Comma))
{
Args(expression, arglist);
}
}
private GenericExpressionNode Arg(string expression)
{
Token current = lexer.CurrentToken;
if (Same(expression, Token.TokenType.String))
{
return new StringExpressionNode(current.String);
}
else if (Same(expression, Token.TokenType.Numeric))
{
return new NumericExpressionNode(current.String);
}
else if (Same(expression, Token.TokenType.Property))
{
return new StringExpressionNode(current.String);
}
else if (Same(expression, Token.TokenType.ItemMetadata))
{
return new StringExpressionNode(current.String);
}
else if (Same(expression, Token.TokenType.ItemList))
{
return new StringExpressionNode(current.String);
}
else
{
return null;
}
}
private bool Same(string expression, Token.TokenType token)
{
if (lexer.IsNext(token))
{
if (!lexer.Advance())
{
errorPosition = lexer.GetErrorPosition();
if (null != lexer.UnexpectedlyFound)
{
ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, lexer.GetErrorResource(), expression, errorPosition, lexer.UnexpectedlyFound);
}
else
{
ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, lexer.GetErrorResource(), expression, errorPosition);
}
}
return true;
}
else
return false;
}
}
}
| |
//
// CheckBoxTableCell.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using AppKit;
using Foundation;
using Xwt.Backends;
namespace Xwt.Mac
{
class CheckBoxTableCell: NSButton, ICellRenderer
{
NSTrackingArea trackingArea;
public CheckBoxTableCell ()
{
SetButtonType (NSButtonType.Switch);
Activated += HandleActivated;
Title = string.Empty;
}
public override NSCellStateValue State {
get {
return base.State;
}
set {
// don't let Cocoa set the state for us
}
}
void HandleActivated (object sender, EventArgs e)
{
Backend.Load (this);
var cellView = Frontend;
var nextState = State; // store new state internally set by Cocoa
base.State = cellView.State.ToMacState (); // reset state to previous state from store
CellContainer.SetCurrentEventRow ();
if (!cellView.RaiseToggled ()) {
if (cellView.StateField != null)
CellContainer.SetValue (cellView.StateField, nextState.ToXwtState ());
else if (cellView.ActiveField != null)
CellContainer.SetValue (cellView.ActiveField, nextState != NSCellStateValue.Off);
}
}
NSCellStateValue GetNextState ()
{
if (!AllowsMixedState) {
switch (State) {
case NSCellStateValue.Off:
case NSCellStateValue.Mixed:
return NSCellStateValue.On;
default: return NSCellStateValue.Off;
}
} else {
switch (State) {
case NSCellStateValue.Off:
return NSCellStateValue.Mixed;
case NSCellStateValue.Mixed:
return NSCellStateValue.On;
default: return NSCellStateValue.Off;
}
}
}
ICheckBoxCellViewFrontend Frontend {
get { return (ICheckBoxCellViewFrontend) Backend.Frontend; }
}
public CellViewBackend Backend { get; set; }
public CompositeCell CellContainer { get; set; }
public NSView CellView { get { return this; } }
public void Fill ()
{
var cellView = Frontend;
AllowsMixedState = cellView.AllowMixed || cellView.State == CheckBoxState.Mixed;
base.State = cellView.State.ToMacState ();
Enabled = cellView.Editable;
Hidden = !cellView.Visible;
}
public virtual NSBackgroundStyle BackgroundStyle {
[Export ("backgroundStyle")]
get {
return Cell.BackgroundStyle;
}
[Export ("setBackgroundStyle:")]
set {
Cell.BackgroundStyle = value;
}
}
public void CopyFrom (object other)
{
var ob = (CheckBoxTableCell)other;
Backend = ob.Backend;
}
public override void UpdateTrackingAreas ()
{
if (trackingArea != null) {
RemoveTrackingArea (trackingArea);
trackingArea.Dispose ();
}
var options = NSTrackingAreaOptions.MouseMoved | NSTrackingAreaOptions.ActiveInKeyWindow | NSTrackingAreaOptions.MouseEnteredAndExited;
trackingArea = new NSTrackingArea (Bounds, options, this, null);
AddTrackingArea (trackingArea);
}
public override void RightMouseDown (NSEvent theEvent)
{
if (!this.HandleMouseDown (theEvent))
base.RightMouseDown (theEvent);
}
public override void RightMouseUp (NSEvent theEvent)
{
if (!this.HandleMouseUp (theEvent))
base.RightMouseUp (theEvent);
}
public override void MouseDown (NSEvent theEvent)
{
if (!this.HandleMouseDown (theEvent))
base.MouseDown (theEvent);
}
public override void MouseUp (NSEvent theEvent)
{
if (!this.HandleMouseUp (theEvent))
base.MouseUp (theEvent);
}
public override void OtherMouseDown (NSEvent theEvent)
{
if (!this.HandleMouseDown (theEvent))
base.OtherMouseDown (theEvent);
}
public override void OtherMouseUp (NSEvent theEvent)
{
if (!this.HandleMouseUp (theEvent))
base.OtherMouseUp (theEvent);
}
public override void MouseEntered (NSEvent theEvent)
{
this.HandleMouseEntered (theEvent);
base.MouseEntered (theEvent);
}
public override void MouseExited (NSEvent theEvent)
{
this.HandleMouseExited (theEvent);
base.MouseExited (theEvent);
}
public override void MouseMoved (NSEvent theEvent)
{
if (!this.HandleMouseMoved (theEvent))
base.MouseMoved (theEvent);
}
public override void MouseDragged (NSEvent theEvent)
{
if (!this.HandleMouseMoved (theEvent))
base.MouseDragged (theEvent);
}
public override void KeyDown (NSEvent theEvent)
{
if (!this.HandleKeyDown (theEvent))
base.KeyDown (theEvent);
}
public override void KeyUp (NSEvent theEvent)
{
if (!this.HandleKeyUp (theEvent))
base.KeyUp (theEvent);
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Referensi_Dokter_List : System.Web.UI.Page
{
public int NoKe = 0;
protected string dsReportSessionName = "dsListRefDokter";
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["DokterManagement"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
else
{
btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddDokter");
}
btnSearch.Text = Resources.GetString("", "Search");
ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif";
ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif";
ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif";
ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif";
UpdateDataView(true);
}
}
#region .Update View Data
//////////////////////////////////////////////////////////////////////
// PhysicalDataRead
// ------------------------------------------------------------------
/// <summary>
/// This function is responsible for loading data from database.
/// </summary>
/// <returns>DataSet</returns>
public DataSet PhysicalDataRead()
{
// Local variables
DataSet oDS = new DataSet();
// Get Data
SIMRS.DataAccess.RS_Dokter myObj = new SIMRS.DataAccess.RS_Dokter();
DataTable myData = myObj.SelectAll();
oDS.Tables.Add(myData);
return oDS;
}
/// <summary>
/// This function is responsible for binding data to Datagrid.
/// </summary>
/// <param name="dv"></param>
private void BindData(DataView dv)
{
// Sets the sorting order
dv.Sort = DataGridList.Attributes["SortField"];
if (DataGridList.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
DataGridList.ShowFooter = false;
int intRowCount = dv.Count;
int intPageSaze = DataGridList.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (DataGridList.CurrentPageIndex >= intPageCount)
DataGridList.CurrentPageIndex = intPageCount - 1;
}
else
{
DataGridList.ShowFooter = true;
DataGridList.CurrentPageIndex = 0;
}
// Re-binds the grid
NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex;
DataGridList.DataSource = dv;
DataGridList.DataBind();
int CurrentPage = DataGridList.CurrentPageIndex + 1;
lblCurrentPage.Text = CurrentPage.ToString();
lblTotalPage.Text = DataGridList.PageCount.ToString();
lblTotalRecord.Text = dv.Count.ToString();
}
/// <summary>
/// This function is responsible for loading data from database and store to Session.
/// </summary>
/// <param name="strDataSessionName"></param>
public void DataFromSourceToMemory(String strDataSessionName)
{
// Gets rows from the data source
DataSet oDS = PhysicalDataRead();
// Stores it in the session cache
Session[strDataSessionName] = oDS;
}
/// <summary>
/// This function is responsible for update data view from datagrid.
/// </summary>
/// <param name="requery">true = get data from database, false= get data from session</param>
public void UpdateDataView(bool requery)
{
// Retrieves the data
if ((Session[dsReportSessionName] == null) || (requery))
{
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString());
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
public void UpdateDataView()
{
// Retrieves the data
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
#endregion
#region .Event DataGridList
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// HANDLERs //
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGridList.CurrentPageIndex = e.NewPageIndex;
DataGridList.SelectedIndex = -1;
UpdateDataView();
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="nPageIndex"></param>
public void GoToPage(Object sender, int nPageIndex)
{
DataGridPageChangedEventArgs evPage;
evPage = new DataGridPageChangedEventArgs(sender, nPageIndex);
PageChanged(sender, evPage);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a first page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToFirst(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, 0);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a previous page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToPrev(Object sender, ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex > 0)
{
GoToPage(sender, DataGridList.CurrentPageIndex - 1);
}
else
{
GoToPage(sender, 0);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a next page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1))
{
GoToPage(sender, DataGridList.CurrentPageIndex + 1);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a last page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToLast(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, DataGridList.PageCount - 1);
}
/// <summary>
/// This function is invoked when you click on a column's header to
/// sort by that. It just saves the current sort field name and
/// refreshes the grid.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SortByColumn(Object sender, DataGridSortCommandEventArgs e)
{
String strSortBy = DataGridList.Attributes["SortField"];
String strSortAscending = DataGridList.Attributes["SortAscending"];
// Sets the new sorting field
DataGridList.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
DataGridList.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
OnClearSelection(null, null);
UpdateDataView();
}
/// <summary>
/// The function gets invoked when a new item is being created in
/// the datagrid. This applies to pager, header, footer, regular
/// and alternating items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageItemCreated(Object sender, DataGridItemEventArgs e)
{
// Get the newly created item
ListItemType itemType = e.Item.ItemType;
//////////////////////////////////////////////////////////
// Is it the HEADER?
if (itemType == ListItemType.Header)
{
for (int i = 0; i < DataGridList.Columns.Count; i++)
{
// draw to reflect sorting
if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression)
{
//////////////////////////////////////////////
// Should be much easier this way:
// ------------------------------------------
// TableCell cell = e.Item.Cells[i];
// Label lblSorted = new Label();
// lblSorted.Font = "webdings";
// lblSorted.Text = strOrder;
// cell.Controls.Add(lblSorted);
//
// but it seems it doesn't work <g>
//////////////////////////////////////////////
// Add a non-clickable triangle to mean desc or asc.
// The </a> ensures that what follows is non-clickable
TableCell cell = e.Item.Cells[i];
LinkButton lb = (LinkButton)cell.Controls[0];
//lb.Text += "</a> <span style=font-family:webdings;>" + GetOrderSymbol() + "</span>";
lb.Text += "</a> <img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >";
}
}
}
//////////////////////////////////////////////////////////
// Is it the PAGER?
if (itemType == ListItemType.Pager)
{
// There's just one control in the list...
TableCell pager = (TableCell)e.Item.Controls[0];
// Enumerates all the items in the pager...
for (int i = 0; i < pager.Controls.Count; i += 2)
{
// It can be either a Label or a Link button
try
{
Label l = (Label)pager.Controls[i];
l.Text = "Hal " + l.Text;
l.CssClass = "CurrentPage";
}
catch
{
LinkButton h = (LinkButton)pager.Controls[i];
h.Text = "[ " + h.Text + " ]";
h.CssClass = "HotLink";
}
}
}
}
/// <summary>
/// Verifies whether the current sort is ascending or descending and
/// returns an appropriate display text (i.e., a webding)
/// </summary>
/// <returns></returns>
private String GetOrderSymbol()
{
bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no");
//return (bDescending ? " 6" : " 5");
return (bDescending ? "downbr.gif" : "upbr.gif");
}
/// <summary>
/// When clicked clears the current selection if any
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnClearSelection(Object sender, EventArgs e)
{
DataGridList.SelectedIndex = -1;
}
#endregion
#region .Event Button
/// <summary>
/// When clicked, redirect to form add for inserts a new record to the database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnNewRecord(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("Add.aspx?CurrentPage=" + CurrentPage);
}
/// <summary>
/// When clicked, filter data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSearch(Object sender, System.EventArgs e)
{
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
DataView dv = ds.Tables[0].DefaultView;
if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Nama")
dv.RowFilter = " Nama LIKE '%" + txtSearch.Text + "%'";
else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Spesialis")
dv.RowFilter = " SpesialisNama LIKE '%" + txtSearch.Text + "%'";
else
dv.RowFilter = "";
BindData(dv);
}
#endregion
#region .Update Link Item Butom
public string GetLinkButton(string DokterId, string Nama, string CurrentPage)
{
string szResult = "";
if (Session["DokterManagement"] != null)
{
szResult += "<a class=\"toolbar\" href=\"Edit.aspx?CurrentPage=" + CurrentPage + "&DokterId=" + DokterId + "\" ";
szResult += ">" + Resources.GetString("", "Edit") + "</a>";
szResult += "<a class=\"toolbar\" href=\"Delete.aspx?CurrentPage=" + CurrentPage + "&DokterId=" + DokterId + "\" ";
szResult += ">" + Resources.GetString("", "Delete") + "</a>";
}
return szResult;
}
#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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class SumTests
{
public static IEnumerable<object[]> SumData(int[] counts)
{
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), x => Functions.SumRange(0L, x))) yield return results;
}
//
// Sum
//
[Theory]
[MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Sum_Int(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Sum());
Assert.Equal(sum, query.Select(x => (int?)x).Sum());
Assert.Equal(default(int), query.Select(x => (int?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -x));
Assert.Equal(-sum, query.Sum(x => -(int?)x));
Assert.Equal(default(int), query.Sum(x => (int?)null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (int?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(int?)x : null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (int?)null).Sum());
Assert.Equal(0, query.Sum(x => (int?)null));
}
[Theory]
[OuterLoop]
[MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 64 }))]
public static void Sum_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int sum)
{
Sum_Int(labeled, count, sum);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Sum_Int_Overflow(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? int.MaxValue : x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? int.MaxValue : (int?)x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? int.MinValue : -x));
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? int.MinValue : -(int?)x));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Sum_Long(Labeled<ParallelQuery<int>> labeled, int count, long sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Select(x => (long)x).Sum());
Assert.Equal(sum, query.Select(x => (long?)x).Sum());
Assert.Equal(default(long), query.Select(x => (long?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -(long)x));
Assert.Equal(-sum, query.Sum(x => -(long?)x));
Assert.Equal(default(long), query.Sum(x => (long?)null));
}
[Theory]
[OuterLoop]
[MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Sum_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, long sum)
{
Sum_Long(labeled, count, sum);
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, long sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0L, count / 2), query.Select(x => x < count / 2 ? (long?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0L, count / 2), query.Sum(x => x < count / 2 ? -(long?)x : null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, long sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (long?)null).Sum());
Assert.Equal(0, query.Sum(x => (long?)null));
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Sum_Long_Overflow(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? long.MaxValue : x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? long.MaxValue : (long?)x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? long.MinValue : -x));
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? long.MinValue : -(long?)x));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Sum_Float(Labeled<ParallelQuery<int>> labeled, int count, float sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Select(x => (float)x).Sum());
Assert.Equal(sum, query.Select(x => (float?)x).Sum());
Assert.Equal(default(float), query.Select(x => (float?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -(float)x));
Assert.Equal(-sum, query.Sum(x => -(float?)x));
Assert.Equal(default(float), query.Sum(x => (float?)null));
}
[Theory]
[OuterLoop]
[MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Sum_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float sum)
{
Sum_Float(labeled, count, sum);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Sum_Float_Overflow(Labeled<ParallelQuery<int>> labeled, int count)
{
Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => float.MaxValue).Sum());
Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => (float?)float.MaxValue).Sum().Value);
Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => float.MaxValue));
Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => (float?)float.MaxValue).Value);
Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => float.PositiveInfinity).Sum());
Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => (float?)float.PositiveInfinity).Sum().Value);
Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => float.PositiveInfinity));
Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => (float?)float.PositiveInfinity).Value);
Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => float.MinValue).Sum());
Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => (float?)float.MinValue).Sum().Value);
Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => float.MinValue));
Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => (float?)float.MinValue).Value);
Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => float.NegativeInfinity).Sum());
Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => (float?)float.NegativeInfinity).Sum().Value);
Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => float.NegativeInfinity));
Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => (float?)float.NegativeInfinity).Value);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Sum_Float_NaN(Labeled<ParallelQuery<int>> labeled, int count)
{
Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : x).Sum());
Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value);
Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : x));
Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : x)).Value);
Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : x).Sum());
Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value);
Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : x));
Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : x)).Value);
Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : -x).Sum());
Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value);
Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : -x));
Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : -x)).Value);
Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : x).Sum());
Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value);
Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : x));
Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : x)).Value);
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (float?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(float?)x : null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (float?)null).Sum());
Assert.Equal(0, query.Sum(x => (float?)null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Sum_Double(Labeled<ParallelQuery<int>> labeled, int count, double sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Select(x => (double)x).Sum());
Assert.Equal(sum, query.Select(x => (double?)x).Sum());
Assert.Equal(default(double), query.Select(x => (double?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -(double)x));
Assert.Equal(-sum, query.Sum(x => -(double?)x));
Assert.Equal(default(double), query.Sum(x => (double?)null));
}
[Theory]
[OuterLoop]
[MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Sum_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double sum)
{
Sum_Double(labeled, count, sum);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Sum_Double_Overflow(Labeled<ParallelQuery<int>> labeled, int count)
{
Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => double.MaxValue).Sum());
Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => (double?)double.MaxValue).Sum().Value);
Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => double.MaxValue));
Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => (double?)double.MaxValue).Value);
Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => double.PositiveInfinity).Sum());
Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => (double?)double.PositiveInfinity).Sum().Value);
Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => double.PositiveInfinity));
Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => (double?)double.PositiveInfinity).Value);
Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => double.MinValue).Sum());
Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => (double?)double.MinValue).Sum().Value);
Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => double.MinValue));
Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => (double?)double.MinValue).Value);
Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => double.NegativeInfinity).Sum());
Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => (double?)double.NegativeInfinity).Sum().Value);
Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => double.NegativeInfinity));
Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => (double?)double.NegativeInfinity).Value);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Sum_Double_NaN(Labeled<ParallelQuery<int>> labeled, int count)
{
Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : x).Sum());
Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value);
Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : x));
Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : x)).Value);
Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : x).Sum());
Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value);
Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : x));
Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : x)).Value);
Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : -x).Sum());
Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value);
Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : -x));
Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : -x)).Value);
Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : x).Sum());
Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value);
Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : x));
Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : x)).Value);
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (double?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(double?)x : null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (double?)null).Sum());
Assert.Equal(0, query.Sum(x => (double?)null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Sum_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(sum, query.Select(x => (decimal)x).Sum());
Assert.Equal(sum, query.Select(x => (decimal?)x).Sum());
Assert.Equal(default(decimal), query.Select(x => (decimal?)null).Sum());
Assert.Equal(-sum, query.Sum(x => -(decimal)x));
Assert.Equal(default(decimal), query.Sum(x => (decimal?)null));
}
[Theory]
[OuterLoop]
[MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Sum_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal sum)
{
Sum_Decimal(labeled, count, sum);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Sum_Decimal_Overflow(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? decimal.MaxValue : x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? decimal.MaxValue : (decimal?)x).Sum());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? decimal.MinValue : -x));
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? decimal.MinValue : -(decimal?)x));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (decimal?)x : null).Sum());
Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(decimal?)x : null));
}
[Theory]
[MemberData("SumData", (object)(new int[] { 1, 2, 16 }))]
public static void Sum_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal sum)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(0, query.Select(x => (decimal?)null).Sum());
Assert.Equal(0, query.Sum(x => (decimal?)null));
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Sum_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (int?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (long)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (long?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (float)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (float?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (double)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (double?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (decimal)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (decimal?)x));
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Sum_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, int>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, int?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, long>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, long?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, float>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, float?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, double>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, double?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, decimal>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, decimal?>)(x => { throw new DeliberateTestException(); })));
}
[Fact]
public static void Sum_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Sum((Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Sum((Func<int?, int?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Sum((Func<long, long>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Sum((Func<long?, long?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Sum((Func<float, float>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Sum((Func<float?, float>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Sum((Func<double, double>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Sum((Func<double?, double>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Sum((Func<decimal, decimal>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Sum());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Sum((Func<decimal?, decimal>)null));
}
}
}
| |
// MIT License
//
// Copyright(c) 2022 ICARUS Consulting GmbH
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System.Collections.Generic;
using Yaapii.Atoms.Enumerable;
using Yaapii.Atoms.Scalar;
namespace Yaapii.Atoms.Number
{
/// <summary>
/// The minimum of the given numbers
/// </summary>
public sealed class MinOf : NumberEnvelope
{
/// <summary>
/// The minimum of the source integers
/// </summary>
/// <param name="src">integers to find max in</param>
public MinOf(params int[] src) : this(
new ManyOf<int>(src))
{ }
/// <summary>
/// The minimum of the source integers
/// </summary>
/// <param name="src">integers to find max in</param>
public MinOf(IEnumerable<int> src) : base(
new ScalarOf<double>(() =>
{
var min = double.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = e.Current;
}
return min;
}),
new ScalarOf<int>(() =>
{
var min = int.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = e.Current;
}
return min;
}),
new ScalarOf<long>(() =>
{
var min = long.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = e.Current;
}
return min;
}),
new ScalarOf<float>(() =>
{
var min = float.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = e.Current;
}
return min;
})
)
{ }
/// <summary>
/// The minimum of the source integers
/// </summary>
/// <param name="src">integers to find max in</param>
public MinOf(params double[] src) : this(
new ManyOf<double>(src))
{ }
/// <summary>
/// The minimum of the source integers
/// </summary>
/// <param name="src">integers to find max in</param>
public MinOf(IEnumerable<double> src) : base(
new ScalarOf<double>(() =>
{
var min = double.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = e.Current;
}
return min;
}),
new ScalarOf<int>(() =>
{
var min = int.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = (int)e.Current;
}
return min;
}),
new ScalarOf<long>(() =>
{
var min = long.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = (long)e.Current;
}
return min;
}),
new ScalarOf<float>(() =>
{
var min = float.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = (float)e.Current;
}
return min;
})
)
{ }
/// <summary>
/// The minimum of the source integers
/// </summary>
/// <param name="src">integers to find max in</param>
public MinOf(params long[] src) : this(
new ManyOf<long>(src))
{ }
/// <summary>
/// The minimum of the source integers
/// </summary>
/// <param name="src">integers to find max in</param>
public MinOf(IEnumerable<long> src) : base(
new ScalarOf<double>(() =>
{
var min = double.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = e.Current;
}
return min;
}),
new ScalarOf<int>(() =>
{
var min = int.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = (int)e.Current;
}
return min;
}),
new ScalarOf<long>(() =>
{
var min = long.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = (long)e.Current;
}
return min;
}),
new ScalarOf<float>(() =>
{
var min = float.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = (float)e.Current;
}
return min;
})
)
{ }
/// <summary>
/// The minimum of the source integers
/// </summary>
/// <param name="src">integers to find max in</param>
public MinOf(params float[] src) : this(
new ManyOf<float>(src))
{ }
/// <summary>
/// The minimum of the source integers
/// </summary>
/// <param name="src">integers to find max in</param>
public MinOf(IEnumerable<float> src) : base(
new ScalarOf<double>(() =>
{
var min = double.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = e.Current;
}
return min;
}),
new ScalarOf<int>(() =>
{
var min = int.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = (int)e.Current;
}
return min;
}),
new ScalarOf<long>(() =>
{
var min = long.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = (long)e.Current;
}
return min;
}),
new ScalarOf<float>(() =>
{
var min = float.MaxValue;
var e = src.GetEnumerator();
while (e.MoveNext())
{
if (e.Current < min) min = (float)e.Current;
}
return min;
})
)
{ }
}
}
| |
using System;
using Raksha.Crypto.Parameters;
namespace Raksha.Crypto.Engines
{
/**
* The specification for RC5 came from the <code>RC5 Encryption Algorithm</code>
* publication in RSA CryptoBytes, Spring of 1995.
* <em>http://www.rsasecurity.com/rsalabs/cryptobytes</em>.
* <p>
* This implementation is set to work with a 64 bit word size.</p>
*/
public class RC564Engine
: IBlockCipher
{
private static readonly int wordSize = 64;
private static readonly int bytesPerWord = wordSize / 8;
/*
* the number of rounds to perform
*/
private int _noRounds;
/*
* the expanded key array of size 2*(rounds + 1)
*/
private long [] _S;
/*
* our "magic constants" for wordSize 62
*
* Pw = Odd((e-2) * 2^wordsize)
* Qw = Odd((o-2) * 2^wordsize)
*
* where e is the base of natural logarithms (2.718281828...)
* and o is the golden ratio (1.61803398...)
*/
private static readonly long P64 = unchecked( (long) 0xb7e151628aed2a6bL);
private static readonly long Q64 = unchecked( (long) 0x9e3779b97f4a7c15L);
private bool forEncryption;
/**
* Create an instance of the RC5 encryption algorithm
* and set some defaults
*/
public RC564Engine()
{
_noRounds = 12;
// _S = null;
}
public string AlgorithmName
{
get { return "RC5-64"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return 2 * bytesPerWord;
}
/**
* initialise a RC5-64 cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is RC5Parameters))
{
throw new ArgumentException("invalid parameter passed to RC564 init - " + parameters.GetType().ToString());
}
RC5Parameters p = (RC5Parameters)parameters;
this.forEncryption = forEncryption;
_noRounds = p.Rounds;
SetKey(p.GetKey());
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
return (forEncryption) ? EncryptBlock(input, inOff, output, outOff)
: DecryptBlock(input, inOff, output, outOff);
}
public void Reset()
{
}
/**
* Re-key the cipher.
*
* @param key the key to be used
*/
private void SetKey(
byte[] key)
{
//
// KEY EXPANSION:
//
// There are 3 phases to the key expansion.
//
// Phase 1:
// Copy the secret key K[0...b-1] into an array L[0..c-1] of
// c = ceil(b/u), where u = wordSize/8 in little-endian order.
// In other words, we fill up L using u consecutive key bytes
// of K. Any unfilled byte positions in L are zeroed. In the
// case that b = c = 0, set c = 1 and L[0] = 0.
//
long[] L = new long[(key.Length + (bytesPerWord - 1)) / bytesPerWord];
for (int i = 0; i != key.Length; i++)
{
L[i / bytesPerWord] += (long)(key[i] & 0xff) << (8 * (i % bytesPerWord));
}
//
// Phase 2:
// Initialize S to a particular fixed pseudo-random bit pattern
// using an arithmetic progression modulo 2^wordsize determined
// by the magic numbers, Pw & Qw.
//
_S = new long[2*(_noRounds + 1)];
_S[0] = P64;
for (int i=1; i < _S.Length; i++)
{
_S[i] = (_S[i-1] + Q64);
}
//
// Phase 3:
// Mix in the user's secret key in 3 passes over the arrays S & L.
// The max of the arrays sizes is used as the loop control
//
int iter;
if (L.Length > _S.Length)
{
iter = 3 * L.Length;
}
else
{
iter = 3 * _S.Length;
}
long A = 0, B = 0;
int ii = 0, jj = 0;
for (int k = 0; k < iter; k++)
{
A = _S[ii] = RotateLeft(_S[ii] + A + B, 3);
B = L[jj] = RotateLeft( L[jj] + A + B, A+B);
ii = (ii+1) % _S.Length;
jj = (jj+1) % L.Length;
}
}
/**
* Encrypt the given block starting at the given offset and place
* the result in the provided buffer starting at the given offset.
*
* @param in in byte buffer containing data to encrypt
* @param inOff offset into src buffer
* @param out out buffer where encrypted data is written
* @param outOff offset into out buffer
*/
private int EncryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
long A = BytesToWord(input, inOff) + _S[0];
long B = BytesToWord(input, inOff + bytesPerWord) + _S[1];
for (int i = 1; i <= _noRounds; i++)
{
A = RotateLeft(A ^ B, B) + _S[2*i];
B = RotateLeft(B ^ A, A) + _S[2*i+1];
}
WordToBytes(A, outBytes, outOff);
WordToBytes(B, outBytes, outOff + bytesPerWord);
return 2 * bytesPerWord;
}
private int DecryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
long A = BytesToWord(input, inOff);
long B = BytesToWord(input, inOff + bytesPerWord);
for (int i = _noRounds; i >= 1; i--)
{
B = RotateRight(B - _S[2*i+1], A) ^ A;
A = RotateRight(A - _S[2*i], B) ^ B;
}
WordToBytes(A - _S[0], outBytes, outOff);
WordToBytes(B - _S[1], outBytes, outOff + bytesPerWord);
return 2 * bytesPerWord;
}
//////////////////////////////////////////////////////////////
//
// PRIVATE Helper Methods
//
//////////////////////////////////////////////////////////////
/**
* Perform a left "spin" of the word. The rotation of the given
* word <em>x</em> is rotated left by <em>y</em> bits.
* Only the <em>lg(wordSize)</em> low-order bits of <em>y</em>
* are used to determine the rotation amount. Here it is
* assumed that the wordsize used is a power of 2.
*
* @param x word to rotate
* @param y number of bits to rotate % wordSize
*/
private long RotateLeft(long x, long y) {
return ((long) ( (ulong) (x << (int) (y & (wordSize-1))) |
((ulong) x >> (int) (wordSize - (y & (wordSize-1)))))
);
}
/**
* Perform a right "spin" of the word. The rotation of the given
* word <em>x</em> is rotated left by <em>y</em> bits.
* Only the <em>lg(wordSize)</em> low-order bits of <em>y</em>
* are used to determine the rotation amount. Here it is
* assumed that the wordsize used is a power of 2.
*
* @param x word to rotate
* @param y number of bits to rotate % wordSize
*/
private long RotateRight(long x, long y) {
return ((long) ( ((ulong) x >> (int) (y & (wordSize-1))) |
(ulong) (x << (int) (wordSize - (y & (wordSize-1)))))
);
}
private long BytesToWord(
byte[] src,
int srcOff)
{
long word = 0;
for (int i = bytesPerWord - 1; i >= 0; i--)
{
word = (word << 8) + (src[i + srcOff] & 0xff);
}
return word;
}
private void WordToBytes(
long word,
byte[] dst,
int dstOff)
{
for (int i = 0; i < bytesPerWord; i++)
{
dst[i + dstOff] = (byte)word;
word = (long) ((ulong) word >> 8);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Reflection.Compatibility.UnitTests.TypeTests
{
public class IsAssignableFromTest
{
[Fact]
public void Test1()
{
VerifyIsAssignableFrom("B&null", typeof(B).GetTypeInfo(), null, false);
}
[Fact]
public void Test2()
{
VerifyIsAssignableFrom("ListArray", typeof(IList<object>).GetTypeInfo(), typeof(object[]).GetTypeInfo(), true);
}
[Fact]
public void Test3()
{
VerifyIsAssignableFrom("ArrayList", typeof(object[]).GetTypeInfo(), typeof(IList<object>).GetTypeInfo(), false);
}
[Fact]
public void Test4()
{
VerifyIsAssignableFrom("B&D", typeof(B).GetTypeInfo(), typeof(D).GetTypeInfo(), true);
}
[Fact]
public void Test5()
{
VerifyIsAssignableFrom("B[]&D[]", typeof(B[]).GetTypeInfo(), typeof(D[]).GetTypeInfo(), true);
}
[Fact]
public void Test6()
{
VerifyIsAssignableFrom("IList<object>&B[]", typeof(IList<object>).GetTypeInfo(), typeof(B[]).GetTypeInfo(), true);
}
[Fact]
public void Test7()
{
VerifyIsAssignableFrom("IList<B>*B[]", typeof(IList<B>).GetTypeInfo(), typeof(B[]).GetTypeInfo(), true);
}
[Fact]
public void Test8()
{
VerifyIsAssignableFrom("IList<B>&D[]", typeof(IList<B>).GetTypeInfo(), typeof(D[]).GetTypeInfo(), true);
}
[Fact]
public void Test9()
{
VerifyIsAssignableFrom("IList<D> & D[]", typeof(IList<D>).GetTypeInfo(), typeof(D[]).GetTypeInfo(), true);
}
[Fact]
public void Test10()
{
VerifyIsAssignableFrom("I<object>&G2<object>", typeof(I<object>).GetTypeInfo(), typeof(G2<object>).GetTypeInfo(), true);
}
[Fact]
public void Test11()
{
VerifyIsAssignableFrom("G<string>&G2<string>", typeof(G<string>).GetTypeInfo(), typeof(G2<string>).GetTypeInfo(), true);
}
[Fact]
public void Test12()
{
VerifyIsAssignableFrom("G<string>&G<string>", typeof(G<string>).GetTypeInfo(), typeof(G<string>).GetTypeInfo(), true);
}
[Fact]
public void Test13()
{
VerifyIsAssignableFrom("G<string>&G<object>", typeof(G<string>).GetTypeInfo(), typeof(G<object>).GetTypeInfo(), false);
}
[Fact]
public void Test14()
{
VerifyIsAssignableFrom("G<object>&G<stgring>", typeof(G<object>).GetTypeInfo(), typeof(G<string>).GetTypeInfo(), false);
}
[Fact]
public void Test15()
{
VerifyIsAssignableFrom("G2<object>&G<object>", typeof(G2<object>).GetTypeInfo(), typeof(G<object>).GetTypeInfo(), false);
}
[Fact]
public void Test16()
{
VerifyIsAssignableFrom("G<string>&I<String>", typeof(G<string>).GetTypeInfo(), typeof(I<string>).GetTypeInfo(), false);
}
[Fact]
public void Test17()
{
VerifyIsAssignableFrom("I2 I2", typeof(I2).GetTypeInfo(), typeof(I2).GetTypeInfo(), true);
}
[Fact]
public void Test18()
{
VerifyIsAssignableFrom("I2 B", typeof(I2).GetTypeInfo(), typeof(B).GetTypeInfo(), true);
}
[Fact]
public void Test19()
{
VerifyIsAssignableFrom("I2 D", typeof(I2).GetTypeInfo(), typeof(D).GetTypeInfo(), true);
}
[Fact]
public void Test20()
{
VerifyIsAssignableFrom("I2 Gen<>", typeof(I2).GetTypeInfo(), typeof(Gen<>).GetTypeInfo(), true);
}
[Fact]
public void Test21()
{
VerifyIsAssignableFrom("I2 Gen<string>", typeof(I2).GetTypeInfo(), typeof(Gen<string>).GetTypeInfo(), true);
}
[Fact]
public void Test22()
{
VerifyIsAssignableFrom("D I1", typeof(D).GetTypeInfo(), typeof(I1).GetTypeInfo(), false);
}
[Fact]
public void Test23()
{
TypeInfo gt = typeof(Gen2<>).GetGenericArguments()[0].GetTypeInfo();
VerifyIsAssignableFrom("I1 Gen2<>.GenericTypeArguments", typeof(I1).GetTypeInfo(), gt, true);
}
[Fact]
public void Test24()
{
TypeInfo gt = typeof(Gen2<>).GetGenericArguments()[0].GetTypeInfo();
}
[Fact]
public void Test25()
{
TypeInfo gt = typeof(Gen2<>).GetGenericArguments()[0].GetTypeInfo();
VerifyIsAssignableFrom("I2 Gen2<>.GenericTypeArguments", typeof(I2).GetTypeInfo(), gt, true);
}
[Fact]
public void Test26()
{
TypeInfo gt = typeof(Gen2<>).GetGenericArguments()[0].GetTypeInfo();
VerifyIsAssignableFrom("Gen<> Gen2<>.GenericTypeArguments", typeof(Gen<>).GetTypeInfo(), gt, false);
}
[Fact]
public void Test27()
{
VerifyIsAssignableFrom("Case500.A Case500.B", typeof(Case500.A).GetTypeInfo(), typeof(Case500.B).GetTypeInfo(), true);
}
[Fact]
public void Test28()
{
VerifyIsAssignableFrom("Case500.A Case500.C", typeof(Case500.A).GetTypeInfo(), typeof(Case500.C).GetTypeInfo(), true);
}
[Fact]
public void Test29()
{
VerifyIsAssignableFrom("Case500.B Case500.C", typeof(Case500.B).GetTypeInfo(), typeof(Case500.C).GetTypeInfo(), true);
}
[Fact]
public void Test30()
{
VerifyIsAssignableFrom("G10<>.GetGenericTypeArguments I1", typeof(G10<>).GetGenericArguments()[0].GetTypeInfo(), typeof(I1).GetTypeInfo(), false);
}
[Fact]
public void Test31()
{
VerifyIsAssignableFrom("G10<>.GetGenericTypeArguments B", typeof(G10<>).GetGenericArguments()[0].GetTypeInfo(), typeof(B).GetTypeInfo(), false);
}
[Fact]
public void Test32()
{
VerifyIsAssignableFrom("I1 G10<>.GetGenericTypeArguments", typeof(I1).GetTypeInfo(), typeof(G10<>).GetGenericArguments()[0].GetTypeInfo(), true);
}
[Fact]
public void Test33()
{
VerifyIsAssignableFrom("B G10<>.GetGenericTypeArguments", typeof(B).GetTypeInfo(), typeof(G10<>).GetGenericArguments()[0].GetTypeInfo(), false);
}
[Fact]
public void Test34()
{
VerifyIsAssignableFrom("I1 Gen2<>.GetGenericArguments", typeof(I1).GetTypeInfo(), typeof(Gen2<>).GetGenericArguments()[0].GetTypeInfo(), true);
}
[Fact]
public void Test35()
{
VerifyIsAssignableFrom("I2 Gen2<>.GetGenericArguments", typeof(I2).GetTypeInfo(), typeof(Gen2<>).GetGenericArguments()[0].GetTypeInfo(), true);
}
// a T[] is assignable to IList<U> iff T[] is assignable to U[]
[Fact]
public void Test36()
{
VerifyIsAssignableFrom("I1[] S[]", typeof(I1[]).GetTypeInfo(), typeof(S[]).GetTypeInfo(), false);
}
[Fact]
public void Test37()
{
VerifyIsAssignableFrom("I1[] D[]", typeof(I1[]).GetTypeInfo(), typeof(D[]).GetTypeInfo(), true);
}
[Fact]
public void Test38()
{
VerifyIsAssignableFrom("IList<I1> S[]", typeof(IList<I1>).GetTypeInfo(), typeof(S[]).GetTypeInfo(), false);
}
[Fact]
public void Test39()
{
VerifyIsAssignableFrom("IList<I1> D[]", typeof(IList<I1>).GetTypeInfo(), typeof(D[]).GetTypeInfo(), true);
}
[Fact]
public void Test40()
{
VerifyIsAssignableFrom("int[] uint[]", typeof(int[]).GetTypeInfo(), typeof(uint[]).GetTypeInfo(), true);
}
[Fact]
public void Test41()
{
VerifyIsAssignableFrom("uint[] int[]", typeof(uint[]).GetTypeInfo(), typeof(int[]).GetTypeInfo(), true);
}
[Fact]
public void Test42()
{
VerifyIsAssignableFrom("IList<int> uint[]", typeof(IList<int>).GetTypeInfo(), typeof(uint[]).GetTypeInfo(), true);
}
[Fact]
public void Test43()
{
VerifyIsAssignableFrom("IList<uint> int[]", typeof(IList<uint>).GetTypeInfo(), typeof(int[]).GetTypeInfo(), true);
}
private void VerifyIsAssignableFrom(String testName, TypeInfo left, TypeInfo right, Boolean expected)
{
Boolean actual = left.IsAssignableFrom(right);
Assert.Equal(expected, actual);
}
}
internal interface I1 { }
internal interface I2 { }
internal struct S : I1 { }
internal class B : I1, I2 { }
internal class D : B { }
internal class Gen<T> : D { }
internal class I<T> { }
internal class G<T> : I<T> { }
internal class G2<T> : G<T> { }
internal class Gen2<T> where T : Gen<T>, I1, I2 { }
namespace Case500
{
internal abstract class A { }
internal abstract class B : A { }
internal class C : B { }
}
internal class G10<T> where T : I1 { }
public class TransparentRC : ReflectionContext
{
public override Assembly MapAssembly(Assembly assembly)
{
return assembly;
}
public override TypeInfo MapType(TypeInfo type)
{
return type;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Azure.Data.Tables.Queryable
{
internal static class XmlConstants
{
internal const string ClrServiceInitializationMethodName = "InitializeService";
internal const string HttpContentID = "Content-ID";
internal const string HttpContentLength = "Content-Length";
internal const string HttpContentType = "Content-Type";
internal const string HttpContentDisposition = "Content-Disposition";
internal const string HttpDataServiceVersion = "DataServiceVersion";
internal const string HttpMaxDataServiceVersion = "MaxDataServiceVersion";
internal const string HttpCacheControlNoCache = "no-cache";
internal const string HttpCharsetParameter = "charset";
internal const string HttpMethodGet = "GET";
internal const string HttpMethodPost = "POST";
internal const string HttpMethodPut = "PUT";
internal const string HttpMethodDelete = "DELETE";
internal const string HttpMethodMerge = "MERGE";
internal const string HttpQueryStringExpand = "$expand";
internal const string HttpQueryStringFilter = "$filter";
internal const string HttpQueryStringOrderBy = "$orderby";
internal const string HttpQueryStringSkip = "$skip";
internal const string HttpQueryStringTop = "$top";
internal const string HttpQueryStringInlineCount = "$inlinecount";
internal const string HttpQueryStringSkipToken = "$skiptoken";
internal const string SkipTokenPropertyPrefix = "SkipTokenProperty";
internal const string HttpQueryStringValueCount = "$count";
internal const string HttpQueryStringSelect = "$select";
internal const string HttpQValueParameter = "q";
internal const string HttpXMethod = "X-HTTP-Method";
internal const string HttpRequestAccept = "Accept";
internal const string HttpRequestAcceptCharset = "Accept-Charset";
internal const string HttpRequestIfMatch = "If-Match";
internal const string HttpRequestIfNoneMatch = "If-None-Match";
internal const string HttpMultipartBoundary = "boundary";
internal const string HttpResponseAllow = "Allow";
internal const string HttpResponseCacheControl = "Cache-Control";
internal const string HttpResponseETag = "ETag";
internal const string HttpResponseLocation = "Location";
internal const string HttpResponseStatusCode = "Status-Code";
internal const string HttpMultipartBoundaryBatchResponse = "batchresponse";
internal const string HttpMultipartBoundaryChangesetResponse = "changesetresponse";
internal const string HttpContentTransferEncoding = "Content-Transfer-Encoding";
internal const string HttpVersionInBatching = "HTTP/1.1";
internal const string HttpAnyETag = "*";
internal const string HttpWeakETagPrefix = "W/\"";
internal const string HttpAcceptCharset = "Accept-Charset";
internal const string HttpCookie = "Cookie";
internal const string HttpSlug = "Slug";
internal const string MimeAny = "*/*";
internal const string MimeApplicationAtom = "application/atom+xml";
internal const string MimeApplicationAtomService = "application/atomsvc+xml";
internal const string MimeApplicationJson = "application/json";
internal const string MimeApplicationOctetStream = "application/octet-stream";
internal const string MimeApplicationHttp = "application/http";
internal const string MimeApplicationType = "application";
internal const string MimeApplicationXml = "application/xml";
internal const string MimeJsonSubType = "json";
internal const string MimeMetadata = MimeApplicationXml;
internal const string MimeMultiPartMixed = "multipart/mixed";
internal const string MimeTextPlain = "text/plain";
internal const string MimeTextType = "text";
internal const string MimeTextXml = "text/xml";
internal const string MimeXmlSubType = "xml";
internal const string BatchRequestContentTransferEncoding = "binary";
internal const string UriHttpAbsolutePrefix = "http://host";
internal const string UriMetadataSegment = "$metadata";
internal const string UriValueSegment = "$value";
internal const string UriBatchSegment = "$batch";
internal const string UriLinkSegment = "$links";
internal const string UriCountSegment = "$count";
internal const string UriRowCountAllOption = "allpages";
internal const string UriRowCountOffOption = "none";
internal const string WcfBinaryElementName = "Binary";
internal const string AtomContentElementName = "content";
internal const string AtomEntryElementName = "entry";
internal const string AtomFeedElementName = "feed";
internal const string MetadataAttributeEpmContentKind = "FC_ContentKind";
internal const string MetadataAttributeEpmKeepInContent = "FC_KeepInContent";
internal const string MetadataAttributeEpmNsPrefix = "FC_NsPrefix";
internal const string MetadataAttributeEpmNsUri = "FC_NsUri";
internal const string MetadataAttributeEpmTargetPath = "FC_TargetPath";
internal const string MetadataAttributeEpmSourcePath = "FC_SourcePath";
internal const string SyndAuthorEmail = "SyndicationAuthorEmail";
internal const string SyndAuthorName = "SyndicationAuthorName";
internal const string SyndAuthorUri = "SyndicationAuthorUri";
internal const string SyndPublished = "SyndicationPublished";
internal const string SyndRights = "SyndicationRights";
internal const string SyndSummary = "SyndicationSummary";
internal const string SyndTitle = "SyndicationTitle";
internal const string AtomUpdatedElementName = "updated";
internal const string SyndContributorEmail = "SyndicationContributorEmail";
internal const string SyndContributorName = "SyndicationContributorName";
internal const string SyndContributorUri = "SyndicationContributorUri";
internal const string SyndUpdated = "SyndicationUpdated";
internal const string SyndContentKindPlaintext = "text";
internal const string SyndContentKindHtml = "html";
internal const string SyndContentKindXHtml = "xhtml";
internal const string AtomHRefAttributeName = "href";
internal const string AtomSummaryElementName = "summary";
internal const string AtomNameElementName = "name";
internal const string AtomEmailElementName = "email";
internal const string AtomUriElementName = "uri";
internal const string AtomPublishedElementName = "published";
internal const string AtomRightsElementName = "rights";
internal const string AtomPublishingCollectionElementName = "collection";
internal const string AtomPublishingServiceElementName = "service";
internal const string AtomPublishingWorkspaceDefaultValue = "Default";
internal const string AtomPublishingWorkspaceElementName = "workspace";
internal const string AtomTitleElementName = "title";
internal const string AtomTypeAttributeName = "type";
internal const string AtomSelfRelationAttributeValue = "self";
internal const string AtomEditRelationAttributeValue = "edit";
internal const string AtomEditMediaRelationAttributeValue = "edit-media";
internal const string AtomNullAttributeName = "null";
internal const string AtomETagAttributeName = "etag";
internal const string AtomInlineElementName = "inline";
internal const string AtomPropertiesElementName = "properties";
internal const string RowCountElement = "count";
internal const string XmlCollectionItemElementName = "element";
internal const string XmlErrorElementName = "error";
internal const string XmlErrorCodeElementName = "code";
internal const string XmlErrorInnerElementName = "innererror";
internal const string XmlErrorInternalExceptionElementName = "internalexception";
internal const string XmlErrorTypeElementName = "type";
internal const string XmlErrorStackTraceElementName = "stacktrace";
internal const string XmlErrorMessageElementName = "message";
internal const string XmlFalseLiteral = "false";
internal const string XmlTrueLiteral = "true";
internal const string XmlInfinityLiteral = "INF";
internal const string XmlNaNLiteral = "NaN";
internal const string XmlBaseAttributeName = "base";
internal const string XmlLangAttributeName = "lang";
internal const string XmlSpaceAttributeName = "space";
internal const string XmlSpacePreserveValue = "preserve";
internal const string XmlBaseAttributeNameWithPrefix = "xml:base";
internal const string EdmV1Namespace = "http://schemas.microsoft.com/ado/2006/04/edm";
internal const string EdmV1dot1Namespace = "http://schemas.microsoft.com/ado/2007/05/edm";
internal const string EdmV1dot2Namespace = "http://schemas.microsoft.com/ado/2008/01/edm";
internal const string EdmV2Namespace = "http://schemas.microsoft.com/ado/2008/09/edm";
internal const string DataWebNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices";
internal const string DataWebMetadataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
internal const string DataWebRelatedNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/related/";
internal const string DataWebSchemeNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme";
internal const string AppNamespace = "http://www.w3.org/2007/app";
internal const string AtomNamespace = "http://www.w3.org/2005/Atom";
internal const string XmlnsNamespacePrefix = "xmlns";
internal const string XmlNamespacePrefix = "xml";
internal const string DataWebNamespacePrefix = "d";
internal const string DataWebMetadataNamespacePrefix = "m";
internal const string XmlNamespacesNamespace = "http://www.w3.org/2000/xmlns/";
internal const string EdmxNamespace = "http://schemas.microsoft.com/ado/2007/06/edmx";
internal const string EdmxNamespacePrefix = "edmx";
internal const string Association = "Association";
internal const string AssociationSet = "AssociationSet";
internal const string ComplexType = "ComplexType";
internal const string Dependent = "Dependent";
internal const string EdmCollectionTypeFormat = "Collection({0})";
internal const string EdmEntitySetAttributeName = "EntitySet";
internal const string EdmFunctionImportElementName = "FunctionImport";
internal const string EdmModeAttributeName = "Mode";
internal const string EdmModeInValue = "In";
internal const string EdmParameterElementName = "Parameter";
internal const string EdmReturnTypeAttributeName = "ReturnType";
internal const string End = "End";
internal const string EntityType = "EntityType";
internal const string EntityContainer = "EntityContainer";
internal const string Key = "Key";
internal const string NavigationProperty = "NavigationProperty";
internal const string OnDelete = "OnDelete";
internal const string Principal = "Principal";
internal const string Property = "Property";
internal const string PropertyRef = "PropertyRef";
internal const string ReferentialConstraint = "ReferentialConstraint";
internal const string Role = "Role";
internal const string Schema = "Schema";
internal const string EdmxElement = "Edmx";
internal const string EdmxDataServicesElement = "DataServices";
internal const string EdmxVersion = "Version";
internal const string EdmxVersionValue = "1.0";
internal const string Action = "Action";
internal const string BaseType = "BaseType";
internal const string EntitySet = "EntitySet";
internal const string FromRole = "FromRole";
internal const string Abstract = "Abstract";
internal const string Multiplicity = "Multiplicity";
internal const string Name = "Name";
internal const string Namespace = "Namespace";
internal const string ToRole = "ToRole";
internal const string Type = "Type";
internal const string Relationship = "Relationship";
internal const string Many = "*";
internal const string One = "1";
internal const string ZeroOrOne = "0..1";
internal const string Nullable = "Nullable";
internal const string ConcurrencyAttribute = "ConcurrencyMode";
internal const string ConcurrencyFixedValue = "Fixed";
internal const string DataWebMimeTypeAttributeName = "MimeType";
internal const string DataWebOpenTypeAttributeName = "OpenType";
internal const string DataWebAccessHasStreamAttribute = "HasStream";
internal const string DataWebAccessDefaultStreamPropertyValue = "true";
internal const string IsDefaultEntityContainerAttribute = "IsDefaultEntityContainer";
internal const string ServiceOperationHttpMethodName = "HttpMethod";
internal const string UriElementName = "uri";
internal const string NextElementName = "next";
internal const string LinkCollectionElementName = "links";
internal const string JsonError = "error";
internal const string JsonErrorCode = "code";
internal const string JsonErrorInner = "innererror";
internal const string JsonErrorInternalException = "internalexception";
internal const string JsonErrorMessage = "message";
internal const string JsonErrorStackTrace = "stacktrace";
internal const string JsonErrorType = "type";
internal const string JsonErrorValue = "value";
internal const string JsonMetadataString = "__metadata";
internal const string JsonUriString = "uri";
internal const string JsonTypeString = "type";
internal const string JsonEditMediaString = "edit_media";
internal const string JsonMediaSrcString = "media_src";
internal const string JsonContentTypeString = "content_type";
internal const string JsonMediaETagString = "media_etag";
internal const string JsonDeferredString = "__deferred";
internal const string JsonETagString = "etag";
internal const string JsonRowCountString = "__count";
internal const string JsonNextString = "__next";
internal const string EdmNamespace = "Edm";
internal const string EdmBinaryTypeName = "Edm.Binary";
internal const string EdmBooleanTypeName = "Edm.Boolean";
internal const string EdmByteTypeName = "Edm.Byte";
internal const string EdmDateTimeTypeName = "Edm.DateTime";
internal const string EdmDecimalTypeName = "Edm.Decimal";
internal const string EdmDoubleTypeName = "Edm.Double";
internal const string EdmGuidTypeName = "Edm.Guid";
internal const string EdmSingleTypeName = "Edm.Single";
internal const string EdmSByteTypeName = "Edm.SByte";
internal const string EdmInt16TypeName = "Edm.Int16";
internal const string EdmInt32TypeName = "Edm.Int32";
internal const string EdmInt64TypeName = "Edm.Int64";
internal const string EdmStringTypeName = "Edm.String";
internal const string DataServiceVersion1Dot0 = "1.0";
internal const string DataServiceVersion2Dot0 = "2.0";
internal const string DataServiceVersion3Dot0 = "3.0";
internal const string DataServiceVersionCurrent = DataServiceVersion3Dot0 + ";";
internal const int DataServiceVersionCurrentMajor = 1;
internal const int DataServiceVersionCurrentMinor = 0;
internal const string LiteralPrefixBinary = "binary";
internal const string LiteralPrefixDateTime = "datetime";
internal const string LiteralPrefixGuid = "guid";
internal const string XmlBinaryPrefix = "X";
internal const string XmlDecimalLiteralSuffix = "M";
internal const string XmlInt64LiteralSuffix = "L";
internal const string XmlSingleLiteralSuffix = "f";
internal const string XmlDoubleLiteralSuffix = "D";
internal const string NullLiteralInETag = "null";
internal const string MicrosoftDataServicesRequestUri = "MicrosoftDataServicesRequestUri";
internal const string MicrosoftDataServicesRootUri = "MicrosoftDataServicesRootUri";
internal const string StoreGeneratedPattern = "http://schemas.microsoft.com/ado/2006/04/edm/ssdl:StoreGeneratedPattern";
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System;
using System.IO;
public class Model_Importer : EditorWindow {
enum SOFTWARE {None,Maya,C4D,Blender,Other};
SOFTWARE _software;
Vector2 _scrollPos;
string [] subDirectoryEntries;
bool includeSubDir;
int dirID;
string _modelPath;
string fileName;
string destFolder;
string _assetPath;
ModelImporter importedModel;
UnityEngine.Object modelObj;
Texture2D modelPreview;
GUIStyle _style = new GUIStyle();
[MenuItem("Tools/Model Importer")]
static void Init () {
Model_Importer window = EditorWindow.GetWindow<Model_Importer>();
window.Show();
}
void OnGUI () {
_style.fontSize = 24;
if(EditorGUIUtility.isProSkin) _style.normal.textColor = Color.white;
else _style.normal.textColor = Color.black;
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.Space();
GUILayout.Label("Model Importer",_style);
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
_scrollPos = EditorGUILayout.BeginScrollView(_scrollPos);
if (_software==SOFTWARE.None) {
EditorGUILayout.HelpBox("Choose a software in order to import the model !",MessageType.Info);
}
EditorGUILayout.Space();
_software = (SOFTWARE)EditorGUILayout.EnumPopup("Software : ",_software);
EditorGUILayout.Space();
EditorGUI.BeginDisabledGroup (_software==SOFTWARE.None);
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.depth = -1;
if (_software != SOFTWARE.None) {
GUILayout.Label(GetLogo());
}
GUI.depth = 0;
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Model path : ", _modelPath);
EditorGUILayout.Space();
if (GUILayout.Button("Choose a file",GUILayout.MaxWidth(200), GUILayout.MinHeight(30))) {
_modelPath = EditorUtility.OpenFilePanel("Model to import : ","",GetExtension());
}
fileName = Path.GetFileName(_modelPath);
//TODO : Improve the condition. Without it, errors are thrown...
// ...filename throws NullReferenceException and subDirectoryEntries is out of range.
if (fileName != null && dirID <= subDirectoryEntries.Length) {
_assetPath = subDirectoryEntries[dirID] + "/" + fileName;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
if (includeSubDir) {
subDirectoryEntries = Directory.GetDirectories("Assets","*",SearchOption.AllDirectories);
} else {
subDirectoryEntries = Directory.GetDirectories("Assets");
}
for (int i=0; i<subDirectoryEntries.Length;i++) {
subDirectoryEntries[i] = subDirectoryEntries[i].Replace("\\","/");
}
dirID = EditorGUILayout.Popup("Destination Folder : ", dirID, subDirectoryEntries);
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
includeSubDir = EditorGUILayout.Toggle("Include all sub-folders ?", includeSubDir);
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.Space();
GUI.backgroundColor = Color.green;
if (GUILayout.Button("Import Model !",GUILayout.MinHeight(30))) {
if (!String.IsNullOrEmpty(_modelPath)) {
Debug.Log("Model name is " + fileName +" !");
if (!File.Exists(_assetPath)) {
FileUtil.CopyFileOrDirectory(_modelPath, _assetPath);
AssetDatabase.ImportAsset(_assetPath);
ModifyModel();
this.ShowNotification(new GUIContent("Model Successfully Imported !"));
} else {
this.ShowNotification(new GUIContent("The model already exists ! Choose another filename."));
}
} else {
this.ShowNotification(new GUIContent("Choose a model in order to import one !"));
}
}
GUI.backgroundColor = Color.white;
EditorGUILayout.Space();
EditorGUILayout.Space();
if (Resources.LoadAssetAtPath(_assetPath,typeof(UnityEngine.Object))) {
modelObj = Resources.LoadAssetAtPath(_assetPath,typeof(UnityEngine.Object)) as UnityEngine.Object;
modelPreview = AssetPreview.GetAssetPreview(modelObj);
} else {
modelPreview = null;
}
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label(modelPreview);
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.EndScrollView();
this.Repaint();
}
string GetExtension(){
string _softEXT;
switch(_software){
case SOFTWARE.Maya:
_softEXT = "*.mb";
break;
case SOFTWARE.C4D:
_softEXT = "*.c4d";
break;
case SOFTWARE.Blender:
_softEXT = "*.blend";
break;
default:
_softEXT = "";
break;
}
return _softEXT;
}
Texture2D GetLogo () {
Texture2D _softIMG;
switch(_software){
case SOFTWARE.Maya:
_softIMG = Resources.Load("mayaLogo") as Texture2D;
break;
case SOFTWARE.C4D:
_softIMG = Resources.Load("c4dLogo") as Texture2D;
break;
case SOFTWARE.Blender:
_softIMG = Resources.Load("blenderLogo") as Texture2D;
break;
default:
_softIMG = Resources.Load("otherLogo") as Texture2D;
break;
}
return _softIMG;
}
void ModifyModel () {
importedModel = ModelImporter.GetAtPath(_assetPath) as ModelImporter;
importedModel.globalScale = 1f;
importedModel.importMaterials = false;
AssetDatabase.ImportAsset(_assetPath);
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lambda-2015-03-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Lambda.Model
{
/// <summary>
/// Container for the parameters to the CreateFunction operation.
/// Creates a new Lambda function. The function metadata is created from the request parameters,
/// and the code for the function is provided by a .zip file in the request body. If the
/// function name already exists, the operation will fail. Note that the function name
/// is case-sensitive.
///
///
/// <para>
/// This operation requires permission for the <code>lambda:CreateFunction</code> action.
/// </para>
/// </summary>
public partial class CreateFunctionRequest : AmazonLambdaRequest
{
private FunctionCode _code;
private string _description;
private string _functionName;
private string _handler;
private int? _memorySize;
private bool? _publish;
private string _role;
private Runtime _runtime;
private int? _timeout;
/// <summary>
/// Gets and sets the property Code.
/// <para>
/// The code for the Lambda function.
/// </para>
/// </summary>
public FunctionCode Code
{
get { return this._code; }
set { this._code = value; }
}
// Check to see if Code property is set
internal bool IsSetCode()
{
return this._code != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// A short, user-defined function description. Lambda does not use this value. Assign
/// a meaningful description as you see fit.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property FunctionName.
/// <para>
/// The name you want to assign to the function you are uploading. You can specify an
/// unqualified function name (for example, "Thumbnail") or you can specify Amazon Resource
/// Name (ARN) of the function (for example, "arn:aws:lambda:us-west-2:account-id:function:ThumbNail").
/// AWS Lambda also allows you to specify only the account ID qualifier (for example,
/// "account-id:Thumbnail"). Note that the length constraint applies only to the ARN.
/// If you specify only the function name, it is limited to 64 character in length. The
/// function names appear in the console and are returned in the <a>ListFunctions</a>
/// API. Function names are used to specify functions to other AWS Lambda APIs, such as
/// <a>Invoke</a>.
/// </para>
/// </summary>
public string FunctionName
{
get { return this._functionName; }
set { this._functionName = value; }
}
// Check to see if FunctionName property is set
internal bool IsSetFunctionName()
{
return this._functionName != null;
}
/// <summary>
/// Gets and sets the property Handler.
/// <para>
/// The function within your code that Lambda calls to begin execution. For Node.js, it
/// is the <i>module-name</i>.<i>export</i> value in your function. For Java, it can be
/// <code>package.class-name::handler</code> or <code>package.class-name</code>. For more
/// information, see <a href="http://docs.aws.amazon.com/lambda/latest/dg/java-programming-model-handler-types.html">Lambda
/// Function Handler (Java)</a>.
/// </para>
/// </summary>
public string Handler
{
get { return this._handler; }
set { this._handler = value; }
}
// Check to see if Handler property is set
internal bool IsSetHandler()
{
return this._handler != null;
}
/// <summary>
/// Gets and sets the property MemorySize.
/// <para>
/// The amount of memory, in MB, your Lambda function is given. Lambda uses this memory
/// size to infer the amount of CPU and memory allocated to your function. Your function
/// use-case determines your CPU and memory requirements. For example, a database operation
/// might need less memory compared to an image processing function. The default value
/// is 128 MB. The value must be a multiple of 64 MB.
/// </para>
/// </summary>
public int MemorySize
{
get { return this._memorySize.GetValueOrDefault(); }
set { this._memorySize = value; }
}
// Check to see if MemorySize property is set
internal bool IsSetMemorySize()
{
return this._memorySize.HasValue;
}
/// <summary>
/// Gets and sets the property Publish.
/// <para>
/// This boolean parameter can be used to request AWS Lambda to create the Lambda function
/// and publish a version as an atomic operation.
/// </para>
/// </summary>
public bool Publish
{
get { return this._publish.GetValueOrDefault(); }
set { this._publish = value; }
}
// Check to see if Publish property is set
internal bool IsSetPublish()
{
return this._publish.HasValue;
}
/// <summary>
/// Gets and sets the property Role.
/// <para>
/// The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it executes
/// your function to access any other Amazon Web Services (AWS) resources. For more information,
/// see <a href="http://docs.aws.amazon.com/lambda/latest/dg/lambda-introduction.html">AWS
/// Lambda: How it Works</a>
/// </para>
/// </summary>
public string Role
{
get { return this._role; }
set { this._role = value; }
}
// Check to see if Role property is set
internal bool IsSetRole()
{
return this._role != null;
}
/// <summary>
/// Gets and sets the property Runtime.
/// <para>
/// The runtime environment for the Lambda function you are uploading. Currently, Lambda
/// supports "java" and "nodejs" as the runtime.
/// </para>
/// </summary>
public Runtime Runtime
{
get { return this._runtime; }
set { this._runtime = value; }
}
// Check to see if Runtime property is set
internal bool IsSetRuntime()
{
return this._runtime != null;
}
/// <summary>
/// Gets and sets the property Timeout.
/// <para>
/// The function execution time at which Lambda should terminate the function. Because
/// the execution time has cost implications, we recommend you set this value based on
/// your expected execution time. The default is 3 seconds.
/// </para>
/// </summary>
public int Timeout
{
get { return this._timeout.GetValueOrDefault(); }
set { this._timeout = value; }
}
// Check to see if Timeout property is set
internal bool IsSetTimeout()
{
return this._timeout.HasValue;
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Activities.Presentation.Internal.PropertyEditing.Editors
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Data;
using System.Runtime;
using System.Activities.Presentation.Model;
using System.Activities.Presentation.PropertyEditing;
using System.Activities.Presentation.Internal.PropertyEditing.FromExpression.Framework.PropertyInspector;
using System.Activities.Presentation.Internal.PropertyEditing.Automation;
using System.Activities.Presentation.Internal.PropertyEditing.Model;
using ModelUtilities = System.Activities.Presentation.Internal.PropertyEditing.Model.ModelUtilities;
using System.Activities.Presentation.Internal.PropertyEditing.Resources;
using System.Activities.Presentation.Internal.PropertyEditing.Selection;
using System.Activities.Presentation.Internal.PropertyEditing.State;
// <summary>
// We use the SubPropertyEditor to replace the entire property row
// when the property exposes its subproperties. This control is _not_
// just used within the value-editing portion of a property row.
// We cheat because we can.
// </summary>
internal class SubPropertyEditor : Control, INotifyPropertyChanged, ISelectionStop
{
// <summary>
// PropertyEntry is used to store the currently displayed PropertyEntry
// </summary>
public static readonly DependencyProperty PropertyEntryProperty = DependencyProperty.Register(
"PropertyEntry",
typeof(PropertyEntry),
typeof(SubPropertyEditor),
new PropertyMetadata(null, new PropertyChangedCallback(OnPropertyEntryChanged)));
// <summary>
// Boolean used to indicate whether the sub-properties are being shown or not. As an optimization,
// we don't actually expose the PropertyValue's sub-properties through SelectiveSubProperties until
// the sub-property expando-pane has been open at least once.
// </summary>
public static readonly DependencyProperty IsExpandedProperty = DependencyProperty.Register(
"IsExpanded",
typeof(bool),
typeof(SubPropertyEditor),
new PropertyMetadata(false, new PropertyChangedCallback(OnIsExpandedChanged)));
// <summary>
// Exposes the currently selected QuickType in the QuickType drop-down. Essentially,
// the value of this DP is plumbed through to reflect the value of _quickTypeView.CurrentItem
// </summary>
public static readonly DependencyProperty CurrentQuickTypeProperty = DependencyProperty.Register(
"CurrentQuickType",
typeof(NewItemFactoryTypeModel),
typeof(SubPropertyEditor),
new PropertyMetadata(null, new PropertyChangedCallback(OnCurrentQuickTypeChanged)));
private ICollectionView _quickTypeView;
private ObservableCollection<NewItemFactoryTypeModel> _quickTypeCollection;
private bool _ignoreInternalChanges;
private bool _exposedSubProperties;
private ItemsControl _subPropertyListControl;
// <summary>
// Basic ctor
// </summary>
public SubPropertyEditor()
{
_quickTypeCollection = new ObservableCollection<NewItemFactoryTypeModel>();
_quickTypeView = CollectionViewSource.GetDefaultView(_quickTypeCollection);
_quickTypeView.CurrentChanged += new EventHandler(OnCurrentQuickTypeChanged);
}
// Automation
public event PropertyChangedEventHandler PropertyChanged;
// Internal event we fire for the sake of SubPropertyEditorAutomationPeer that
// causes it to refresh its offered set of children
internal event EventHandler VisualsChanged;
public PropertyEntry PropertyEntry
{
get { return (PropertyEntry)this.GetValue(PropertyEntryProperty); }
set { this.SetValue(PropertyEntryProperty, value); }
}
public bool IsExpanded
{
get { return (bool)this.GetValue(IsExpandedProperty); }
set { this.SetValue(IsExpandedProperty, value); }
}
public NewItemFactoryTypeModel CurrentQuickType
{
get { return (NewItemFactoryTypeModel)this.GetValue(CurrentQuickTypeProperty); }
set { this.SetValue(CurrentQuickTypeProperty, value); }
}
// <summary>
// Gets a flag indicating whether QuickTypes exist
// </summary>
public bool HasQuickTypes
{
get {
return _quickTypeCollection.Count > 0;
}
}
// <summary>
// Returns a list of available QuickTypes (collection of NewItemFactoryTypeModel instances)
// </summary>
public ICollectionView QuickTypes
{
get {
return _quickTypeView;
}
}
// <summary>
// Exposes PropertyValue.SubProperties when the IsExpanded flag first gets set to true
// and forever thereafter (or at least until the current PropertyValue changes and we
// collapse the sub-properties)
// </summary>
public IEnumerable<PropertyEntry> SelectiveSubProperties
{
get {
if (!_exposedSubProperties)
{
if (!this.IsExpanded)
{
yield break;
}
_exposedSubProperties = true;
}
PropertyEntry parent = this.PropertyEntry;
if (parent == null)
{
yield break;
}
foreach (ModelPropertyEntry subProperty in parent.PropertyValue.SubProperties)
{
if (subProperty.IsBrowsable)
{
yield return subProperty;
}
}
}
}
// <summary>
// Gets a flag indicating whether the sub-property editor can be expanded or not.
// </summary>
public bool IsExpandable
{
get { return this.HasQuickTypes && this.CurrentQuickType != null; }
}
// <summary>
// Gets a SelectionPath to itself.
// </summary>
public SelectionPath Path
{
get { return PropertySelectionPathInterpreter.Instance.ConstructSelectionPath(this.PropertyEntry); }
}
// <summary>
// Gets a description of the contained property
// to expose through automation
// </summary>
public string Description
{
get {
PropertyEntry property = this.PropertyEntry;
if (property != null)
{
return string.Format(
CultureInfo.CurrentCulture,
Properties.Resources.PropertyEditing_SelectionStatus_Property,
this.PropertyEntry.PropertyName);
}
return string.Empty;
}
}
// <summary>
// Exposes the ItemsControl used to display the list of sub-properties. UI-specific
// </summary>
private ItemsControl SubPropertyListControl
{
get {
if (_subPropertyListControl == null)
{
_subPropertyListControl = VisualTreeUtils.GetNamedChild<ItemsControl>(this, "PART_SubPropertyList");
Fx.Assert(_subPropertyListControl != null, "UI for SubPropertyEditor changed. Need to update SubPropertyEditor class logic.");
}
return _subPropertyListControl;
}
}
// Keyboard Navigation
protected override AutomationPeer OnCreateAutomationPeer()
{
return new SubPropertyEditorAutomationPeer(this);
}
// Properties
// PropertyEntry DP
// When the displayed PropertyEntry changes, make sure we update the UI and hook into the
// new PropertyEntry's notification mechanism
private static void OnPropertyEntryChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
SubPropertyEditor theThis = obj as SubPropertyEditor;
if (theThis == null)
{
return;
}
PropertyEntry oldValue = e.OldValue as PropertyEntry;
if (oldValue != null)
{
oldValue.PropertyValue.RootValueChanged -= new EventHandler(theThis.OnPropertyValueRootValueChanged);
}
PropertyEntry newValue = e.NewValue as PropertyEntry;
if (newValue != null)
{
newValue.PropertyValue.RootValueChanged += new EventHandler(theThis.OnPropertyValueRootValueChanged);
}
theThis.RefreshVisuals();
}
private void OnPropertyValueRootValueChanged(object sender, EventArgs e)
{
if (_ignoreInternalChanges)
{
return;
}
RefreshVisuals();
}
// IsExpanded DP
private static void OnIsExpandedChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
SubPropertyEditor theThis = obj as SubPropertyEditor;
if (theThis == null)
{
return;
}
bool newIsExpanded = (bool)e.NewValue;
PropertyEntry containedProperty = theThis.PropertyEntry;
// Store the new expansion state
if (containedProperty != null)
{
PropertyState state = PropertyStateContainer.Instance.GetPropertyState(
ModelUtilities.GetCachedSubPropertyHierarchyPath(containedProperty));
state.SubPropertiesExpanded = newIsExpanded;
}
// If we are expanded but we never exposed the sub-properties to anyone before,
// fire a signal saying that a list of sub-properties may be now available, so that
// UI DataBindings refresh themselves
if (newIsExpanded == true &&
theThis._exposedSubProperties == false)
{
theThis.FireSubPropertiesListChangedEvents();
}
}
// CurrentQuickType DP
// This method gets called when the DP changes
private static void OnCurrentQuickTypeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
SubPropertyEditor theThis = obj as SubPropertyEditor;
if (theThis == null)
{
return;
}
if (theThis._ignoreInternalChanges)
{
return;
}
theThis._quickTypeView.MoveCurrentTo(e.NewValue);
theThis.ExpandSubProperties();
theThis.FireSubPropertiesListChangedEvents();
}
// This method gets called when the CurrentItem on _quickTypeView changes
private void OnCurrentQuickTypeChanged(object sender, EventArgs e)
{
if (_ignoreInternalChanges)
{
return;
}
NewItemFactoryTypeModel selectedTypeModel = _quickTypeView.CurrentItem as NewItemFactoryTypeModel;
if (selectedTypeModel == null)
{
return;
}
Fx.Assert(this.PropertyEntry != null, "PropertyEntry should not be null");
if (this.PropertyEntry == null)
{
return;
}
bool previousValue = IgnoreInternalChanges();
try
{
this.PropertyEntry.PropertyValue.Value = selectedTypeModel.CreateInstance();
}
finally
{
NoticeInternalChanges(previousValue);
}
}
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
if (e.Property == PropertyContainer.OwningPropertyContainerProperty)
{
// A quick and dirty way to register this instance as the implementation of
// ISelectionBranchPoint that controls the expansion / collapse of this control
//
OnOwningPropertyContainerChanged((PropertyContainer)e.OldValue, (PropertyContainer)e.NewValue);
}
base.OnPropertyChanged(e);
}
private void OnOwningPropertyContainerChanged(PropertyContainer oldValue, PropertyContainer newValue)
{
if (oldValue != null)
{
PropertySelection.ClearSelectionStop(oldValue);
PropertySelection.ClearIsSelectionStopDoubleClickTarget(oldValue);
}
if (newValue != null)
{
PropertySelection.SetSelectionStop(newValue, this);
PropertySelection.SetIsSelectionStopDoubleClickTarget(newValue, true);
}
}
// Visual Lookup Helpers
// <summary>
// Looks for and returns the specified sub-property
// </summary>
// <param name="propertyName">Sub-property to look up</param>
// <returns>Corresponding PropertyEntry if found, null otherwise.</returns>
internal PropertyEntry FindSubPropertyEntry(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
{
return null;
}
foreach (PropertyEntry property in SelectiveSubProperties)
{
if (property.PropertyName.Equals(propertyName))
{
return property;
}
}
return null;
}
// <summary>
// Looks for and returns the PropertyContainer used to display
// the specified PropertyEntry
// </summary>
// <param name="property">Property to look for</param>
// <returns>Corresponding PropertyContainer if found, null otherwise.</returns>
internal PropertyContainer FindSubPropertyEntryVisual(PropertyEntry property)
{
if (property == null)
{
return null;
}
ItemsControl subPropertyListControl = this.SubPropertyListControl;
if (subPropertyListControl == null)
{
return null;
}
return subPropertyListControl.ItemContainerGenerator.ContainerFromItem(property) as PropertyContainer;
}
// Helpers
private void RefreshVisuals()
{
RefreshQuickTypes();
RestoreIsExpandedState();
FireVisualsChangedEvents();
}
private void RefreshQuickTypes()
{
bool previousValue = IgnoreInternalChanges();
try
{
_quickTypeCollection.Clear();
PropertyEntry containedProperty = this.PropertyEntry;
if (containedProperty == null)
{
return;
}
ModelProperty property = ((ModelPropertyEntry)containedProperty).FirstModelProperty;
Type containerValueType = ((ModelPropertyEntryBase)containedProperty).CommonValueType;
NewItemFactoryTypeModel selectedFactoryModel = null;
Type defaultItemType = GetDefaultItemType(property);
// Find all elligible NewItemFactoryTypes declared through metadata
IEnumerable<NewItemFactoryTypeModel> factoryModels =
ExtensibilityAccessor.GetNewItemFactoryTypeModels(
property,
ResourceUtilities.GetDesiredTypeIconSize(this));
if (factoryModels != null)
{
foreach (NewItemFactoryTypeModel factoryModel in factoryModels)
{
_quickTypeCollection.Add(factoryModel);
if (selectedFactoryModel == null)
{
if (object.Equals(containerValueType, factoryModel.Type))
{
selectedFactoryModel = factoryModel;
}
}
if (defaultItemType != null &&
object.Equals(defaultItemType, factoryModel.Type))
{
defaultItemType = null;
}
}
}
//add a null value - user should always have an option to clear property value
NewItemFactoryTypeModel nullTypeFactoryTypeModel =
new NewItemFactoryTypeModel(null, new NullItemFactory());
// Add a default item type based on the property type (if it wasn't also added through
// metadata)
if (defaultItemType != null)
{
NewItemFactoryTypeModel defaultItemFactoryTypeModel = new NewItemFactoryTypeModel(defaultItemType, new NewItemFactory());
_quickTypeCollection.Add(defaultItemFactoryTypeModel);
if (selectedFactoryModel == null)
{
if (object.Equals(containerValueType, defaultItemFactoryTypeModel.Type))
{
selectedFactoryModel = defaultItemFactoryTypeModel;
}
else if (containerValueType == null)
{
selectedFactoryModel = nullTypeFactoryTypeModel;
}
}
}
_quickTypeCollection.Add(nullTypeFactoryTypeModel);
// Make sure the currently selected value on the CollectionView reflects the
// actual value of the property
_quickTypeView.MoveCurrentTo(selectedFactoryModel);
this.CurrentQuickType = selectedFactoryModel;
}
finally
{
NoticeInternalChanges(previousValue);
}
}
private static Type GetDefaultItemType(ModelProperty property)
{
if (property == null)
{
return null;
}
Type propertyType = property.PropertyType;
if (EditorUtilities.IsConcreteWithDefaultCtor(propertyType))
{
return propertyType;
}
return null;
}
private void RestoreIsExpandedState()
{
bool newIsExpanded = false;
PropertyEntry property = this.PropertyEntry;
if (property != null)
{
PropertyState state = PropertyStateContainer.Instance.GetPropertyState(
ModelUtilities.GetCachedSubPropertyHierarchyPath(property));
newIsExpanded = state.SubPropertiesExpanded;
}
this.IsExpanded = newIsExpanded;
_exposedSubProperties = false;
}
private void ExpandSubProperties()
{
this.IsExpanded = true;
}
// Change Notification Helpers
private bool IgnoreInternalChanges()
{
bool previousValue = _ignoreInternalChanges;
_ignoreInternalChanges = true;
return previousValue;
}
private void NoticeInternalChanges(bool previousValue)
{
_ignoreInternalChanges = previousValue;
}
private void FireVisualsChangedEvents()
{
// Fire updated events
OnPropertyChanged("HasQuickTypes");
OnPropertyChanged("QuickTypes");
FireSubPropertiesListChangedEvents();
}
private void FireSubPropertiesListChangedEvents()
{
OnPropertyChanged("IsExpandable");
OnPropertyChanged("SelectiveSubProperties");
if (VisualsChanged != null)
{
VisualsChanged(this, EventArgs.Empty);
}
}
// INotifyPropertyChanged Members
private void OnPropertyChanged(string propertyName)
{
Fx.Assert(!string.IsNullOrEmpty(propertyName), "Can't raise OnPropertyChanged event without a valid property name.");
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
// ISelectionStop Members
//NullItemFactory - this class is used to provide a null entry in quick types list - it is required to allow user
//to clear value of an object.
sealed class NullItemFactory : NewItemFactory
{
public override object CreateInstance(Type type)
{
//no input type is allowed - we never create instance of anything
Fx.Assert(type == null, "NullItemFactory supports only null as type parameter");
return null;
}
public override string GetDisplayName(Type type)
{
//no input type is allowed - we always return (null) string
Fx.Assert(type == null, "NullItemFactory supports only null as type parameter");
return "(null)";
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace NotifyProcessingSample
{
[TemplateVisualState(Name = "Large", GroupName = "SizeStates")]
[TemplateVisualState(Name = "Small", GroupName = "SizeStates")]
[TemplateVisualState(Name = "Inactive", GroupName = "ActiveStates")]
[TemplateVisualState(Name = "Active", GroupName = "ActiveStates")]
public class ProgressRing : Control
{
public static readonly DependencyProperty BindableWidthProperty = DependencyProperty.Register("BindableWidth", typeof(double), typeof(ProgressRing), new PropertyMetadata(default(double), BindableWidthCallback));
public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register("IsActive", typeof(bool), typeof(ProgressRing), new PropertyMetadata(true, IsActiveChanged));
public static readonly DependencyProperty IsLargeProperty = DependencyProperty.Register("IsLarge", typeof(bool), typeof(ProgressRing), new PropertyMetadata(true, IsLargeChangedCallback));
public static readonly DependencyProperty MaxSideLengthProperty = DependencyProperty.Register("MaxSideLength", typeof(double), typeof(ProgressRing), new PropertyMetadata(default(double)));
public static readonly DependencyProperty EllipseDiameterProperty = DependencyProperty.Register("EllipseDiameter", typeof(double), typeof(ProgressRing), new PropertyMetadata(default(double)));
public static readonly DependencyProperty EllipseOffsetProperty = DependencyProperty.Register("EllipseOffset", typeof(Thickness), typeof(ProgressRing), new PropertyMetadata(default(Thickness)));
public static readonly DependencyProperty EllipseDiameterScaleProperty = DependencyProperty.Register("EllipseDiameterScale", typeof(double), typeof(ProgressRing), new PropertyMetadata(1D));
private List<Action> _deferredActions = new List<Action>();
static ProgressRing()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ProgressRing), new FrameworkPropertyMetadata(typeof(ProgressRing)));
VisibilityProperty.OverrideMetadata(typeof(ProgressRing),
new FrameworkPropertyMetadata(
new PropertyChangedCallback(
(ringObject, e) => {
if (e.NewValue != e.OldValue) {
var ring = (ProgressRing)ringObject;
//auto set IsActive to false if we're hiding it.
if ((Visibility)e.NewValue != Visibility.Visible) {
//sets the value without overriding it's binding (if any).
ring.SetCurrentValue(ProgressRing.IsActiveProperty, false);
} else {
// #1105 don't forget to re-activate
ring.IsActive = true;
}
}
})));
}
public ProgressRing()
{
SizeChanged += OnSizeChanged;
}
public double MaxSideLength
{
get { return (double)GetValue(MaxSideLengthProperty); }
private set { SetValue(MaxSideLengthProperty, value); }
}
public double EllipseDiameter
{
get { return (double)GetValue(EllipseDiameterProperty); }
private set { SetValue(EllipseDiameterProperty, value); }
}
public double EllipseDiameterScale
{
get { return (double)GetValue(EllipseDiameterScaleProperty); }
set { SetValue(EllipseDiameterScaleProperty, value); }
}
public Thickness EllipseOffset
{
get { return (Thickness)GetValue(EllipseOffsetProperty); }
private set { SetValue(EllipseOffsetProperty, value); }
}
public double BindableWidth
{
get { return (double)GetValue(BindableWidthProperty); }
private set { SetValue(BindableWidthProperty, value); }
}
public bool IsActive
{
get { return (bool)GetValue(IsActiveProperty); }
set { SetValue(IsActiveProperty, value); }
}
public bool IsLarge
{
get { return (bool)GetValue(IsLargeProperty); }
set { SetValue(IsLargeProperty, value); }
}
private static void BindableWidthCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var ring = dependencyObject as ProgressRing;
if (ring == null)
return;
var action = new Action(() =>
{
ring.SetEllipseDiameter(
(double) dependencyPropertyChangedEventArgs.NewValue);
ring.SetEllipseOffset(
(double) dependencyPropertyChangedEventArgs.NewValue);
ring.SetMaxSideLength(
(double) dependencyPropertyChangedEventArgs.NewValue);
});
if (ring._deferredActions != null)
ring._deferredActions.Add(action);
else
action();
}
private void SetMaxSideLength(double width)
{
MaxSideLength = width <= 20 ? 20 : width;
}
private void SetEllipseDiameter(double width)
{
EllipseDiameter =(width / 8)*EllipseDiameterScale;
}
private void SetEllipseOffset(double width)
{
EllipseOffset = new Thickness(0, width / 2, 0, 0);
}
private static void IsLargeChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var ring = dependencyObject as ProgressRing;
if (ring == null)
return;
ring.UpdateLargeState();
}
private void UpdateLargeState()
{
Action action;
if (IsLarge)
action = () => VisualStateManager.GoToState(this, "Large", true);
else
action = () => VisualStateManager.GoToState(this, "Small", true);
if (_deferredActions != null)
_deferredActions.Add(action);
else
action();
}
private void OnSizeChanged(object sender, SizeChangedEventArgs sizeChangedEventArgs)
{
BindableWidth = ActualWidth;
}
private static void IsActiveChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var ring = dependencyObject as ProgressRing;
if (ring == null)
return;
ring.UpdateActiveState();
}
private void UpdateActiveState()
{
Action action;
if (IsActive)
action = () => VisualStateManager.GoToState(this, "Active", true);
else
action = () => VisualStateManager.GoToState(this, "Inactive", true);
if (_deferredActions != null)
_deferredActions.Add(action);
else
action();
}
public override void OnApplyTemplate()
{
//make sure the states get updated
UpdateLargeState();
UpdateActiveState();
base.OnApplyTemplate();
if (_deferredActions != null)
foreach (var action in _deferredActions)
action();
_deferredActions = null;
}
}
internal class WidthToMaxSideLengthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is double)
{
var width = (double)value;
return width <= 20 ? 20 : width;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="EntityViewGenerator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Metadata.Edm;
using System.Data.Mapping;
using System.Data.EntityClient;
using System.Data.EntityModel;
using System.Data.Common.CommandTrees;
using System.Reflection;
using System.Security.Cryptography;
using System.Data.Entity.Design.Common;
using System.Diagnostics;
using System.Globalization;
using System.Data.Common.Utils;
using Microsoft.Build.Utilities;
using System.Runtime.Versioning;
using System.Linq;
namespace System.Data.Entity.Design
{
/// <summary>
/// EntityViewGenerator class produces the views for the extents in the passed in StorageMappingItemCollection.
/// The views are written as code to the passed in output stream. There are a set of options that user
/// can use to control the code generation process. The options should be apssed into the constrcutor.
/// While storing the views in the code, the view generator class also stores a Hash value produced based
/// on the content of the views and the names of extents. We also generate a hash for each schema file( csdl, ssdl and msl)
/// that was used in view generation process and store the hash in the generated code.The entity runtime will try to discover this
/// type and if it does discover it will use the generated views in this type. The discovery process is
/// explained in detail in the comments for StorageMappingItemCollection class.
/// The runtime will throw an exception if any of the the hash values produced in the design time does not match
/// the hash values produced at the runtime.
/// </summary>
public class EntityViewGenerator
{
#region Constructors
/// <summary>
/// Create the instance of ViewGenerator with the given language option.
/// </summary>
/// <param name="languageOption">Language Option for generated code.</param>
public EntityViewGenerator(LanguageOption languageOption)
{
m_languageOption = EDesignUtil.CheckLanguageOptionArgument(languageOption, "languageOption");
}
/// <summary>
/// Create the instance of ViewGenerator using C# as the default
/// language option.
/// </summary>
public EntityViewGenerator()
: this(LanguageOption.GenerateCSharpCode)
{
}
#endregion
#region Fields
private LanguageOption m_languageOption;
private static readonly int MAXONELINELENGTH = 2046;
private static readonly int ONELINELENGTH = 80;
private static readonly int ERRORCODE_MAPPINGALLQUERYVIEWATCOMPILETIME = 2088;
#endregion
#region Properties
/// <summary>
/// Language Option for generated code.
/// </summary>
public LanguageOption LanguageOption
{
get { return m_languageOption; }
set { m_languageOption = EDesignUtil.CheckLanguageOptionArgument(value, "value"); }
}
#endregion
#region Methods
/// <summary>
/// Generates the views for the extents in the mapping item collection and produces
/// the code for a type that will cache these views. The methods also produces
/// a hash based on the StorageEntityContainerMapping, which contains all the
/// metadata and mapping. It also produces a hash based
/// on the view content and the name of the extents.
/// </summary>
/// <param name="mappingCollection">Mapping Item Collection for which views should be generated</param>
/// <param name="outputUri">Uri to which generated code needs to be written</param>
[ResourceExposure(ResourceScope.Machine)] //Exposes the outputPath as part of ConnectionString which are a Machine resource.
[ResourceConsumption(ResourceScope.Machine)] //For StreamWriter constructor call. But the path to the stream is not created in this method.
[CLSCompliant(false)]
public IList<EdmSchemaError> GenerateViews(StorageMappingItemCollection mappingCollection, string outputPath)
{
EDesignUtil.CheckArgumentNull(mappingCollection, "mappingCollection");
EDesignUtil.CheckStringArgument(outputPath, "outputPath");
TextWriter outputWriter = null;
try
{
return InternalGenerateViews(mappingCollection, () => new StreamWriter(outputPath), out outputWriter);
}
finally
{
if (outputWriter != null)
{
outputWriter.Dispose();
}
}
}
/// <summary>
/// Generates the views for the extents in the mapping item collection and produces
/// the code for a type that will cache these views. The methods also produces
/// a hash based on the storageEntityContainerMapping object, which contains all the
/// metadata and mapping. It also produces a hash based
/// on the view content and the name of the extents.
/// </summary>
/// <param name="mappingCollection">Mapping Item Collection for which views should be generated</param>
/// <param name="outputWriter">Output writer to which we want to write the code</param>
[CLSCompliant(false)]
public IList<EdmSchemaError> GenerateViews(StorageMappingItemCollection mappingCollection, TextWriter outputWriter)
{
EDesignUtil.CheckArgumentNull(mappingCollection, "mappingCollection");
Version targetEntityFrameworkVersion;
IList<EdmSchemaError> errorList = GetMinimumTargetFrameworkVersion(mappingCollection, out targetEntityFrameworkVersion);
return GenerateViews(mappingCollection, outputWriter, targetEntityFrameworkVersion).Concat(errorList).ToList();
}
/// <summary>
/// Generates the views for the extents in the mapping item collection and produces
/// the code for a type that will cache these views. The methods also produces
/// a hash based on the storageEntityContainerMapping object, which contains all the
/// metadata and mapping. It also produces a hash based
/// on the view content and the name of the extents.
/// </summary>
/// <param name="mappingCollection">Mapping Item Collection for which views should be generated</param>
/// <param name="outputWriter">Output writer to which we want to write the code</param>
[CLSCompliant(false)]
public IList<EdmSchemaError> GenerateViews(StorageMappingItemCollection mappingCollection, TextWriter outputWriter, Version targetEntityFrameworkVersion)
{
EDesignUtil.CheckArgumentNull(mappingCollection, "mappingCollection");
EDesignUtil.CheckArgumentNull(outputWriter, "outputWriter");
EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");
CheckForCompatibleSchemaAndTarget(mappingCollection, targetEntityFrameworkVersion);
TextWriter writer;
return InternalGenerateViews(mappingCollection, () => outputWriter, out writer);
}
private static void CheckForCompatibleSchemaAndTarget(StorageMappingItemCollection mappingCollection, Version targetEntityFrameworkVersion)
{
Version mappingVersion = EntityFrameworkVersionsUtil.ConvertToVersion(mappingCollection.MappingVersion);
if (targetEntityFrameworkVersion < mappingVersion)
{
throw EDesignUtil.Argument(Strings.TargetVersionSchemaVersionMismatch(targetEntityFrameworkVersion, mappingVersion), null);
}
Version edmVersion = EntityFrameworkVersionsUtil.ConvertToVersion(mappingCollection.EdmItemCollection.EdmVersion);
if (targetEntityFrameworkVersion < edmVersion)
{
throw EDesignUtil.Argument(Strings.TargetVersionSchemaVersionMismatch(targetEntityFrameworkVersion, edmVersion), null);
}
}
private IList<EdmSchemaError> InternalGenerateViews(
StorageMappingItemCollection mappingCollection,
Func<TextWriter> GetWriter,
out TextWriter outputWriter)
{
IList<EdmSchemaError> schemaErrors;
CodeDomProvider provider;
Dictionary<EntitySetBase, string> generatedViews;
if (GetViewsWithErrors(mappingCollection, out provider, out schemaErrors, out generatedViews))
{
outputWriter = null;
return schemaErrors;
}
outputWriter = GetWriter();
GenerateAndStoreViews(mappingCollection, generatedViews,
outputWriter, provider, schemaErrors);
return schemaErrors;
}
/// <summary>
/// Validates the mappingCollections and returns the schemaErrors.
/// </summary>
/// <param name="mappingCollection"></param>
/// <returns>list of EdmSchemaError</returns>
[CLSCompliant(false)]
public static IList<EdmSchemaError> Validate(StorageMappingItemCollection mappingCollection)
{
EDesignUtil.CheckArgumentNull(mappingCollection, "mappingCollection");
Version targetEntityFrameworkVersion;
IList<EdmSchemaError> errorList = GetMinimumTargetFrameworkVersion(mappingCollection, out targetEntityFrameworkVersion);
return Validate(mappingCollection, targetEntityFrameworkVersion).Concat(errorList).ToList();
}
/// <summary>
/// Validates the mappingCollections and returns the schemaErrors.
/// </summary>
/// <param name="mappingCollection"></param>
/// <returns>list of EdmSchemaError</returns>
[CLSCompliant(false)]
public static IList<EdmSchemaError> Validate(StorageMappingItemCollection mappingCollection, Version targetEntityFrameworkVersion)
{
EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");
CheckForCompatibleSchemaAndTarget(mappingCollection, targetEntityFrameworkVersion);
// purpose of this API is to validate the mappingCollection, it basically will call GetEntitySetViews
EDesignUtil.CheckArgumentNull(mappingCollection, "mappingCollection");
// we need a temp var to to pass it to GetViews (since we will directly invoke GetViews)
Dictionary<EntitySetBase, string> generatedViews;
// mappingCollection will be validated and schemaErrors will be returned from GetViews API
IList<EdmSchemaError> schemaErrors;
// Validate entity set views.
GetEntitySetViews(mappingCollection, out schemaErrors, out generatedViews);
// Validate function imports and their mapping.
foreach (var containerMapping in mappingCollection.GetItems<StorageEntityContainerMapping>())
{
foreach (var functionImport in containerMapping.EdmEntityContainer.FunctionImports)
{
FunctionImportMapping functionImportMapping;
if (containerMapping.TryGetFunctionImportMapping(functionImport, out functionImportMapping))
{
if (functionImport.IsComposableAttribute)
{
((FunctionImportMappingComposable)functionImportMapping).ValidateFunctionView(schemaErrors);
}
}
else
{
schemaErrors.Add(new EdmSchemaError(
Strings.UnmappedFunctionImport(functionImport.Identity),
(int)StorageMappingErrorCode.UnmappedFunctionImport,
EdmSchemaErrorSeverity.Warning));
}
}
}
Debug.Assert(schemaErrors != null, "schemaErrors is null");
return HandleValidationErrors(schemaErrors);
}
private static IList<EdmSchemaError> HandleValidationErrors(IList<EdmSchemaError> schemaErrors)
{
IEnumerable<EdmSchemaError> warningsToRemove =
schemaErrors.Where(s =>
s.ErrorCode == ERRORCODE_MAPPINGALLQUERYVIEWATCOMPILETIME); // When EntityContainerMapping only has QueryView, the mapping is valid
return schemaErrors.Except(warningsToRemove).ToList();
}
private bool GetViewsWithErrors(StorageMappingItemCollection mappingCollection, out CodeDomProvider provider, out IList<EdmSchemaError> schemaErrors, out Dictionary<EntitySetBase, string> generatedViews)
{
GetViewsAndCodeDomProvider(mappingCollection, out provider, out schemaErrors, out generatedViews);
//If the generated views are empty because of errors or warnings, then don't create an output file.
if (generatedViews.Count == 0 && schemaErrors.Count > 0)
{
return true;
}
return false;
}
private void GetViewsAndCodeDomProvider(StorageMappingItemCollection mappingCollection, out CodeDomProvider provider, out IList<EdmSchemaError> schemaErrors, out Dictionary<EntitySetBase, string> generatedViews)
{
//Create a CodeDomProvider based on options.
provider = null;
switch (m_languageOption)
{
case LanguageOption.GenerateCSharpCode:
provider = new Microsoft.CSharp.CSharpCodeProvider();
break;
case LanguageOption.GenerateVBCode:
provider = new Microsoft.VisualBasic.VBCodeProvider();
break;
}
//Get the views for the Entity Sets and Association Sets in the mapping item collection
GetEntitySetViews(mappingCollection, out schemaErrors, out generatedViews);
}
private static void GetEntitySetViews(StorageMappingItemCollection mappingCollection,
out IList<EdmSchemaError> schemaErrors, out Dictionary<EntitySetBase, string> generatedViews)
{
generatedViews = mappingCollection.GenerateEntitySetViews(out schemaErrors);
}
private static IList<EdmSchemaError> GetMinimumTargetFrameworkVersion(StorageMappingItemCollection mappingCollection, out Version targetFrameworkVersion)
{
List<EdmSchemaError> errorList = new List<EdmSchemaError>();
targetFrameworkVersion = EntityFrameworkVersionsUtil.ConvertToVersion(mappingCollection.EdmItemCollection.EdmVersion);
if (targetFrameworkVersion > EntityFrameworkVersions.Default)
{
errorList.Add(new EdmSchemaError(Strings.DefaultTargetVersionTooLow(EntityFrameworkVersions.Default, targetFrameworkVersion), (int)System.Data.Entity.Design.SsdlGenerator.ModelBuilderErrorCode.SchemaVersionHigherThanTargetVersion, EdmSchemaErrorSeverity.Warning));
}
return errorList;
}
/// <summary>
/// Generates the code to store the views in a C# or a VB file based on the
/// options passed in by the user.
/// </summary>
/// <param name="mappingCollection"></param>
/// <param name="generatedViews"></param>
/// <param name="sourceWriter"></param>
/// <param name="provider"></param>
/// <returns></returns>
private static void GenerateAndStoreViews(StorageMappingItemCollection mappingCollection,
Dictionary<EntitySetBase, string> generatedViews, TextWriter sourceWriter, CodeDomProvider provider, IList<EdmSchemaError> schemaErrors)
{
EdmItemCollection edmCollection = mappingCollection.EdmItemCollection;
StoreItemCollection storeCollection = mappingCollection.StoreItemCollection;
//Create an emtpty compile unit and build up the generated code
CodeCompileUnit compileUnit = new CodeCompileUnit();
//Add the namespace for generated code
CodeNamespace codeNamespace = new CodeNamespace(EntityViewGenerationConstants.NamespaceName);
//Add copyright notice to the namespace comment.
compileUnit.Namespaces.Add(codeNamespace);
foreach (var storageEntityContainerMapping in mappingCollection.GetItems<StorageEntityContainerMapping>())
{
//Throw warning when containerMapping contains query view for bug 547285.
if (HasQueryView(storageEntityContainerMapping))
{
schemaErrors.Add(new EdmSchemaError(
Strings.UnsupportedQueryViewInEntityContainerMapping(storageEntityContainerMapping.Identity),
(int)StorageMappingErrorCode.UnsupportedQueryViewInEntityContainerMapping,
EdmSchemaErrorSeverity.Warning));
continue;
}
#region Class Declaration
string edmContainerName = storageEntityContainerMapping.EdmEntityContainer.Name;
string storeContainerName = storageEntityContainerMapping.StorageEntityContainer.Name;
string hashOverMappingClosure = MetadataMappingHasherVisitor.GetMappingClosureHash(edmCollection.EdmVersion, storageEntityContainerMapping);
StringBuilder inputForTypeNameContent = new StringBuilder(hashOverMappingClosure);
string viewStorageTypeName = EntityViewGenerationConstants.ViewGenerationTypeNamePrefix + StringHashBuilder.ComputeHash(MetadataHelper.CreateMetadataHashAlgorithm(edmCollection.EdmVersion), inputForTypeNameContent.ToString()).ToUpperInvariant();
//Add typeof expression to get the type that contains ViewGen type. This will help us in avoiding to go through
//all the types in the assembly. I have also verified that this works with VB with a root namespace prepended to the
//namespace since VB is picking up the type correctly as long as it is in the same assembly even with out the root namespace.
CodeTypeOfExpression viewGenTypeOfExpression = new CodeTypeOfExpression(EntityViewGenerationConstants.NamespaceName + "." + viewStorageTypeName);
//Add the assembly attribute that marks the assembly as the one that contains the generated views
CodeAttributeDeclaration viewGenAttribute = new CodeAttributeDeclaration(EntityViewGenerationConstants.ViewGenerationCustomAttributeName);
CodeAttributeArgument viewGenTypeArgument = new CodeAttributeArgument(viewGenTypeOfExpression);
viewGenAttribute.Arguments.Add(viewGenTypeArgument);
compileUnit.AssemblyCustomAttributes.Add(viewGenAttribute);
//Add the type which will be the class that contains all the views in this assembly
CodeTypeDeclaration viewStoringType = CreateTypeForStoringViews(viewStorageTypeName);
//Add the constructor, this will be the only method that this type will contain
//Create empty constructor.
CodeConstructor viewStoringTypeConstructor = CreateConstructorForViewStoringType();
viewStoringType.Attributes = MemberAttributes.Public;
//Get an expression that expresses this instance
CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression();
string viewHash = MetadataHelper.GenerateHashForAllExtentViewsContent(edmCollection.EdmVersion, GenerateDictionaryForEntitySetNameAndView(generatedViews));
CodeAssignStatement EdmEntityContainerNameStatement =
new CodeAssignStatement(
new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.EdmEntityContainerName),
new CodePrimitiveExpression(edmContainerName));
CodeAssignStatement StoreEntityContainerNameStatement =
new CodeAssignStatement(
new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.StoreEntityContainerName),
new CodePrimitiveExpression(storeContainerName));
CodeAssignStatement HashOverMappingClosureStatement =
new CodeAssignStatement(
new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.HashOverMappingClosure),
new CodePrimitiveExpression(hashOverMappingClosure));
CodeAssignStatement HashOverAllExtentViewsStatement =
new CodeAssignStatement(
new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.HashOverAllExtentViews),
new CodePrimitiveExpression(viewHash));
CodeAssignStatement ViewCountStatement =
new CodeAssignStatement(
new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.ViewCountPropertyName),
new CodePrimitiveExpression(generatedViews.Count));
viewStoringTypeConstructor.Statements.Add(EdmEntityContainerNameStatement);
viewStoringTypeConstructor.Statements.Add(StoreEntityContainerNameStatement);
viewStoringTypeConstructor.Statements.Add(HashOverMappingClosureStatement);
viewStoringTypeConstructor.Statements.Add(HashOverAllExtentViewsStatement);
viewStoringTypeConstructor.Statements.Add(ViewCountStatement);
//Add the constructor to the type
viewStoringType.Members.Add(viewStoringTypeConstructor);
//Add the method to store views to the type
CreateAndAddGetViewAtMethod(viewStoringType, generatedViews);
//Add the type to the namespace
codeNamespace.Types.Add(viewStoringType);
#endregion
}
if (codeNamespace.Types.Count > 0)
{
GenerateCode(sourceWriter, provider, compileUnit);
sourceWriter.Flush();
}
}
private static bool HasQueryView(StorageEntityContainerMapping storageEntityContainerMapping)
{
foreach (EntitySetBase extent in storageEntityContainerMapping.EdmEntityContainer.BaseEntitySets)
{
if (storageEntityContainerMapping.HasQueryViewForSetMap(extent.Name))
{
return true;
}
}
return false;
}
private static Dictionary<string, string> GenerateDictionaryForEntitySetNameAndView(Dictionary<EntitySetBase, string> dictionary)
{
Dictionary<string, string> newDictionary = new Dictionary<string, string>();
foreach (var item in dictionary)
{
newDictionary.Add(GetExtentFullName(item.Key), item.Value);
}
return newDictionary;
}
/// <summary>
/// Write code to the given stream from the compile unit.
/// </summary>
/// <param name="sourceWriter"></param>
/// <param name="provider"></param>
/// <param name="compileUnit"></param>
private static void GenerateCode(TextWriter sourceWriter, CodeDomProvider provider, CodeCompileUnit compileUnit)
{
CodeGeneratorOptions styleOptions = new CodeGeneratorOptions();
styleOptions.BracingStyle = "C";
styleOptions.BlankLinesBetweenMembers = true;
styleOptions.VerbatimOrder = true;
provider.GenerateCodeFromCompileUnit(compileUnit, sourceWriter, styleOptions);
}
/// <summary>
/// Generate Code to put the views in the generated code.
/// </summary>
/// <param name="typeDeclaration"></param>
/// <param name="generatedViews"></param>
/// <returns></returns>
private static void CreateAndAddGetViewAtMethod(CodeTypeDeclaration typeDeclaration, Dictionary<EntitySetBase, string> generatedViews)
{
//Add the views to a method
CodeMemberMethod getViewAtMethod = new CodeMemberMethod();
getViewAtMethod.Name = EntityViewGenerationConstants.GetViewAtMethodName;
getViewAtMethod.ReturnType = new CodeTypeReference(typeof(KeyValuePair<,>).MakeGenericType(new Type[] { typeof(string), typeof(string) }));
CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "index");
getViewAtMethod.Parameters.Add(parameter);
getViewAtMethod.Comments.Add(new CodeCommentStatement(EntityViewGenerationConstants.SummaryStartElement, true /*docComment*/));
getViewAtMethod.Comments.Add(new CodeCommentStatement(Strings.GetViewAtMethodComments, true /*docComment*/));
getViewAtMethod.Comments.Add(new CodeCommentStatement(EntityViewGenerationConstants.SummaryEndElement, true /*docComment*/));
getViewAtMethod.Attributes = MemberAttributes.Family | MemberAttributes.Override;
typeDeclaration.Members.Add(getViewAtMethod);
int index = 0;
CodeVariableReferenceExpression indexParameterReference = new CodeVariableReferenceExpression(getViewAtMethod.Parameters[0].Name);
foreach (KeyValuePair<EntitySetBase, string> generatedViewPair in generatedViews)
{
// the CodeDom does not support the following scenarios
// 1. switch statement
// 2. if(){} else if(){}
// The original design here was to have the following code,
// if() { else { if(){} } }
// but this had some drawbacks as described in TFS workitem 590996
// Given the not supported scenarios in CodeDom, we choose only use if statement in this case
// if(index == 0)
CodeConditionStatement currentIf = new CodeConditionStatement(new CodeBinaryOperatorExpression(
indexParameterReference, CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(index)));
getViewAtMethod.Statements.Add(currentIf);
EntitySetBase entitySet = generatedViewPair.Key;
string extentFullName = GetExtentFullName(entitySet);
CodeMemberMethod viewMethod = CreateViewReturnMethod(extentFullName, index, generatedViewPair.Value);
typeDeclaration.Members.Add(viewMethod);
// return GetNorthwindContext_Customers();
CodeMethodReturnStatement returnViewMethodCall = new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(null, viewMethod.Name)));
currentIf.TrueStatements.Add(returnViewMethodCall);
index++;
}
// if an invalid index is asked for throw
getViewAtMethod.Statements.Add(new CodeThrowExceptionStatement(
new CodeObjectCreateExpression(new CodeTypeReference(typeof(IndexOutOfRangeException)))));
}
private static CodeMemberMethod CreateViewReturnMethod(string extentFullName, int index, string viewText)
{
//Add the views to a method
CodeMemberMethod viewMethod = new CodeMemberMethod();
viewMethod.Name = "GetView" + index.ToString(CultureInfo.InvariantCulture);
viewMethod.Attributes = MemberAttributes.Private;
viewMethod.ReturnType = new CodeTypeReference(typeof(KeyValuePair<,>).MakeGenericType(new Type[] { typeof(string), typeof(string) }));
viewMethod.Comments.Add(new CodeCommentStatement(EntityViewGenerationConstants.SummaryStartElement, true /*docComment*/));
viewMethod.Comments.Add(new CodeCommentStatement(Strings.IndividualViewComments(extentFullName), true /*docComment*/));
viewMethod.Comments.Add(new CodeCommentStatement(EntityViewGenerationConstants.SummaryEndElement, true /*docComment*/));
CodeExpression viewTextExpression;
// only use the StringBuilder if we have to.
if (viewText.Length > MAXONELINELENGTH)
{
CreateSizedStringBuilder(viewMethod.Statements, viewText.Length);
foreach (var appendExpression in GetAppendViewStringsExpressions(viewText))
{
// viewString.Append(xxx);
viewMethod.Statements.Add(appendExpression);
}
viewTextExpression = new CodeMethodInvokeExpression(GetViewStringBuilderVariable(), "ToString");
}
else
{
viewTextExpression = new CodePrimitiveExpression(viewText);
}
// return new System.Collections.Generic.KeyValuePair<string, string>("dbo.Products", viewString.ToString());
// or
// return new System.Collections.Generic.KeyValuePair<string, string>("dbo.Products", "SELECT value c...");
CodeObjectCreateExpression newExpression =
new CodeObjectCreateExpression(
viewMethod.ReturnType,
new CodePrimitiveExpression(extentFullName),
viewTextExpression);
viewMethod.Statements.Add(new CodeMethodReturnStatement(newExpression));
return viewMethod;
}
private static void CreateSizedStringBuilder(CodeStatementCollection statements, int capacity)
{
// StringBuilder viewString = new StringBuilder(237);
CodeVariableDeclarationStatement viewStringDeclaration = new CodeVariableDeclarationStatement(typeof(StringBuilder), "viewString");
CodeObjectCreateExpression viewStringConstruct = new CodeObjectCreateExpression(typeof(StringBuilder), new CodePrimitiveExpression(capacity));
viewStringDeclaration.InitExpression = viewStringConstruct;
statements.Add(viewStringDeclaration);
}
private static IEnumerable<string> SplitViewStrings(string largeViewString)
{
for (int i = 0; i <= largeViewString.Length / ONELINELENGTH; i++)
{
if (i * ONELINELENGTH + ONELINELENGTH < largeViewString.Length)
{
yield return largeViewString.Substring(i * ONELINELENGTH, ONELINELENGTH);
}
else
{
// the very last part of the splited string
yield return largeViewString.Substring(i * ONELINELENGTH);
}
}
}
private static IEnumerable<CodeMethodInvokeExpression> GetViewStringsAppendToStringBuilder(
params string[] viewStrings)
{
foreach (var viewString in viewStrings)
{
// viewString.Append("xxx");
yield return AppendStringToStringBuilder(GetViewStringBuilderVariable(), viewString);
}
}
private static CodeVariableReferenceExpression GetViewStringBuilderVariable()
{
return new CodeVariableReferenceExpression("viewString");
}
private static CodeMethodInvokeExpression AppendStringToStringBuilder(
CodeVariableReferenceExpression stringBuilder, string stringToAppend)
{
return new CodeMethodInvokeExpression(
stringBuilder, "Append", new CodePrimitiveExpression(stringToAppend));
}
private static IEnumerable<CodeMethodInvokeExpression> GetAppendViewStringsExpressions(string viewString)
{
if (viewString.Length > MAXONELINELENGTH)
{
// if the string is longer than 2046 charactors, we splitted them in to 80 each
// and append them using StringBuilder
return GetViewStringsAppendToStringBuilder(SplitViewStrings(viewString).ToArray<string>());
}
else
{
return GetViewStringsAppendToStringBuilder(viewString);
}
}
private static string GetExtentFullName(EntitySetBase entitySet)
{
//We store the full Extent Name in the generated code which is
//EntityContainer name + "." + entitysetName
return entitySet.EntityContainer.Name + EntityViewGenerationConstants.QualificationCharacter + entitySet.Name;
}
/// <summary>
/// Get the constructor for the type that will contain the generated views
/// </summary>
/// <returns></returns>
private static CodeConstructor CreateConstructorForViewStoringType()
{
CodeConstructor constructor = new CodeConstructor();
//Mark it as public
constructor.Attributes = MemberAttributes.Public;
//Add constructor comments
constructor.Comments.Add(new CodeCommentStatement(EntityViewGenerationConstants.SummaryStartElement, true /*docComment*/));
constructor.Comments.Add(new CodeCommentStatement(Strings.ConstructorComments, true /*docComment*/));
constructor.Comments.Add(new CodeCommentStatement(EntityViewGenerationConstants.SummaryEndElement, true /*docComment*/));
return constructor;
}
/// <summary>
/// Get the type declaration for the type that will contain the views.
/// </summary>
/// <returns></returns>
private static CodeTypeDeclaration CreateTypeForStoringViews(string viewStorageTypeName)
{
CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(viewStorageTypeName);
typeDecl.TypeAttributes = TypeAttributes.Sealed | TypeAttributes.Public;
//This type should derive from the framework type EntityViewContainer which reduces the amount
//of generated code
typeDecl.BaseTypes.Add(EntityViewGenerationConstants.BaseTypeName);
//Add type comments
typeDecl.Comments.Add(new CodeCommentStatement(EntityViewGenerationConstants.SummaryStartElement, true /*docComment*/));
typeDecl.Comments.Add(new CodeCommentStatement(Strings.TypeComments, true /*docComment*/));
typeDecl.Comments.Add(new CodeCommentStatement(EntityViewGenerationConstants.SummaryEndElement, true /*docComment*/));
return typeDecl;
}
#endregion
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2014-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describe a Spot Instance request.
/// </summary>
public partial class SpotInstanceRequest
{
private string _availabilityZoneGroup;
private DateTime? _createTime;
private SpotInstanceStateFault _fault;
private string _instanceId;
private string _launchedAvailabilityZone;
private string _launchGroup;
private LaunchSpecification _launchSpecification;
private RIProductDescription _productDescription;
private string _spotInstanceRequestId;
private string _spotPrice;
private SpotInstanceState _state;
private SpotInstanceStatus _status;
private List<Tag> _tags = new List<Tag>();
private SpotInstanceType _type;
private DateTime? _validFrom;
private DateTime? _validUntil;
/// <summary>
/// Gets and sets the property AvailabilityZoneGroup.
/// <para>
/// The Availability Zone group. If you specify the same Availability Zone group for all
/// Spot Instance requests, all Spot Instances are launched in the same Availability Zone.
/// </para>
/// </summary>
public string AvailabilityZoneGroup
{
get { return this._availabilityZoneGroup; }
set { this._availabilityZoneGroup = value; }
}
// Check to see if AvailabilityZoneGroup property is set
internal bool IsSetAvailabilityZoneGroup()
{
return this._availabilityZoneGroup != null;
}
/// <summary>
/// Gets and sets the property CreateTime.
/// <para>
/// The time stamp when the Spot Instance request was created.
/// </para>
/// </summary>
public DateTime CreateTime
{
get { return this._createTime.GetValueOrDefault(); }
set { this._createTime = value; }
}
// Check to see if CreateTime property is set
internal bool IsSetCreateTime()
{
return this._createTime.HasValue;
}
/// <summary>
/// Gets and sets the property Fault.
/// <para>
/// The fault codes for the Spot Instance request, if any.
/// </para>
/// </summary>
public SpotInstanceStateFault Fault
{
get { return this._fault; }
set { this._fault = value; }
}
// Check to see if Fault property is set
internal bool IsSetFault()
{
return this._fault != null;
}
/// <summary>
/// Gets and sets the property InstanceId.
/// <para>
/// The instance ID, if an instance has been launched to fulfill the Spot Instance request.
/// </para>
/// </summary>
public string InstanceId
{
get { return this._instanceId; }
set { this._instanceId = value; }
}
// Check to see if InstanceId property is set
internal bool IsSetInstanceId()
{
return this._instanceId != null;
}
/// <summary>
/// Gets and sets the property LaunchedAvailabilityZone.
/// <para>
/// The Availability Zone in which the bid is launched.
/// </para>
/// </summary>
public string LaunchedAvailabilityZone
{
get { return this._launchedAvailabilityZone; }
set { this._launchedAvailabilityZone = value; }
}
// Check to see if LaunchedAvailabilityZone property is set
internal bool IsSetLaunchedAvailabilityZone()
{
return this._launchedAvailabilityZone != null;
}
/// <summary>
/// Gets and sets the property LaunchGroup.
/// <para>
/// The instance launch group. Launch groups are Spot Instances that launch together and
/// terminate together.
/// </para>
/// </summary>
public string LaunchGroup
{
get { return this._launchGroup; }
set { this._launchGroup = value; }
}
// Check to see if LaunchGroup property is set
internal bool IsSetLaunchGroup()
{
return this._launchGroup != null;
}
/// <summary>
/// Gets and sets the property LaunchSpecification.
/// <para>
/// Additional information for launching instances.
/// </para>
/// </summary>
public LaunchSpecification LaunchSpecification
{
get { return this._launchSpecification; }
set { this._launchSpecification = value; }
}
// Check to see if LaunchSpecification property is set
internal bool IsSetLaunchSpecification()
{
return this._launchSpecification != null;
}
/// <summary>
/// Gets and sets the property ProductDescription.
/// <para>
/// The product description associated with the Spot Instance.
/// </para>
/// </summary>
public RIProductDescription ProductDescription
{
get { return this._productDescription; }
set { this._productDescription = value; }
}
// Check to see if ProductDescription property is set
internal bool IsSetProductDescription()
{
return this._productDescription != null;
}
/// <summary>
/// Gets and sets the property SpotInstanceRequestId.
/// <para>
/// The ID of the Spot Instance request.
/// </para>
/// </summary>
public string SpotInstanceRequestId
{
get { return this._spotInstanceRequestId; }
set { this._spotInstanceRequestId = value; }
}
// Check to see if SpotInstanceRequestId property is set
internal bool IsSetSpotInstanceRequestId()
{
return this._spotInstanceRequestId != null;
}
/// <summary>
/// Gets and sets the property SpotPrice.
/// <para>
/// The maximum hourly price (bid) for any Spot Instance launched to fulfill the request.
/// </para>
/// </summary>
public string SpotPrice
{
get { return this._spotPrice; }
set { this._spotPrice = value; }
}
// Check to see if SpotPrice property is set
internal bool IsSetSpotPrice()
{
return this._spotPrice != null;
}
/// <summary>
/// Gets and sets the property State.
/// <para>
/// The state of the Spot Instance request. Spot bid status information can help you track
/// your Spot Instance requests. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html">Spot
/// Bid Status</a> in the <i>Amazon Elastic Compute Cloud User Guide for Linux</i>.
/// </para>
/// </summary>
public SpotInstanceState State
{
get { return this._state; }
set { this._state = value; }
}
// Check to see if State property is set
internal bool IsSetState()
{
return this._state != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The status code and status message describing the Spot Instance request.
/// </para>
/// </summary>
public SpotInstanceStatus Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// Any tags assigned to the resource.
/// </para>
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property Type.
/// <para>
/// The Spot Instance request type.
/// </para>
/// </summary>
public SpotInstanceType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
/// <summary>
/// Gets and sets the property ValidFrom.
/// <para>
/// The start date of the request. If this is a one-time request, the request becomes
/// active at this date and time and remains active until all instances launch, the request
/// expires, or the request is canceled. If the request is persistent, the request becomes
/// active at this date and time and remains active until it expires or is canceled.
/// </para>
/// </summary>
public DateTime ValidFrom
{
get { return this._validFrom.GetValueOrDefault(); }
set { this._validFrom = value; }
}
// Check to see if ValidFrom property is set
internal bool IsSetValidFrom()
{
return this._validFrom.HasValue;
}
/// <summary>
/// Gets and sets the property ValidUntil.
/// <para>
/// The end date of the request. If this is a one-time request, the request remains active
/// until all instances launch, the request is canceled, or this date is reached. If the
/// request is persistent, it remains active until it is canceled or this date is reached.
/// </para>
/// </summary>
public DateTime ValidUntil
{
get { return this._validUntil.GetValueOrDefault(); }
set { this._validUntil = value; }
}
// Check to see if ValidUntil property is set
internal bool IsSetValidUntil()
{
return this._validUntil.HasValue;
}
}
}
| |
/*******************************************************************************
*
* Copyright (C) 2013-2014 Frozen North Computing
*
* 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.Drawing;
using System.Collections.Generic;
#if FN2D_WIN
using OpenTK.Graphics.OpenGL;
#elif FN2D_IOS || FN2D_AND
using OpenTK.Graphics.ES11;
using BeginMode = OpenTK.Graphics.ES11.All;
#endif
namespace FrozenNorth.OpenGL.FN2D
{
public class FN2DLineStrips : List<FN2DArrays>, IDisposable
{
// instance variables
private Color lineColor;
private int lineWidth;
private PointF lastPoint = PointF.Empty;
/// <summary>
/// Constructor - Creates an empty set of line strips.
/// </summary>
/// <param name="lineColor">Line color.</param>
/// <param name="lineWidth">Line width.</param>
public FN2DLineStrips(Color lineColor, int lineWidth = 1)
: base()
{
// save the parameters
this.lineColor = lineColor;
this.lineWidth = lineWidth;
}
/// <summary>
/// Destructor - Calls Dispose().
/// </summary>
~FN2DLineStrips()
{
Dispose(false);
}
/// <summary>
/// Releases all resource used by the object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Frees unmanaged resources and calls Dispose() on the member objects.
/// </summary>
protected virtual void Dispose(bool disposing)
{
// if we got here via Dispose(), call Dispose() on the member objects
if (disposing)
{
Clear();
}
}
/// <summary>
/// Gets the current/last line strip.
/// </summary>
public FN2DArrays LineStrip
{
get { return (Count != 0) ? this[Count - 1] : null; }
}
public new void Remove(FN2DArrays lineStrip)
{
if (lineStrip != null)
{
lineStrip.Dispose();
base.Remove(lineStrip);
}
}
/// <summary>
/// Adds a line strip.
/// </summary>
public void Add()
{
if (Count == 0 || this[Count - 1].NumVertices != 0)
{
Add(FN2DArrays.Create(BeginMode.LineStrip));
}
}
/// <summary>
/// Adds a point.
/// </summary>
/// <param name="x">The point's X coordinate.</param>
/// <param name="y">The point's Y coordinate.</param>
public void Add(float x, float y)
{
FN2DArrays lineStrip = LineStrip;
if (lineStrip == null)
{
lineStrip = FN2DArrays.Create(BeginMode.LineStrip);
Add(lineStrip);
}
lineStrip.AddVertex(x, y);
lastPoint.X = x;
lastPoint.Y = y;
}
/// <summary>
/// Adds a point.
/// </summary>
/// <param name="point">Point to be added.</param>
public void Add(PointF point)
{
Add(point.X, point.Y);
}
/// <summary>
/// Adds a point.
/// </summary>
/// <param name="point">Point to be added.</param>
public void Add(Point point)
{
Add(point.X, point.Y);
}
/// <summary>
/// Adds a line.
/// </summary>
/// <param name="x1">The start point's X coordinate.</param>
/// <param name="y1">The start point's Y coordinate.</param>
/// <param name="x2">The end point's X coordinate.</param>
/// <param name="y2">The end point's Y coordinate.</param>
public void Add(float x1, float y1, float x2, float y2)
{
FN2DArrays lineStrip = LineStrip;
if (lineStrip == null || (lineStrip.NumVertices != 0 && (lastPoint.X != x1 || lastPoint.Y != y1)))
{
lineStrip = FN2DArrays.Create(BeginMode.LineStrip);
lineStrip.AddVertex(x1, y1);
Add(lineStrip);
}
lineStrip.AddVertex(x2, y2);
lastPoint.X = x2;
lastPoint.Y = y2;
}
/// <summary>
/// Adds a line.
/// </summary>
/// <param name="fromPoint">Start point of the line.</param>
/// <param name="toPoint">End point of the line.</param>
public void Add(PointF fromPoint, PointF toPoint)
{
Add(fromPoint.X, fromPoint.Y, toPoint.X, toPoint.Y);
}
/// <summary>
/// Adds a line.
/// </summary>
/// <param name="fromPoint">Start point of the line.</param>
/// <param name="toPoint">End point of the line.</param>
public void Add(Point fromPoint, Point toPoint)
{
Add(fromPoint.X, fromPoint.Y, toPoint.X, toPoint.Y);
}
/// <summary>
/// Removes all existing line strips.
/// </summary>
public new void Clear()
{
foreach (FN2DArrays lineStrip in this)
{
lineStrip.Dispose();
}
base.Clear();
}
/// <summary>
/// Draws the line.
/// </summary>
public virtual void Draw()
{
// set the line color
if (lineColor.R != 0 || lineColor.G != 0 || lineColor.B != 0)
GL.Color4(lineColor.R, lineColor.G, lineColor.B, lineColor.A);
else
GL.Color4(1, 1, 1, 255);
// set the line width
GL.LineWidth(lineWidth);
// draw the line strips
foreach (FN2DArrays lineStrip in this)
{
lineStrip.Draw();
}
}
}
/// <summary>
/// OpenGL 2D list of line strips.
/// </summary>
public class FN2DLineStripsList : List<FN2DLineStrips> {}
}
| |
// 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.Reflection;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Infrastructure.Common;
using Xunit;
public class DuplexChannelFactoryTest
{
[WcfFact]
public static void CreateChannel_EndpointAddress_Null_Throws()
{
WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
InstanceContext context = new InstanceContext(callback);
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.None;
EndpointAddress remoteAddress = null;
DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, remoteAddress);
try
{
Assert.Throws<InvalidOperationException>(() =>
{
factory.Open();
factory.CreateChannel();
});
}
finally
{
factory.Abort();
}
}
[WcfFact]
public static void CreateChannel_InvalidEndpointAddress_AsString_ThrowsUriFormat()
{
WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
InstanceContext context = new InstanceContext(callback);
Binding binding = new NetTcpBinding();
Assert.Throws<UriFormatException>(() =>
{
DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, "invalid");
});
}
[WcfFact]
public static void CreateChannel_EmptyEndpointAddress_AsString_ThrowsUriFormat()
{
WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
InstanceContext context = new InstanceContext(callback);
Binding binding = new NetTcpBinding();
Assert.Throws<UriFormatException>(() =>
{
DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, string.Empty);
});
}
[WcfFact]
// valid address, but the scheme is incorrect
public static void CreateChannel_ExpectedNetTcpScheme_HttpScheme_ThrowsUriFormat()
{
WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
InstanceContext context = new InstanceContext(callback);
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.None;
Assert.Throws<ArgumentException>("via", () =>
{
DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, "http://not-the-right-scheme");
factory.CreateChannel();
});
}
[WcfFact]
// valid address, but the scheme is incorrect
public static void CreateChannel_ExpectedNetTcpScheme_InvalidScheme_ThrowsUriFormat()
{
WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
InstanceContext context = new InstanceContext(callback);
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.None;
Assert.Throws<ArgumentException>("via", () =>
{
DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, "qwerty://not-the-right-scheme");
factory.CreateChannel();
});
}
[WcfFact]
// valid address, but the scheme is incorrect
public static void CreateChannel_BasicHttpBinding_Throws_InvalidOperation()
{
WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
InstanceContext context = new InstanceContext(callback);
Binding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
// Contract requires Duplex, but Binding 'BasicHttpBinding' doesn't support it or isn't configured properly to support it.
var exception = Assert.Throws<InvalidOperationException>(() =>
{
DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, "http://basichttp-not-duplex");
factory.CreateChannel();
});
Assert.True(exception.Message.Contains("BasicHttpBinding"),
string.Format("InvalidOperationException exception string should contain 'BasicHttpBinding'. Actual message:\r\n" + exception.ToString()));
}
[WcfFact]
public static void CreateChannel_Address_NullString_ThrowsArgumentNull()
{
WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
InstanceContext context = new InstanceContext(callback);
Binding binding = new NetTcpBinding();
Assert.Throws<ArgumentNullException>("uri", () =>
{
DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, (string)null);
});
}
[WcfFact]
public static void CreateChannel_Address_NullEndpointAddress_ThrowsArgumentNull()
{
WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
InstanceContext context = new InstanceContext(callback);
Binding binding = new NetTcpBinding();
DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, (EndpointAddress)null);
Assert.Throws<InvalidOperationException>(() =>
{
factory.CreateChannel();
});
}
[WcfFact]
public static void CreateChannel_Using_NetTcpBinding_Defaults()
{
WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
InstanceContext context = new InstanceContext(callback);
Binding binding = new NetTcpBinding();
EndpointAddress endpoint = new EndpointAddress("net.tcp://not-an-endpoint");
DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpoint);
IWcfDuplexService proxy = factory.CreateChannel();
Assert.NotNull(proxy);
}
[WcfFact]
public static void CreateChannel_Using_NetTcp_NoSecurity()
{
WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
InstanceContext context = new InstanceContext(callback);
Binding binding = new NetTcpBinding(SecurityMode.None);
EndpointAddress endpoint = new EndpointAddress("net.tcp://not-an-endpoint");
DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpoint);
factory.CreateChannel();
}
[WcfFact]
public static void CreateChannel_Using_Http_NoSecurity()
{
WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
InstanceContext context = new InstanceContext(callback);
Binding binding = new NetHttpBinding(BasicHttpSecurityMode.None);
EndpointAddress endpoint = new EndpointAddress(FakeAddress.HttpAddress);
DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpoint);
factory.CreateChannel();
}
[WcfFact]
public static void CreateChannel_Of_IDuplexChannel_Using_NetTcpBinding_Creates_Unique_Instances()
{
DuplexChannelFactory<IWcfDuplexService> factory = null;
DuplexChannelFactory<IWcfDuplexService> factory2 = null;
IWcfDuplexService channel = null;
IWcfDuplexService channel2 = null;
WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback();
InstanceContext context = new InstanceContext(callback);
try
{
NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
EndpointAddress endpointAddress = new EndpointAddress(FakeAddress.TcpAddress);
// Create the channel factory for the request-reply message exchange pattern.
factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpointAddress);
factory2 = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpointAddress);
// Create the channel.
channel = factory.CreateChannel();
Assert.True(typeof(IWcfDuplexService).GetTypeInfo().IsAssignableFrom(channel.GetType().GetTypeInfo()),
String.Format("Channel type '{0}' was not assignable to '{1}'", channel.GetType(), typeof(IDuplexChannel)));
channel2 = factory2.CreateChannel();
Assert.True(typeof(IWcfDuplexService).GetTypeInfo().IsAssignableFrom(channel2.GetType().GetTypeInfo()),
String.Format("Channel type '{0}' was not assignable to '{1}'", channel2.GetType(), typeof(IDuplexChannel)));
// Validate ToString()
string toStringResult = channel.ToString();
string toStringExpected = "IWcfDuplexService";
Assert.Equal<string>(toStringExpected, toStringResult);
// Validate Equals()
Assert.StrictEqual<IWcfDuplexService>(channel, channel);
// Validate Equals(other channel) negative
Assert.NotStrictEqual<IWcfDuplexService>(channel, channel2);
// Validate Equals("other") negative
Assert.NotStrictEqual<object>(channel, "other");
// Validate Equals(null) negative
Assert.NotStrictEqual<IWcfDuplexService>(channel, null);
}
finally
{
if (factory != null)
{
factory.Close();
}
if (factory2 != null)
{
factory2.Close();
}
}
}
}
| |
using System;
using System.Linq;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Services;
using Umbraco.Tests.TestHelpers.Entities;
using Umbraco.Tests.Testing;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.PropertyEditors;
namespace Umbraco.Tests.Models.Mapping
{
[TestFixture]
[UmbracoTest(WithApplication = true)]
public class ContentTypeModelMappingTests : UmbracoTestBase
{
// mocks of services that can be setup on a test by test basis to return whatever we want
private readonly Mock<IContentTypeService> _contentTypeService = new Mock<IContentTypeService>();
private readonly Mock<IContentService> _contentService = new Mock<IContentService>();
private readonly Mock<IDataTypeService> _dataTypeService = new Mock<IDataTypeService>();
private readonly Mock<IEntityService> _entityService = new Mock<IEntityService>();
private readonly Mock<IFileService> _fileService = new Mock<IFileService>();
private Mock<PropertyEditorCollection> _editorsMock;
protected override void Compose()
{
base.Compose();
// create and register a fake property editor collection to return fake property editors
var editors = new DataEditor[] { new TextboxPropertyEditor(Mock.Of<ILogger>()), };
var dataEditors = new DataEditorCollection(editors);
_editorsMock = new Mock<PropertyEditorCollection>(dataEditors);
_editorsMock.Setup(x => x[It.IsAny<string>()]).Returns(editors[0]);
Composition.RegisterUnique(f => _editorsMock.Object);
Composition.RegisterUnique(_ => _contentTypeService.Object);
Composition.RegisterUnique(_ => _contentService.Object);
Composition.RegisterUnique(_ => _dataTypeService.Object);
Composition.RegisterUnique(_ => _entityService.Object);
Composition.RegisterUnique(_ => _fileService.Object);
}
[Test]
public void MemberTypeSave_To_IMemberType()
{
//Arrange
// setup the mocks to return the data we want to test against...
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(Mock.Of<IDataType>(
definition =>
definition.Id == 555
&& definition.EditorAlias == "myPropertyType"
&& definition.DatabaseType == ValueStorageType.Nvarchar));
var display = CreateMemberTypeSave();
//Act
var result = Mapper.Map<IMemberType>(display);
//Assert
Assert.AreEqual(display.Alias, result.Alias);
Assert.AreEqual(display.Description, result.Description);
Assert.AreEqual(display.Icon, result.Icon);
Assert.AreEqual(display.Id, result.Id);
Assert.AreEqual(display.Name, result.Name);
Assert.AreEqual(display.ParentId, result.ParentId);
Assert.AreEqual(display.Path, result.Path);
Assert.AreEqual(display.Thumbnail, result.Thumbnail);
Assert.AreEqual(display.IsContainer, result.IsContainer);
Assert.AreEqual(display.AllowAsRoot, result.AllowedAsRoot);
Assert.AreEqual(display.CreateDate, result.CreateDate);
Assert.AreEqual(display.UpdateDate, result.UpdateDate);
// TODO: Now we need to assert all of the more complicated parts
Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count);
for (var i = 0; i < display.Groups.Count(); i++)
{
Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id);
Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name);
var propTypes = display.Groups.ElementAt(i).Properties;
Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count());
for (var j = 0; j < propTypes.Count(); j++)
{
Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id);
Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId);
Assert.AreEqual(propTypes.ElementAt(j).MemberCanViewProperty, result.MemberCanViewProperty(result.PropertyTypes.ElementAt(j).Alias));
Assert.AreEqual(propTypes.ElementAt(j).MemberCanEditProperty, result.MemberCanEditProperty(result.PropertyTypes.ElementAt(j).Alias));
Assert.AreEqual(propTypes.ElementAt(j).IsSensitiveData, result.IsSensitiveProperty(result.PropertyTypes.ElementAt(j).Alias));
}
}
Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count());
for (var i = 0; i < display.AllowedContentTypes.Count(); i++)
{
Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value);
}
}
[Test]
public void MediaTypeSave_To_IMediaType()
{
//Arrange
// setup the mocks to return the data we want to test against...
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(Mock.Of<IDataType>(
definition =>
definition.Id == 555
&& definition.EditorAlias == "myPropertyType"
&& definition.DatabaseType == ValueStorageType.Nvarchar));
var display = CreateMediaTypeSave();
//Act
var result = Mapper.Map<IMediaType>(display);
//Assert
Assert.AreEqual(display.Alias, result.Alias);
Assert.AreEqual(display.Description, result.Description);
Assert.AreEqual(display.Icon, result.Icon);
Assert.AreEqual(display.Id, result.Id);
Assert.AreEqual(display.Name, result.Name);
Assert.AreEqual(display.ParentId, result.ParentId);
Assert.AreEqual(display.Path, result.Path);
Assert.AreEqual(display.Thumbnail, result.Thumbnail);
Assert.AreEqual(display.IsContainer, result.IsContainer);
Assert.AreEqual(display.AllowAsRoot, result.AllowedAsRoot);
Assert.AreEqual(display.CreateDate, result.CreateDate);
Assert.AreEqual(display.UpdateDate, result.UpdateDate);
// TODO: Now we need to assert all of the more complicated parts
Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count);
for (var i = 0; i < display.Groups.Count(); i++)
{
Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id);
Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name);
var propTypes = display.Groups.ElementAt(i).Properties;
Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count());
for (var j = 0; j < propTypes.Count(); j++)
{
Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id);
Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId);
}
}
Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count());
for (var i = 0; i < display.AllowedContentTypes.Count(); i++)
{
Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value);
}
}
[Test]
public void ContentTypeSave_To_IContentType()
{
//Arrange
// setup the mocks to return the data we want to test against...
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(Mock.Of<IDataType>(
definition =>
definition.Id == 555
&& definition.EditorAlias == "myPropertyType"
&& definition.DatabaseType == ValueStorageType.Nvarchar));
_fileService.Setup(x => x.GetTemplate(It.IsAny<string>()))
.Returns((string alias) => Mock.Of<ITemplate>(
definition =>
definition.Id == alias.GetHashCode() && definition.Alias == alias));
var display = CreateContentTypeSave();
//Act
var result = Mapper.Map<IContentType>(display);
//Assert
Assert.AreEqual(display.Alias, result.Alias);
Assert.AreEqual(display.Description, result.Description);
Assert.AreEqual(display.Icon, result.Icon);
Assert.AreEqual(display.Id, result.Id);
Assert.AreEqual(display.Name, result.Name);
Assert.AreEqual(display.ParentId, result.ParentId);
Assert.AreEqual(display.Path, result.Path);
Assert.AreEqual(display.Thumbnail, result.Thumbnail);
Assert.AreEqual(display.IsContainer, result.IsContainer);
Assert.AreEqual(display.AllowAsRoot, result.AllowedAsRoot);
Assert.AreEqual(display.CreateDate, result.CreateDate);
Assert.AreEqual(display.UpdateDate, result.UpdateDate);
// TODO: Now we need to assert all of the more complicated parts
Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count);
for (var i = 0; i < display.Groups.Count(); i++)
{
Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id);
Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name);
var propTypes = display.Groups.ElementAt(i).Properties;
Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count());
for (var j = 0; j < propTypes.Count(); j++)
{
Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id);
Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId);
}
}
var allowedTemplateAliases = display.AllowedTemplates
.Concat(new[] {display.DefaultTemplate})
.Distinct();
Assert.AreEqual(allowedTemplateAliases.Count(), result.AllowedTemplates.Count());
for (var i = 0; i < display.AllowedTemplates.Count(); i++)
{
Assert.AreEqual(display.AllowedTemplates.ElementAt(i), result.AllowedTemplates.ElementAt(i).Alias);
}
Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count());
for (var i = 0; i < display.AllowedContentTypes.Count(); i++)
{
Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value);
}
}
[Test]
public void MediaTypeSave_With_Composition_To_IMediaType()
{
//Arrange
// setup the mocks to return the data we want to test against...
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(Mock.Of<IDataType>(
definition =>
definition.Id == 555
&& definition.EditorAlias == "myPropertyType"
&& definition.DatabaseType == ValueStorageType.Nvarchar));
var display = CreateCompositionMediaTypeSave();
//Act
var result = Mapper.Map<IMediaType>(display);
//Assert
// TODO: Now we need to assert all of the more complicated parts
Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count);
}
[Test]
public void ContentTypeSave_With_Composition_To_IContentType()
{
//Arrange
// setup the mocks to return the data we want to test against...
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(Mock.Of<IDataType>(
definition =>
definition.Id == 555
&& definition.EditorAlias == "myPropertyType"
&& definition.DatabaseType == ValueStorageType.Nvarchar));
var display = CreateCompositionContentTypeSave();
//Act
var result = Mapper.Map<IContentType>(display);
//Assert
// TODO: Now we need to assert all of the more complicated parts
Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count);
}
[Test]
public void IMemberType_To_MemberTypeDisplay()
{
//Arrange
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType(new VoidEditor(Mock.Of<ILogger>())));
// setup the mocks to return the data we want to test against...
var memberType = MockedContentTypes.CreateSimpleMemberType();
memberType.MemberTypePropertyTypes[memberType.PropertyTypes.Last().Alias] = new MemberTypePropertyProfileAccess(true, true, true);
MockedContentTypes.EnsureAllIds(memberType, 8888);
//Act
var result = Mapper.Map<MemberTypeDisplay>(memberType);
//Assert
Assert.AreEqual(memberType.Alias, result.Alias);
Assert.AreEqual(memberType.Description, result.Description);
Assert.AreEqual(memberType.Icon, result.Icon);
Assert.AreEqual(memberType.Id, result.Id);
Assert.AreEqual(memberType.Name, result.Name);
Assert.AreEqual(memberType.ParentId, result.ParentId);
Assert.AreEqual(memberType.Path, result.Path);
Assert.AreEqual(memberType.Thumbnail, result.Thumbnail);
Assert.AreEqual(memberType.IsContainer, result.IsContainer);
Assert.AreEqual(memberType.CreateDate, result.CreateDate);
Assert.AreEqual(memberType.UpdateDate, result.UpdateDate);
// TODO: Now we need to assert all of the more complicated parts
Assert.AreEqual(memberType.PropertyGroups.Count(), result.Groups.Count());
for (var i = 0; i < memberType.PropertyGroups.Count(); i++)
{
Assert.AreEqual(memberType.PropertyGroups.ElementAt(i).Id, result.Groups.ElementAt(i).Id);
Assert.AreEqual(memberType.PropertyGroups.ElementAt(i).Name, result.Groups.ElementAt(i).Name);
var propTypes = memberType.PropertyGroups.ElementAt(i).PropertyTypes;
Assert.AreEqual(propTypes.Count(), result.Groups.ElementAt(i).Properties.Count());
for (var j = 0; j < propTypes.Count(); j++)
{
Assert.AreEqual(propTypes.ElementAt(j).Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id);
Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId);
Assert.AreEqual(memberType.MemberCanViewProperty(propTypes.ElementAt(j).Alias), result.Groups.ElementAt(i).Properties.ElementAt(j).MemberCanViewProperty);
Assert.AreEqual(memberType.MemberCanEditProperty(propTypes.ElementAt(j).Alias), result.Groups.ElementAt(i).Properties.ElementAt(j).MemberCanEditProperty);
}
}
Assert.AreEqual(memberType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count());
for (var i = 0; i < memberType.AllowedContentTypes.Count(); i++)
{
Assert.AreEqual(memberType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i));
}
}
[Test]
public void IMediaType_To_MediaTypeDisplay()
{
//Arrange
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType(new VoidEditor(Mock.Of<ILogger>())));
// setup the mocks to return the data we want to test against...
var mediaType = MockedContentTypes.CreateImageMediaType();
MockedContentTypes.EnsureAllIds(mediaType, 8888);
//Act
var result = Mapper.Map<MediaTypeDisplay>(mediaType);
//Assert
Assert.AreEqual(mediaType.Alias, result.Alias);
Assert.AreEqual(mediaType.Description, result.Description);
Assert.AreEqual(mediaType.Icon, result.Icon);
Assert.AreEqual(mediaType.Id, result.Id);
Assert.AreEqual(mediaType.Name, result.Name);
Assert.AreEqual(mediaType.ParentId, result.ParentId);
Assert.AreEqual(mediaType.Path, result.Path);
Assert.AreEqual(mediaType.Thumbnail, result.Thumbnail);
Assert.AreEqual(mediaType.IsContainer, result.IsContainer);
Assert.AreEqual(mediaType.CreateDate, result.CreateDate);
Assert.AreEqual(mediaType.UpdateDate, result.UpdateDate);
// TODO: Now we need to assert all of the more complicated parts
Assert.AreEqual(mediaType.PropertyGroups.Count(), result.Groups.Count());
for (var i = 0; i < mediaType.PropertyGroups.Count(); i++)
{
Assert.AreEqual(mediaType.PropertyGroups.ElementAt(i).Id, result.Groups.ElementAt(i).Id);
Assert.AreEqual(mediaType.PropertyGroups.ElementAt(i).Name, result.Groups.ElementAt(i).Name);
var propTypes = mediaType.PropertyGroups.ElementAt(i).PropertyTypes;
Assert.AreEqual(propTypes.Count(), result.Groups.ElementAt(i).Properties.Count());
for (var j = 0; j < propTypes.Count(); j++)
{
Assert.AreEqual(propTypes.ElementAt(j).Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id);
Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId);
}
}
Assert.AreEqual(mediaType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count());
for (var i = 0; i < mediaType.AllowedContentTypes.Count(); i++)
{
Assert.AreEqual(mediaType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i));
}
}
[Test]
public void IContentType_To_ContentTypeDisplay()
{
//Arrange
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType(new VoidEditor(Mock.Of<ILogger>())));
// setup the mocks to return the data we want to test against...
var contentType = MockedContentTypes.CreateTextPageContentType();
MockedContentTypes.EnsureAllIds(contentType, 8888);
//Act
var result = Mapper.Map<DocumentTypeDisplay>(contentType);
//Assert
Assert.AreEqual(contentType.Alias, result.Alias);
Assert.AreEqual(contentType.Description, result.Description);
Assert.AreEqual(contentType.Icon, result.Icon);
Assert.AreEqual(contentType.Id, result.Id);
Assert.AreEqual(contentType.Name, result.Name);
Assert.AreEqual(contentType.ParentId, result.ParentId);
Assert.AreEqual(contentType.Path, result.Path);
Assert.AreEqual(contentType.Thumbnail, result.Thumbnail);
Assert.AreEqual(contentType.IsContainer, result.IsContainer);
Assert.AreEqual(contentType.CreateDate, result.CreateDate);
Assert.AreEqual(contentType.UpdateDate, result.UpdateDate);
Assert.AreEqual(contentType.DefaultTemplate.Alias, result.DefaultTemplate.Alias);
// TODO: Now we need to assert all of the more complicated parts
Assert.AreEqual(contentType.PropertyGroups.Count, result.Groups.Count());
for (var i = 0; i < contentType.PropertyGroups.Count; i++)
{
Assert.AreEqual(contentType.PropertyGroups[i].Id, result.Groups.ElementAt(i).Id);
Assert.AreEqual(contentType.PropertyGroups[i].Name, result.Groups.ElementAt(i).Name);
var propTypes = contentType.PropertyGroups[i].PropertyTypes;
Assert.AreEqual(propTypes.Count, result.Groups.ElementAt(i).Properties.Count());
for (var j = 0; j < propTypes.Count; j++)
{
Assert.AreEqual(propTypes[j].Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id);
Assert.AreEqual(propTypes[j].DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId);
}
}
Assert.AreEqual(contentType.AllowedTemplates.Count(), result.AllowedTemplates.Count());
for (var i = 0; i < contentType.AllowedTemplates.Count(); i++)
{
Assert.AreEqual(contentType.AllowedTemplates.ElementAt(i).Id, result.AllowedTemplates.ElementAt(i).Id);
}
Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count());
for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++)
{
Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i));
}
}
[Test]
public void MemberPropertyGroupBasic_To_MemberPropertyGroup()
{
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType(new VoidEditor(Mock.Of<ILogger>())));
var basic = new PropertyGroupBasic<MemberPropertyTypeBasic>
{
Id = 222,
Name = "Group 1",
SortOrder = 1,
Properties = new[]
{
new MemberPropertyTypeBasic()
{
MemberCanEditProperty = true,
MemberCanViewProperty = true,
IsSensitiveData = true,
Id = 33,
SortOrder = 1,
Alias = "prop1",
Description = "property 1",
DataTypeId = 99,
GroupId = 222,
Label = "Prop 1",
Validation = new PropertyTypeValidation()
{
Mandatory = true,
Pattern = null
}
},
new MemberPropertyTypeBasic()
{
MemberCanViewProperty = false,
MemberCanEditProperty = false,
IsSensitiveData = false,
Id = 34,
SortOrder = 2,
Alias = "prop2",
Description = "property 2",
DataTypeId = 99,
GroupId = 222,
Label = "Prop 2",
Validation = new PropertyTypeValidation()
{
Mandatory = false,
Pattern = null
}
},
}
};
var contentType = new MemberTypeSave
{
Id = 0,
ParentId = -1,
Alias = "alias",
Groups = new[] { basic }
};
// proper group properties mapping takes place when mapping the content type,
// not when mapping the group - because of inherited properties and such
//var result = Mapper.Map<PropertyGroup>(basic);
var result = Mapper.Map<IMemberType>(contentType).PropertyGroups[0];
Assert.AreEqual(basic.Name, result.Name);
Assert.AreEqual(basic.Id, result.Id);
Assert.AreEqual(basic.SortOrder, result.SortOrder);
Assert.AreEqual(basic.Properties.Count(), result.PropertyTypes.Count());
}
[Test]
public void PropertyGroupBasic_To_PropertyGroup()
{
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType(new VoidEditor(Mock.Of<ILogger>())));
var basic = new PropertyGroupBasic<PropertyTypeBasic>
{
Id = 222,
Name = "Group 1",
SortOrder = 1,
Properties = new[]
{
new PropertyTypeBasic()
{
Id = 33,
SortOrder = 1,
Alias = "prop1",
Description = "property 1",
DataTypeId = 99,
GroupId = 222,
Label = "Prop 1",
Validation = new PropertyTypeValidation()
{
Mandatory = true,
Pattern = null
}
},
new PropertyTypeBasic()
{
Id = 34,
SortOrder = 2,
Alias = "prop2",
Description = "property 2",
DataTypeId = 99,
GroupId = 222,
Label = "Prop 2",
Validation = new PropertyTypeValidation()
{
Mandatory = false,
Pattern = null
}
},
}
};
var contentType = new DocumentTypeSave
{
Id = 0,
ParentId = -1,
Alias = "alias",
AllowedTemplates = Enumerable.Empty<string>(),
Groups = new[] { basic }
};
// proper group properties mapping takes place when mapping the content type,
// not when mapping the group - because of inherited properties and such
//var result = Mapper.Map<PropertyGroup>(basic);
var result = Mapper.Map<IContentType>(contentType).PropertyGroups[0];
Assert.AreEqual(basic.Name, result.Name);
Assert.AreEqual(basic.Id, result.Id);
Assert.AreEqual(basic.SortOrder, result.SortOrder);
Assert.AreEqual(basic.Properties.Count(), result.PropertyTypes.Count());
}
[Test]
public void MemberPropertyTypeBasic_To_PropertyType()
{
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType(new VoidEditor(Mock.Of<ILogger>())));
var basic = new MemberPropertyTypeBasic()
{
Id = 33,
SortOrder = 1,
Alias = "prop1",
Description = "property 1",
DataTypeId = 99,
GroupId = 222,
Label = "Prop 1",
Validation = new PropertyTypeValidation()
{
Mandatory = true,
Pattern = "xyz"
}
};
var result = Mapper.Map<PropertyType>(basic);
Assert.AreEqual(basic.Id, result.Id);
Assert.AreEqual(basic.SortOrder, result.SortOrder);
Assert.AreEqual(basic.Alias, result.Alias);
Assert.AreEqual(basic.Description, result.Description);
Assert.AreEqual(basic.DataTypeId, result.DataTypeId);
Assert.AreEqual(basic.Label, result.Name);
Assert.AreEqual(basic.Validation.Mandatory, result.Mandatory);
Assert.AreEqual(basic.Validation.Pattern, result.ValidationRegExp);
}
[Test]
public void PropertyTypeBasic_To_PropertyType()
{
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType(new VoidEditor(Mock.Of<ILogger>())));
var basic = new PropertyTypeBasic()
{
Id = 33,
SortOrder = 1,
Alias = "prop1",
Description = "property 1",
DataTypeId = 99,
GroupId = 222,
Label = "Prop 1",
Validation = new PropertyTypeValidation()
{
Mandatory = true,
Pattern = "xyz"
}
};
var result = Mapper.Map<PropertyType>(basic);
Assert.AreEqual(basic.Id, result.Id);
Assert.AreEqual(basic.SortOrder, result.SortOrder);
Assert.AreEqual(basic.Alias, result.Alias);
Assert.AreEqual(basic.Description, result.Description);
Assert.AreEqual(basic.DataTypeId, result.DataTypeId);
Assert.AreEqual(basic.Label, result.Name);
Assert.AreEqual(basic.Validation.Mandatory, result.Mandatory);
Assert.AreEqual(basic.Validation.Pattern, result.ValidationRegExp);
}
[Test]
public void IMediaTypeComposition_To_MediaTypeDisplay()
{
//Arrange
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType(new VoidEditor(Mock.Of<ILogger>())));
// setup the mocks to return the data we want to test against...
_entityService.Setup(x => x.GetObjectType(It.IsAny<int>()))
.Returns(UmbracoObjectTypes.DocumentType);
var ctMain = MockedContentTypes.CreateSimpleMediaType("parent", "Parent");
//not assigned to tab
ctMain.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext)
{
Alias = "umbracoUrlName",
Name = "Slug",
Description = "",
Mandatory = false,
SortOrder = 1,
DataTypeId = -88
});
MockedContentTypes.EnsureAllIds(ctMain, 8888);
var ctChild1 = MockedContentTypes.CreateSimpleMediaType("child1", "Child 1", ctMain, true);
ctChild1.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext)
{
Alias = "someProperty",
Name = "Some Property",
Description = "",
Mandatory = false,
SortOrder = 1,
DataTypeId = -88
}, "Another tab");
MockedContentTypes.EnsureAllIds(ctChild1, 7777);
var contentType = MockedContentTypes.CreateSimpleMediaType("child2", "Child 2", ctChild1, true, "CustomGroup");
//not assigned to tab
contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext)
{
Alias = "umbracoUrlAlias",
Name = "AltUrl",
Description = "",
Mandatory = false,
SortOrder = 1,
DataTypeId = -88
});
MockedContentTypes.EnsureAllIds(contentType, 6666);
//Act
var result = Mapper.Map<MediaTypeDisplay>(contentType);
//Assert
Assert.AreEqual(contentType.Alias, result.Alias);
Assert.AreEqual(contentType.Description, result.Description);
Assert.AreEqual(contentType.Icon, result.Icon);
Assert.AreEqual(contentType.Id, result.Id);
Assert.AreEqual(contentType.Name, result.Name);
Assert.AreEqual(contentType.ParentId, result.ParentId);
Assert.AreEqual(contentType.Path, result.Path);
Assert.AreEqual(contentType.Thumbnail, result.Thumbnail);
Assert.AreEqual(contentType.IsContainer, result.IsContainer);
Assert.AreEqual(contentType.CreateDate, result.CreateDate);
Assert.AreEqual(contentType.UpdateDate, result.UpdateDate);
// TODO: Now we need to assert all of the more complicated parts
Assert.AreEqual(contentType.CompositionPropertyGroups.Select(x => x.Name).Distinct().Count(), result.Groups.Count(x => x.IsGenericProperties == false));
Assert.AreEqual(1, result.Groups.Count(x => x.IsGenericProperties));
Assert.AreEqual(contentType.PropertyGroups.Count(), result.Groups.Count(x => x.Inherited == false && x.IsGenericProperties == false));
var allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray();
var allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray();
var allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray();
Assert.AreEqual(contentType.PropertyTypes.Count(), allPropertiesMapped.Count(x => x.Inherited == false));
Assert.AreEqual(allPropertyIdsMapped.Count(), allSourcePropertyIds.Count());
Assert.IsTrue(allPropertyIdsMapped.ContainsAll(allSourcePropertyIds));
Assert.AreEqual(2, result.Groups.Count(x => x.ParentTabContentTypes.Any()));
Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] { ctMain.Id, ctChild1.Id }));
Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count());
for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++)
{
Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i));
}
}
[Test]
public void IContentTypeComposition_To_ContentTypeDisplay()
{
//Arrange
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType(new VoidEditor(Mock.Of<ILogger>())));
// setup the mocks to return the data we want to test against...
_entityService.Setup(x => x.GetObjectType(It.IsAny<int>()))
.Returns(UmbracoObjectTypes.DocumentType);
var ctMain = MockedContentTypes.CreateSimpleContentType();
//not assigned to tab
ctMain.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext)
{
Alias = "umbracoUrlName", Name = "Slug", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88
});
MockedContentTypes.EnsureAllIds(ctMain, 8888);
var ctChild1 = MockedContentTypes.CreateSimpleContentType("child1", "Child 1", ctMain, true);
ctChild1.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext)
{
Alias = "someProperty",
Name = "Some Property",
Description = "",
Mandatory = false,
SortOrder = 1,
DataTypeId = -88
}, "Another tab");
MockedContentTypes.EnsureAllIds(ctChild1, 7777);
var contentType = MockedContentTypes.CreateSimpleContentType("child2", "Child 2", ctChild1, true, "CustomGroup");
//not assigned to tab
contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext)
{
Alias = "umbracoUrlAlias", Name = "AltUrl", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88
});
MockedContentTypes.EnsureAllIds(contentType, 6666);
//Act
var result = Mapper.Map<DocumentTypeDisplay>(contentType);
//Assert
Assert.AreEqual(contentType.Alias, result.Alias);
Assert.AreEqual(contentType.Description, result.Description);
Assert.AreEqual(contentType.Icon, result.Icon);
Assert.AreEqual(contentType.Id, result.Id);
Assert.AreEqual(contentType.Name, result.Name);
Assert.AreEqual(contentType.ParentId, result.ParentId);
Assert.AreEqual(contentType.Path, result.Path);
Assert.AreEqual(contentType.Thumbnail, result.Thumbnail);
Assert.AreEqual(contentType.IsContainer, result.IsContainer);
Assert.AreEqual(contentType.CreateDate, result.CreateDate);
Assert.AreEqual(contentType.UpdateDate, result.UpdateDate);
Assert.AreEqual(contentType.DefaultTemplate.Alias, result.DefaultTemplate.Alias);
// TODO: Now we need to assert all of the more complicated parts
Assert.AreEqual(contentType.CompositionPropertyGroups.Select(x => x.Name).Distinct().Count(), result.Groups.Count(x => x.IsGenericProperties == false));
Assert.AreEqual(1, result.Groups.Count(x => x.IsGenericProperties));
Assert.AreEqual(contentType.PropertyGroups.Count(), result.Groups.Count(x => x.Inherited == false && x.IsGenericProperties == false));
var allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray();
var allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray();
var allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray();
Assert.AreEqual(contentType.PropertyTypes.Count(), allPropertiesMapped.Count(x => x.Inherited == false));
Assert.AreEqual(allPropertyIdsMapped.Count(), allSourcePropertyIds.Count());
Assert.IsTrue(allPropertyIdsMapped.ContainsAll(allSourcePropertyIds));
Assert.AreEqual(2, result.Groups.Count(x => x.ParentTabContentTypes.Any()));
Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] {ctMain.Id, ctChild1.Id}));
Assert.AreEqual(contentType.AllowedTemplates.Count(), result.AllowedTemplates.Count());
for (var i = 0; i < contentType.AllowedTemplates.Count(); i++)
{
Assert.AreEqual(contentType.AllowedTemplates.ElementAt(i).Id, result.AllowedTemplates.ElementAt(i).Id);
}
Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count());
for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++)
{
Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i));
}
}
[Test]
public void MemberPropertyTypeBasic_To_MemberPropertyTypeDisplay()
{
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType(new VoidEditor(Mock.Of<ILogger>())));
var basic = new MemberPropertyTypeBasic()
{
Id = 33,
SortOrder = 1,
Alias = "prop1",
Description = "property 1",
DataTypeId = 99,
GroupId = 222,
Label = "Prop 1",
MemberCanViewProperty = true,
MemberCanEditProperty = true,
IsSensitiveData = true,
Validation = new PropertyTypeValidation()
{
Mandatory = true,
Pattern = "xyz"
}
};
var result = Mapper.Map<MemberPropertyTypeDisplay>(basic);
Assert.AreEqual(basic.Id, result.Id);
Assert.AreEqual(basic.SortOrder, result.SortOrder);
Assert.AreEqual(basic.Alias, result.Alias);
Assert.AreEqual(basic.Description, result.Description);
Assert.AreEqual(basic.GroupId, result.GroupId);
Assert.AreEqual(basic.Inherited, result.Inherited);
Assert.AreEqual(basic.Label, result.Label);
Assert.AreEqual(basic.Validation, result.Validation);
Assert.AreEqual(basic.MemberCanViewProperty, result.MemberCanViewProperty);
Assert.AreEqual(basic.MemberCanEditProperty, result.MemberCanEditProperty);
Assert.AreEqual(basic.IsSensitiveData, result.IsSensitiveData);
}
[Test]
public void PropertyTypeBasic_To_PropertyTypeDisplay()
{
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType(new VoidEditor(Mock.Of<ILogger>())));
var basic = new PropertyTypeBasic()
{
Id = 33,
SortOrder = 1,
Alias = "prop1",
Description = "property 1",
DataTypeId = 99,
GroupId = 222,
Label = "Prop 1",
Validation = new PropertyTypeValidation()
{
Mandatory = true,
Pattern = "xyz"
}
};
var result = Mapper.Map<PropertyTypeDisplay>(basic);
Assert.AreEqual(basic.Id, result.Id);
Assert.AreEqual(basic.SortOrder, result.SortOrder);
Assert.AreEqual(basic.Alias, result.Alias);
Assert.AreEqual(basic.Description, result.Description);
Assert.AreEqual(basic.GroupId, result.GroupId);
Assert.AreEqual(basic.Inherited, result.Inherited);
Assert.AreEqual(basic.Label, result.Label);
Assert.AreEqual(basic.Validation, result.Validation);
}
private MemberTypeSave CreateMemberTypeSave()
{
return new MemberTypeSave
{
Alias = "test",
AllowAsRoot = true,
AllowedContentTypes = new[] { 666, 667 },
Description = "hello world",
Icon = "tree-icon",
Id = 1234,
Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"),
Name = "My content type",
Path = "-1,1234",
ParentId = -1,
Thumbnail = "tree-thumb",
IsContainer = true,
Groups = new[]
{
new PropertyGroupBasic<MemberPropertyTypeBasic>()
{
Id = 987,
Name = "Tab 1",
SortOrder = 0,
Inherited = false,
Properties = new []
{
new MemberPropertyTypeBasic
{
MemberCanEditProperty = true,
MemberCanViewProperty = true,
IsSensitiveData = true,
Alias = "property1",
Description = "this is property 1",
Inherited = false,
Label = "Property 1",
Validation = new PropertyTypeValidation
{
Mandatory = false,
Pattern = ""
},
SortOrder = 0,
DataTypeId = 555
}
}
}
}
};
}
private MediaTypeSave CreateMediaTypeSave()
{
return new MediaTypeSave
{
Alias = "test",
AllowAsRoot = true,
AllowedContentTypes = new[] { 666, 667 },
Description = "hello world",
Icon = "tree-icon",
Id = 1234,
Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"),
Name = "My content type",
Path = "-1,1234",
ParentId = -1,
Thumbnail = "tree-thumb",
IsContainer = true,
Groups = new[]
{
new PropertyGroupBasic<PropertyTypeBasic>()
{
Id = 987,
Name = "Tab 1",
SortOrder = 0,
Inherited = false,
Properties = new []
{
new PropertyTypeBasic
{
Alias = "property1",
Description = "this is property 1",
Inherited = false,
Label = "Property 1",
Validation = new PropertyTypeValidation
{
Mandatory = false,
Pattern = ""
},
SortOrder = 0,
DataTypeId = 555
}
}
}
}
};
}
private DocumentTypeSave CreateContentTypeSave()
{
return new DocumentTypeSave
{
Alias = "test",
AllowAsRoot = true,
AllowedTemplates = new []
{
"template1",
"template2"
},
AllowedContentTypes = new [] {666, 667},
DefaultTemplate = "test",
Description = "hello world",
Icon = "tree-icon",
Id = 1234,
Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"),
Name = "My content type",
Path = "-1,1234",
ParentId = -1,
Thumbnail = "tree-thumb",
IsContainer = true,
Groups = new []
{
new PropertyGroupBasic<PropertyTypeBasic>()
{
Id = 987,
Name = "Tab 1",
SortOrder = 0,
Inherited = false,
Properties = new []
{
new PropertyTypeBasic
{
Alias = "property1",
Description = "this is property 1",
Inherited = false,
Label = "Property 1",
Validation = new PropertyTypeValidation
{
Mandatory = false,
Pattern = ""
},
SortOrder = 0,
DataTypeId = 555
}
}
}
}
};
}
private MediaTypeSave CreateCompositionMediaTypeSave()
{
return new MediaTypeSave
{
Alias = "test",
AllowAsRoot = true,
AllowedContentTypes = new[] { 666, 667 },
Description = "hello world",
Icon = "tree-icon",
Id = 1234,
Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"),
Name = "My content type",
Path = "-1,1234",
ParentId = -1,
Thumbnail = "tree-thumb",
IsContainer = true,
Groups = new[]
{
new PropertyGroupBasic<PropertyTypeBasic>()
{
Id = 987,
Name = "Tab 1",
SortOrder = 0,
Inherited = false,
Properties = new[]
{
new PropertyTypeBasic
{
Alias = "property1",
Description = "this is property 1",
Inherited = false,
Label = "Property 1",
Validation = new PropertyTypeValidation
{
Mandatory = false,
Pattern = ""
},
SortOrder = 0,
DataTypeId = 555
}
}
},
new PropertyGroupBasic<PropertyTypeBasic>()
{
Id = 894,
Name = "Tab 2",
SortOrder = 0,
Inherited = true,
Properties = new[]
{
new PropertyTypeBasic
{
Alias = "parentProperty",
Description = "this is a property from the parent",
Inherited = true,
Label = "Parent property",
Validation = new PropertyTypeValidation
{
Mandatory = false,
Pattern = ""
},
SortOrder = 0,
DataTypeId = 555
}
}
}
}
};
}
private DocumentTypeSave CreateCompositionContentTypeSave()
{
return new DocumentTypeSave
{
Alias = "test",
AllowAsRoot = true,
AllowedTemplates = new[]
{
"template1",
"template2"
},
AllowedContentTypes = new[] { 666, 667 },
DefaultTemplate = "test",
Description = "hello world",
Icon = "tree-icon",
Id = 1234,
Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"),
Name = "My content type",
Path = "-1,1234",
ParentId = -1,
Thumbnail = "tree-thumb",
IsContainer = true,
Groups = new[]
{
new PropertyGroupBasic<PropertyTypeBasic>()
{
Id = 987,
Name = "Tab 1",
SortOrder = 0,
Inherited = false,
Properties = new[]
{
new PropertyTypeBasic
{
Alias = "property1",
Description = "this is property 1",
Inherited = false,
Label = "Property 1",
Validation = new PropertyTypeValidation
{
Mandatory = false,
Pattern = ""
},
SortOrder = 0,
DataTypeId = 555
}
}
},
new PropertyGroupBasic<PropertyTypeBasic>()
{
Id = 894,
Name = "Tab 2",
SortOrder = 0,
Inherited = true,
Properties = new[]
{
new PropertyTypeBasic
{
Alias = "parentProperty",
Description = "this is a property from the parent",
Inherited = true,
Label = "Parent property",
Validation = new PropertyTypeValidation
{
Mandatory = false,
Pattern = ""
},
SortOrder = 0,
DataTypeId = 555
}
}
}
}
};
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.