context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using CodeJewelApi.Areas.HelpPage.Models;
namespace CodeJewelApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using Microsoft.Extensions.Logging;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer4.Logging.Models;
using IdentityServer4.Validation;
using Microsoft.AspNetCore.Authentication;
namespace IdentityServer4.Services
{
/// <summary>
/// Default refresh token service
/// </summary>
public class DefaultRefreshTokenService : IRefreshTokenService
{
/// <summary>
/// The logger
/// </summary>
protected readonly ILogger Logger;
/// <summary>
/// The refresh token store
/// </summary>
protected IRefreshTokenStore RefreshTokenStore { get; }
/// <summary>
/// The profile service
/// </summary>
protected IProfileService Profile { get; }
/// <summary>
/// The clock
/// </summary>
protected ISystemClock Clock { get; }
/// <summary>
/// Initializes a new instance of the <see cref="DefaultRefreshTokenService" /> class.
/// </summary>
/// <param name="refreshTokenStore">The refresh token store</param>
/// <param name="profile"></param>
/// <param name="clock">The clock</param>
/// <param name="logger">The logger</param>
public DefaultRefreshTokenService(IRefreshTokenStore refreshTokenStore, IProfileService profile,
ISystemClock clock,
ILogger<DefaultRefreshTokenService> logger)
{
RefreshTokenStore = refreshTokenStore;
Profile = profile;
Clock = clock;
Logger = logger;
}
/// <summary>
/// Validates a refresh token
/// </summary>
/// <param name="tokenHandle">The token handle.</param>
/// <param name="client">The client.</param>
/// <returns></returns>
public virtual async Task<TokenValidationResult> ValidateRefreshTokenAsync(string tokenHandle, Client client)
{
var invalidGrant = new TokenValidationResult
{
IsError = true, Error = OidcConstants.TokenErrors.InvalidGrant
};
Logger.LogTrace("Start refresh token validation");
/////////////////////////////////////////////
// check if refresh token is valid
/////////////////////////////////////////////
var refreshToken = await RefreshTokenStore.GetRefreshTokenAsync(tokenHandle);
if (refreshToken == null)
{
Logger.LogWarning("Invalid refresh token");
return invalidGrant;
}
/////////////////////////////////////////////
// check if refresh token has expired
/////////////////////////////////////////////
if (refreshToken.CreationTime.HasExceeded(refreshToken.Lifetime, Clock.UtcNow.DateTime))
{
Logger.LogWarning("Refresh token has expired.");
return invalidGrant;
}
/////////////////////////////////////////////
// check if client belongs to requested refresh token
/////////////////////////////////////////////
if (client.ClientId != refreshToken.ClientId)
{
Logger.LogError("{0} tries to refresh token belonging to {1}", client.ClientId, refreshToken.ClientId);
return invalidGrant;
}
/////////////////////////////////////////////
// check if client still has offline_access scope
/////////////////////////////////////////////
if (!client.AllowOfflineAccess)
{
Logger.LogError("{clientId} does not have access to offline_access scope anymore", client.ClientId);
return invalidGrant;
}
/////////////////////////////////////////////
// check if refresh token has been consumed
/////////////////////////////////////////////
if (refreshToken.ConsumedTime.HasValue)
{
if ((await AcceptConsumedTokenAsync(refreshToken)) == false)
{
Logger.LogWarning("Rejecting refresh token because it has been consumed already.");
return invalidGrant;
}
}
/////////////////////////////////////////////
// make sure user is enabled
/////////////////////////////////////////////
var isActiveCtx = new IsActiveContext(
refreshToken.Subject,
client,
IdentityServerConstants.ProfileIsActiveCallers.RefreshTokenValidation);
await Profile.IsActiveAsync(isActiveCtx);
if (isActiveCtx.IsActive == false)
{
Logger.LogError("{subjectId} has been disabled", refreshToken.Subject.GetSubjectId());
return invalidGrant;
}
return new TokenValidationResult
{
IsError = false,
RefreshToken = refreshToken,
Client = client
};
}
/// <summary>
/// Callback to decide if an already consumed token should be accepted.
/// </summary>
/// <param name="refreshToken"></param>
/// <returns></returns>
protected virtual Task<bool> AcceptConsumedTokenAsync(RefreshToken refreshToken)
{
// by default we will not accept consumed tokens
// change the behavior here to implement a time window
// you can also implement additional revocation logic here
return Task.FromResult(false);
}
/// <summary>
/// Creates the refresh token.
/// </summary>
/// <param name="subject">The subject.</param>
/// <param name="accessToken">The access token.</param>
/// <param name="client">The client.</param>
/// <returns>
/// The refresh token handle
/// </returns>
public virtual async Task<string> CreateRefreshTokenAsync(ClaimsPrincipal subject, Token accessToken,
Client client)
{
Logger.LogDebug("Creating refresh token");
int lifetime;
if (client.RefreshTokenExpiration == TokenExpiration.Absolute)
{
Logger.LogDebug("Setting an absolute lifetime: {absoluteLifetime}",
client.AbsoluteRefreshTokenLifetime);
lifetime = client.AbsoluteRefreshTokenLifetime;
}
else
{
lifetime = client.SlidingRefreshTokenLifetime;
if (client.AbsoluteRefreshTokenLifetime > 0 && lifetime > client.AbsoluteRefreshTokenLifetime)
{
Logger.LogWarning(
"Client {clientId}'s configured " + nameof(client.SlidingRefreshTokenLifetime) +
" of {slidingLifetime} exceeds its " + nameof(client.AbsoluteRefreshTokenLifetime) +
" of {absoluteLifetime}. The refresh_token's sliding lifetime will be capped to the absolute lifetime",
client.ClientId, lifetime, client.AbsoluteRefreshTokenLifetime);
lifetime = client.AbsoluteRefreshTokenLifetime;
}
Logger.LogDebug("Setting a sliding lifetime: {slidingLifetime}", lifetime);
}
var refreshToken = new RefreshToken
{
CreationTime = Clock.UtcNow.UtcDateTime, Lifetime = lifetime, AccessToken = accessToken
};
var handle = await RefreshTokenStore.StoreRefreshTokenAsync(refreshToken);
return handle;
}
/// <summary>
/// Updates the refresh token.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="refreshToken">The refresh token.</param>
/// <param name="client">The client.</param>
/// <returns>
/// The refresh token handle
/// </returns>
public virtual async Task<string> UpdateRefreshTokenAsync(string handle, RefreshToken refreshToken,
Client client)
{
Logger.LogDebug("Updating refresh token");
bool needsCreate = false;
bool needsUpdate = false;
if (client.RefreshTokenUsage == TokenUsage.OneTimeOnly)
{
Logger.LogDebug("Token usage is one-time only. Setting current handle as consumed, and generating new handle");
// flag as consumed
if (refreshToken.ConsumedTime == null)
{
refreshToken.ConsumedTime = Clock.UtcNow.UtcDateTime;
await RefreshTokenStore.UpdateRefreshTokenAsync(handle, refreshToken);
}
// create new one
needsCreate = true;
}
if (client.RefreshTokenExpiration == TokenExpiration.Sliding)
{
Logger.LogDebug("Refresh token expiration is sliding - extending lifetime");
// if absolute exp > 0, make sure we don't exceed absolute exp
// if absolute exp = 0, allow indefinite slide
var currentLifetime = refreshToken.CreationTime.GetLifetimeInSeconds(Clock.UtcNow.UtcDateTime);
Logger.LogDebug("Current lifetime: {currentLifetime}", currentLifetime.ToString());
var newLifetime = currentLifetime + client.SlidingRefreshTokenLifetime;
Logger.LogDebug("New lifetime: {slidingLifetime}", newLifetime.ToString());
// zero absolute refresh token lifetime represents unbounded absolute lifetime
// if absolute lifetime > 0, cap at absolute lifetime
if (client.AbsoluteRefreshTokenLifetime > 0 && newLifetime > client.AbsoluteRefreshTokenLifetime)
{
newLifetime = client.AbsoluteRefreshTokenLifetime;
Logger.LogDebug("New lifetime exceeds absolute lifetime, capping it to {newLifetime}",
newLifetime.ToString());
}
refreshToken.Lifetime = newLifetime;
needsUpdate = true;
}
if (needsCreate)
{
// set it to null so that we save non-consumed token
refreshToken.ConsumedTime = null;
handle = await RefreshTokenStore.StoreRefreshTokenAsync(refreshToken);
Logger.LogDebug("Created refresh token in store");
}
else if (needsUpdate)
{
await RefreshTokenStore.UpdateRefreshTokenAsync(handle, refreshToken);
Logger.LogDebug("Updated refresh token in store");
}
else
{
Logger.LogDebug("No updates to refresh token done");
}
return handle;
}
}
}
| |
/*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* 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 name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Antlr4.Runtime;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime
{
/// <summary>A lexer is recognizer that draws input symbols from a character stream.</summary>
/// <remarks>
/// A lexer is recognizer that draws input symbols from a character stream.
/// lexer grammars result in a subclass of this object. A Lexer object
/// uses simplified match() and error recovery mechanisms in the interest
/// of speed.
/// </remarks>
public abstract class Lexer : Recognizer<int, LexerATNSimulator>, ITokenSource
{
public const int DefaultMode = 0;
public const int DefaultTokenChannel = TokenConstants.DefaultChannel;
public const int Hidden = TokenConstants.HiddenChannel;
public const int MinCharValue = '\u0000';
public const int MaxCharValue = '\uFFFE';
private ICharStream _input;
private Tuple<ITokenSource, ICharStream> _tokenFactorySourcePair;
/// <summary>How to create token objects</summary>
private ITokenFactory _factory = CommonTokenFactory.Default;
/// <summary>The goal of all lexer rules/methods is to create a token object.</summary>
/// <remarks>
/// The goal of all lexer rules/methods is to create a token object.
/// This is an instance variable as multiple rules may collaborate to
/// create a single token. nextToken will return this object after
/// matching lexer rule(s). If you subclass to allow multiple token
/// emissions, then set this to the last token to be matched or
/// something nonnull so that the auto token emit mechanism will not
/// emit another token.
/// </remarks>
private IToken _token;
/// <summary>
/// What character index in the stream did the current token start at?
/// Needed, for example, to get the text for current token.
/// </summary>
/// <remarks>
/// What character index in the stream did the current token start at?
/// Needed, for example, to get the text for current token. Set at
/// the start of nextToken.
/// </remarks>
private int _tokenStartCharIndex = -1;
/// <summary>The line on which the first character of the token resides</summary>
private int _tokenStartLine;
/// <summary>The character position of first character within the line</summary>
private int _tokenStartColumn;
/// <summary>Once we see EOF on char stream, next token will be EOF.</summary>
/// <remarks>
/// Once we see EOF on char stream, next token will be EOF.
/// If you have DONE : EOF ; then you see DONE EOF.
/// </remarks>
private bool _hitEOF;
/// <summary>The channel number for the current token</summary>
private int _channel;
/// <summary>The token type for the current token</summary>
private int _type;
private readonly Stack<int> _modeStack = new Stack<int>();
private int _mode = Antlr4.Runtime.Lexer.DefaultMode;
/// <summary>
/// You can set the text for the current token to override what is in
/// the input char buffer.
/// </summary>
/// <remarks>
/// You can set the text for the current token to override what is in
/// the input char buffer. Use setText() or can set this instance var.
/// </remarks>
private string _text;
public Lexer(ICharStream input)
{
this._input = input;
this._tokenFactorySourcePair = Tuple.Create((ITokenSource)this, input);
}
public virtual void Reset()
{
// wack Lexer state variables
if (_input != null)
{
_input.Seek(0);
}
// rewind the input
_token = null;
_type = TokenConstants.InvalidType;
_channel = TokenConstants.DefaultChannel;
_tokenStartCharIndex = -1;
_tokenStartColumn = -1;
_tokenStartLine = -1;
_text = null;
_hitEOF = false;
_mode = Antlr4.Runtime.Lexer.DefaultMode;
_modeStack.Clear();
Interpreter.Reset();
}
/// <summary>
/// Return a token from this source; i.e., match a token on the char
/// stream.
/// </summary>
/// <remarks>
/// Return a token from this source; i.e., match a token on the char
/// stream.
/// </remarks>
public virtual IToken NextToken()
{
if (_input == null)
{
throw new InvalidOperationException("nextToken requires a non-null input stream.");
}
// Mark start location in char stream so unbuffered streams are
// guaranteed at least have text of current token
int tokenStartMarker = _input.Mark();
try
{
while (true)
{
if (_hitEOF)
{
EmitEOF();
return _token;
}
_token = null;
_channel = TokenConstants.DefaultChannel;
_tokenStartCharIndex = _input.Index;
_tokenStartColumn = Interpreter.Column;
_tokenStartLine = Interpreter.Line;
_text = null;
do
{
_type = TokenConstants.InvalidType;
// System.out.println("nextToken line "+tokenStartLine+" at "+((char)input.LA(1))+
// " in mode "+mode+
// " at index "+input.index());
int ttype;
try
{
ttype = Interpreter.Match(_input, _mode);
}
catch (LexerNoViableAltException e)
{
NotifyListeners(e);
// report error
Recover(e);
ttype = TokenTypes.Skip;
}
if (_input.La(1) == IntStreamConstants.Eof)
{
_hitEOF = true;
}
if (_type == TokenConstants.InvalidType)
{
_type = ttype;
}
if (_type == TokenTypes.Skip)
{
goto outer_continue;
}
}
while (_type == TokenTypes.More);
if (_token == null)
{
Emit();
}
return _token;
outer_continue: ;
}
}
finally
{
// make sure we release marker after match or
// unbuffered char stream will keep buffering
_input.Release(tokenStartMarker);
}
}
/// <summary>
/// Instruct the lexer to skip creating a token for current lexer rule
/// and look for another token.
/// </summary>
/// <remarks>
/// Instruct the lexer to skip creating a token for current lexer rule
/// and look for another token. nextToken() knows to keep looking when
/// a lexer rule finishes with token set to SKIP_TOKEN. Recall that
/// if token==null at end of any token rule, it creates one for you
/// and emits it.
/// </remarks>
public virtual void Skip()
{
_type = TokenTypes.Skip;
}
public virtual void More()
{
_type = TokenTypes.More;
}
public virtual void Mode(int m)
{
_mode = m;
}
public virtual void PushMode(int m)
{
_modeStack.Push(_mode);
Mode(m);
}
public virtual int PopMode()
{
if (_modeStack.Count == 0)
{
throw new InvalidOperationException();
}
int mode = _modeStack.Pop();
Mode(mode);
return _mode;
}
public virtual ITokenFactory TokenFactory
{
get
{
return _factory;
}
set
{
ITokenFactory factory = value;
this._factory = factory;
}
}
/// <summary>Set the char stream and reset the lexer</summary>
public virtual void SetInputStream(ICharStream input)
{
this._input = null;
this._tokenFactorySourcePair = Tuple.Create((ITokenSource)this, _input);
Reset();
this._input = input;
this._tokenFactorySourcePair = Tuple.Create((ITokenSource)this, _input);
}
public virtual string SourceName
{
get
{
return _input.SourceName;
}
}
public override IIntStream InputStream
{
get
{
return _input;
}
}
ICharStream ITokenSource.InputStream
{
get
{
return _input;
}
}
/// <summary>
/// By default does not support multiple emits per nextToken invocation
/// for efficiency reasons.
/// </summary>
/// <remarks>
/// By default does not support multiple emits per nextToken invocation
/// for efficiency reasons. Subclass and override this method, nextToken,
/// and getToken (to push tokens into a list and pull from that list
/// rather than a single variable as this implementation does).
/// </remarks>
public virtual void Emit(IToken token)
{
//System.err.println("emit "+token);
this._token = token;
}
/// <summary>
/// The standard method called to automatically emit a token at the
/// outermost lexical rule.
/// </summary>
/// <remarks>
/// The standard method called to automatically emit a token at the
/// outermost lexical rule. The token object should point into the
/// char buffer start..stop. If there is a text override in 'text',
/// use that to set the token's text. Override this method to emit
/// custom Token objects or provide a new factory.
/// </remarks>
public virtual IToken Emit()
{
IToken t = _factory.Create(_tokenFactorySourcePair, _type, _text, _channel, _tokenStartCharIndex, CharIndex - 1, _tokenStartLine, _tokenStartColumn);
Emit(t);
return t;
}
public virtual IToken EmitEOF()
{
int cpos = Column;
int line = Line;
IToken eof = _factory.Create(_tokenFactorySourcePair, TokenConstants.Eof, null, TokenConstants.DefaultChannel, _input.Index, _input.Index - 1, line, cpos);
Emit(eof);
return eof;
}
public virtual int Line
{
get
{
return Interpreter.Line;
}
set
{
int line = value;
Interpreter.Line = line;
}
}
public virtual int Column
{
get
{
return Interpreter.Column;
}
set
{
int charPositionInLine = value;
Interpreter.Column = charPositionInLine;
}
}
/// <summary>What is the index of the current character of lookahead?</summary>
public virtual int CharIndex
{
get
{
return _input.Index;
}
}
public virtual int TokenStartCharIndex
{
get
{
return _tokenStartCharIndex;
}
}
public virtual int TokenStartLine
{
get
{
return _tokenStartLine;
}
}
public virtual int TokenStartColumn
{
get
{
return _tokenStartColumn;
}
}
/// <summary>
/// Return the text matched so far for the current token or any text
/// override.
/// </summary>
/// <remarks>
/// Return the text matched so far for the current token or any text
/// override.
/// </remarks>
/// <summary>
/// Set the complete text of this token; it wipes any previous changes to the
/// text.
/// </summary>
/// <remarks>
/// Set the complete text of this token; it wipes any previous changes to the
/// text.
/// </remarks>
public virtual string Text
{
get
{
if (_text != null)
{
return _text;
}
return Interpreter.GetText(_input);
}
set
{
string text = value;
this._text = text;
}
}
/// <summary>Override if emitting multiple tokens.</summary>
/// <remarks>Override if emitting multiple tokens.</remarks>
public virtual IToken Token
{
get
{
return _token;
}
set
{
IToken _token = value;
this._token = _token;
}
}
public virtual int Type
{
get
{
return _type;
}
set
{
int ttype = value;
_type = ttype;
}
}
public virtual int Channel
{
get
{
return _channel;
}
set
{
int channel = value;
_channel = channel;
}
}
public virtual Stack<int> ModeStack
{
get
{
return _modeStack;
}
}
public virtual int CurrentMode
{
get
{
return _mode;
}
set
{
int mode = value;
_mode = mode;
}
}
public virtual bool HitEOF
{
get
{
return _hitEOF;
}
set
{
bool hitEOF = value;
_hitEOF = hitEOF;
}
}
public virtual string[] ModeNames
{
get
{
return null;
}
}
/// <summary>Return a list of all Token objects in input char stream.</summary>
/// <remarks>
/// Return a list of all Token objects in input char stream.
/// Forces load of all tokens. Does not include EOF token.
/// </remarks>
public virtual IList<IToken> GetAllTokens()
{
IList<IToken> tokens = new List<IToken>();
IToken t = NextToken();
while (t.Type != TokenConstants.Eof)
{
tokens.Add(t);
t = NextToken();
}
return tokens;
}
public virtual void Recover(LexerNoViableAltException e)
{
if (_input.La(1) != IntStreamConstants.Eof)
{
// skip a char and try again
Interpreter.Consume(_input);
}
}
public virtual void NotifyListeners(LexerNoViableAltException e)
{
string text = _input.GetText(Interval.Of(_tokenStartCharIndex, _input.Index));
string msg = "token recognition error at: '" + GetErrorDisplay(text) + "'";
IAntlrErrorListener<int> listener = ErrorListenerDispatch;
listener.SyntaxError(this, 0, _tokenStartLine, _tokenStartColumn, msg, e);
}
public virtual string GetErrorDisplay(string s)
{
StringBuilder buf = new StringBuilder();
foreach (char c in s.ToCharArray())
{
buf.Append(GetErrorDisplay(c));
}
return buf.ToString();
}
public virtual string GetErrorDisplay(int c)
{
string s = ((char)c).ToString();
switch (c)
{
case TokenConstants.Eof:
{
s = "<EOF>";
break;
}
case '\n':
{
s = "\\n";
break;
}
case '\t':
{
s = "\\t";
break;
}
case '\r':
{
s = "\\r";
break;
}
}
return s;
}
public virtual string GetCharErrorDisplay(int c)
{
string s = GetErrorDisplay(c);
return "'" + s + "'";
}
/// <summary>
/// Lexers can normally match any char in it's vocabulary after matching
/// a token, so do the easy thing and just kill a character and hope
/// it all works out.
/// </summary>
/// <remarks>
/// Lexers can normally match any char in it's vocabulary after matching
/// a token, so do the easy thing and just kill a character and hope
/// it all works out. You can instead use the rule invocation stack
/// to do sophisticated error recovery if you are in a fragment rule.
/// </remarks>
public virtual void Recover(RecognitionException re)
{
//System.out.println("consuming char "+(char)input.LA(1)+" during recovery");
//re.printStackTrace();
// TODO: Do we lose character or line position information?
_input.Consume();
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.IO;
using System.Runtime;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.ServiceModel.MsmqIntegration;
using System.ServiceModel.Security;
using System.Transactions;
using System.Xml;
using System.Xml.Serialization;
static class MsmqDecodeHelper
{
static ActiveXSerializer activeXSerializer;
static BinaryFormatter binaryFormatter;
const int defaultMaxViaSize = 2048;
const int defaultMaxContentTypeSize = 256;
static ActiveXSerializer ActiveXSerializer
{
get
{
if (null == activeXSerializer)
activeXSerializer = new ActiveXSerializer();
return activeXSerializer;
}
}
static BinaryFormatter BinaryFormatter
{
get
{
if (null == binaryFormatter)
binaryFormatter = new BinaryFormatter();
return binaryFormatter;
}
}
static void ReadServerMode(MsmqChannelListenerBase listener, ServerModeDecoder modeDecoder, byte[] incoming, long lookupId, ref int offset, ref int size)
{
for (;;)
{
if (size <= 0)
{
throw listener.NormalizePoisonException(lookupId, modeDecoder.CreatePrematureEOFException());
}
int decoded = modeDecoder.Decode(incoming, offset, size);
offset += decoded;
size -= decoded;
if (ServerModeDecoder.State.Done == modeDecoder.CurrentState)
break;
}
}
internal static Message DecodeTransportDatagram(MsmqInputChannelListener listener, MsmqReceiveHelper receiver, MsmqInputMessage msmqMessage, MsmqMessageProperty messageProperty)
{
using (MsmqDiagnostics.BoundReceiveBytesOperation())
{
long lookupId = msmqMessage.LookupId.Value;
int size = msmqMessage.BodyLength.Value;
int offset = 0;
byte[] incoming = msmqMessage.Body.Buffer;
ServerModeDecoder modeDecoder = new ServerModeDecoder();
try
{
ReadServerMode(listener, modeDecoder, incoming, messageProperty.LookupId, ref offset, ref size);
}
catch (ProtocolException ex)
{
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, ex);
}
if (modeDecoder.Mode != FramingMode.SingletonSized)
{
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, new ProtocolException(SR.GetString(SR.MsmqBadFrame)));
}
ServerSingletonSizedDecoder decoder = new ServerSingletonSizedDecoder(0, defaultMaxViaSize, defaultMaxContentTypeSize);
try
{
for (;;)
{
if (size <= 0)
{
throw listener.NormalizePoisonException(messageProperty.LookupId, decoder.CreatePrematureEOFException());
}
int decoded = decoder.Decode(incoming, offset, size);
offset += decoded;
size -= decoded;
if (decoder.CurrentState == ServerSingletonSizedDecoder.State.Start)
break;
}
}
catch (ProtocolException ex)
{
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, ex);
}
if (size > listener.MaxReceivedMessageSize)
{
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, MaxMessageSizeStream.CreateMaxReceivedMessageSizeExceededException(listener.MaxReceivedMessageSize));
}
if (!listener.MessageEncoderFactory.Encoder.IsContentTypeSupported(decoder.ContentType))
{
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, new ProtocolException(SR.GetString(SR.MsmqBadContentType)));
}
byte[] envelopeBuffer = listener.BufferManager.TakeBuffer(size);
Buffer.BlockCopy(incoming, offset, envelopeBuffer, 0, size);
Message message = null;
using (MsmqDiagnostics.BoundDecodeOperation())
{
try
{
message = listener.MessageEncoderFactory.Encoder.ReadMessage(
new ArraySegment<byte>(envelopeBuffer, 0, size), listener.BufferManager);
}
catch (XmlException e)
{
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, new ProtocolException(SR.GetString(SR.MsmqBadXml), e));
}
bool closeMessage = true;
try
{
SecurityMessageProperty securityProperty = listener.ValidateSecurity(msmqMessage);
if (null != securityProperty)
message.Properties.Security = securityProperty;
closeMessage = false;
MsmqDiagnostics.TransferFromTransport(message);
return message;
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
throw;
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, ex);
}
finally
{
if (closeMessage)
{
message.Close();
}
}
}
}
}
internal static IInputSessionChannel DecodeTransportSessiongram(
MsmqInputSessionChannelListener listener,
MsmqInputMessage msmqMessage,
MsmqMessageProperty messageProperty,
MsmqReceiveContextLockManager receiveContextManager)
{
using (MsmqDiagnostics.BoundReceiveBytesOperation())
{
long lookupId = msmqMessage.LookupId.Value;
int size = msmqMessage.BodyLength.Value;
int offset = 0;
byte[] incoming = msmqMessage.Body.Buffer;
MsmqReceiveHelper receiver = listener.MsmqReceiveHelper;
ServerModeDecoder modeDecoder = new ServerModeDecoder();
try
{
ReadServerMode(listener, modeDecoder, incoming, messageProperty.LookupId, ref offset, ref size);
}
catch (ProtocolException ex)
{
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, ex);
}
if (modeDecoder.Mode != FramingMode.Simplex)
{
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, new ProtocolException(SR.GetString(SR.MsmqBadFrame)));
}
MsmqInputSessionChannel channel = null;
ServerSessionDecoder sessionDecoder = new ServerSessionDecoder(0, defaultMaxViaSize, defaultMaxContentTypeSize);
try
{
for (;;)
{
if (size <= 0)
{
throw listener.NormalizePoisonException(messageProperty.LookupId, sessionDecoder.CreatePrematureEOFException());
}
int decoded = sessionDecoder.Decode(incoming, offset, size);
offset += decoded;
size -= decoded;
if (ServerSessionDecoder.State.EnvelopeStart == sessionDecoder.CurrentState)
break;
}
}
catch (ProtocolException ex)
{
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, ex);
}
MessageEncoder encoder = listener.MessageEncoderFactory.CreateSessionEncoder();
if (!encoder.IsContentTypeSupported(sessionDecoder.ContentType))
{
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, new ProtocolException(SR.GetString(SR.MsmqBadContentType)));
}
ReceiveContext receiveContext = null;
// tack on the receive context property depending on the receive mode
if (receiver.MsmqReceiveParameters.ReceiveContextSettings.Enabled)
{
receiveContext = receiveContextManager.CreateMsmqReceiveContext(msmqMessage.LookupId.Value);
}
channel = new MsmqInputSessionChannel(listener, Transaction.Current, receiveContext);
Message message = DecodeSessiongramMessage(listener, channel, encoder, messageProperty, incoming, offset, sessionDecoder.EnvelopeSize);
SecurityMessageProperty securityProperty = null;
try
{
securityProperty = listener.ValidateSecurity(msmqMessage);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
throw;
channel.FaultChannel();
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, ex);
}
if (null != securityProperty)
message.Properties.Security = securityProperty;
message.Properties[MsmqMessageProperty.Name] = messageProperty;
channel.EnqueueAndDispatch(message);
listener.RaiseMessageReceived();
for (;;)
{
int decoded;
try
{
if (size <= 0)
{
channel.FaultChannel();
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, sessionDecoder.CreatePrematureEOFException());
}
decoded = sessionDecoder.Decode(incoming, offset, size);
}
catch (ProtocolException ex)
{
channel.FaultChannel();
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, ex);
}
offset += decoded;
size -= decoded;
if (ServerSessionDecoder.State.End == sessionDecoder.CurrentState)
break;
if (ServerSessionDecoder.State.EnvelopeStart == sessionDecoder.CurrentState)
{
message = DecodeSessiongramMessage(listener, channel, encoder, messageProperty, incoming, offset, sessionDecoder.EnvelopeSize);
if (null != securityProperty)
{
message.Properties.Security = (SecurityMessageProperty)securityProperty.CreateCopy();
}
message.Properties[MsmqMessageProperty.Name] = messageProperty;
channel.EnqueueAndDispatch(message);
listener.RaiseMessageReceived();
}
}
channel.Shutdown();
MsmqDiagnostics.SessiongramReceived(channel.Session.Id, msmqMessage.MessageId, channel.InternalPendingItems);
return channel;
}
}
static Message DecodeSessiongramMessage(
MsmqInputSessionChannelListener listener,
MsmqInputSessionChannel channel,
MessageEncoder encoder,
MsmqMessageProperty messageProperty,
byte[] buffer,
int offset,
int size)
{
if (size > listener.MaxReceivedMessageSize)
{
channel.FaultChannel();
listener.MsmqReceiveHelper.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, MaxMessageSizeStream.CreateMaxReceivedMessageSizeExceededException(listener.MaxReceivedMessageSize));
}
// Fix for CSDMain bug 17842
// size is derived from user data, check for corruption
if ((size + offset) > buffer.Length)
{
listener.MsmqReceiveHelper.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, new ProtocolException(SR.GetString(SR.MsmqBadFrame)));
}
byte[] envelopeBuffer = listener.BufferManager.TakeBuffer(size);
Buffer.BlockCopy(buffer, offset, envelopeBuffer, 0, size);
try
{
Message message = null;
using (MsmqDiagnostics.BoundDecodeOperation())
{
message = encoder.ReadMessage(new ArraySegment<byte>(envelopeBuffer, 0, size), listener.BufferManager);
MsmqDiagnostics.TransferFromTransport(message);
}
return message;
}
catch (XmlException e)
{
channel.FaultChannel();
listener.MsmqReceiveHelper.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, new ProtocolException(SR.GetString(SR.MsmqBadXml), e));
}
}
internal static Message DecodeIntegrationDatagram(MsmqIntegrationChannelListener listener, MsmqReceiveHelper receiver, MsmqIntegrationInputMessage msmqMessage, MsmqMessageProperty messageProperty)
{
using (MsmqDiagnostics.BoundReceiveBytesOperation())
{
Message message = Message.CreateMessage(MessageVersion.None, (string)null);
bool closeMessage = true;
try
{
SecurityMessageProperty securityProperty = listener.ValidateSecurity(msmqMessage);
if (null != securityProperty)
message.Properties.Security = securityProperty;
MsmqIntegrationMessageProperty integrationProperty = new MsmqIntegrationMessageProperty();
msmqMessage.SetMessageProperties(integrationProperty);
int size = msmqMessage.BodyLength.Value;
if (size > listener.MaxReceivedMessageSize)
{
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, MaxMessageSizeStream.CreateMaxReceivedMessageSizeExceededException(listener.MaxReceivedMessageSize));
}
byte[] bodyBytes = msmqMessage.Body.GetBufferCopy(size);
MemoryStream bodyStream = new MemoryStream(bodyBytes, 0, bodyBytes.Length, false);
object body = null;
using (MsmqDiagnostics.BoundDecodeOperation())
{
try
{
body = DeserializeForIntegration(listener, bodyStream, integrationProperty, messageProperty.LookupId);
}
catch (SerializationException e)
{
receiver.FinalDisposition(messageProperty);
throw listener.NormalizePoisonException(messageProperty.LookupId, new ProtocolException(SR.GetString(SR.MsmqDeserializationError), e));
}
integrationProperty.Body = body;
message.Properties[MsmqIntegrationMessageProperty.Name] = integrationProperty;
bodyStream.Seek(0, SeekOrigin.Begin);
message.Headers.To = listener.Uri;
closeMessage = false;
MsmqDiagnostics.TransferFromTransport(message);
}
return message;
}
finally
{
if (closeMessage)
message.Close();
}
}
}
static object DeserializeForIntegration(MsmqIntegrationChannelListener listener, Stream bodyStream, MsmqIntegrationMessageProperty property, long lookupId)
{
MsmqMessageSerializationFormat serializationFormat = (listener.ReceiveParameters as MsmqIntegrationReceiveParameters).SerializationFormat;
switch (serializationFormat)
{
case MsmqMessageSerializationFormat.Xml:
return XmlDeserializeForIntegration(listener, bodyStream, lookupId);
case MsmqMessageSerializationFormat.Binary:
return BinaryFormatter.Deserialize(bodyStream);
case MsmqMessageSerializationFormat.ActiveX:
int bodyType = property.BodyType.Value;
return ActiveXSerializer.Deserialize(bodyStream as MemoryStream, bodyType);
case MsmqMessageSerializationFormat.ByteArray:
return (bodyStream as MemoryStream).ToArray();
case MsmqMessageSerializationFormat.Stream:
return bodyStream;
default:
throw new SerializationException(SR.GetString(SR.MsmqUnsupportedSerializationFormat, serializationFormat));
}
}
static object XmlDeserializeForIntegration(MsmqIntegrationChannelListener listener, Stream stream, long lookupId)
{
XmlTextReader reader = new XmlTextReader(stream);
reader.WhitespaceHandling = WhitespaceHandling.Significant;
reader.DtdProcessing = DtdProcessing.Prohibit;
try
{
foreach (XmlSerializer serializer in listener.XmlSerializerList)
{
if (serializer.CanDeserialize(reader))
return serializer.Deserialize(reader);
}
}
catch (InvalidOperationException e)
{
// XmlSerializer throws InvalidOperationException on failure of Deserialize.
// We map it to SerializationException to provide consistent interface
throw new SerializationException(e.Message);
}
throw new SerializationException(SR.GetString(SR.MsmqCannotDeserializeXmlMessage));
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLite;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
using TearDown = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestCleanupAttribute;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#else
using NUnit.Framework;
#endif
using System.Diagnostics;
namespace SQLite.Tests
{
[TestFixture]
public class InsertTest
{
private TestDb _db;
public class TestObj
{
[AutoIncrement, PrimaryKey]
public int Id { get; set; }
public String Text { get; set; }
public override string ToString ()
{
return string.Format("[TestObj: Id={0}, Text={1}]", Id, Text);
}
}
public class TestObj2
{
[PrimaryKey]
public int Id { get; set; }
public String Text { get; set; }
public override string ToString()
{
return string.Format("[TestObj: Id={0}, Text={1}]", Id, Text);
}
}
public class OneColumnObj
{
[AutoIncrement, PrimaryKey]
public int Id { get; set; }
}
public class UniqueObj
{
[PrimaryKey]
public int Id { get; set; }
}
public class EncryptedObj
{
[AutoIncrement, PrimaryKey]
public int Id { get; set; }
[Encrypt]
public String Text { get; set; }
}
public class TestDb : SQLiteConnection
{
public TestDb(String path)
: base(path)
{
CreateTable<TestObj>();
CreateTable<TestObj2>();
CreateTable<OneColumnObj>();
CreateTable<UniqueObj>();
CreateTable<EncryptedObj>();
}
}
[SetUp]
public void Setup()
{
_db = new TestDb(TestPath.GetTempFileName());
}
[TearDown]
public void TearDown()
{
if (_db != null) _db.Close();
}
[Test]
public void InsertALot()
{
int n = 10000;
var q = from i in Enumerable.Range(1, n)
select new TestObj() {
Text = "I am"
};
var objs = q.ToArray();
_db.Trace = false;
var sw = new Stopwatch();
sw.Start();
var numIn = _db.InsertAll(objs);
sw.Stop();
Assert.AreEqual(numIn, n, "Num inserted must = num objects");
var inObjs = _db.CreateCommand("select * from TestObj").ExecuteQuery<TestObj>().ToArray();
for (var i = 0; i < inObjs.Length; i++) {
Assert.AreEqual(i+1, objs[i].Id);
Assert.AreEqual(i+1, inObjs[i].Id);
Assert.AreEqual("I am", inObjs[i].Text);
}
var numCount = _db.CreateCommand("select count(*) from TestObj").ExecuteScalar<int>();
Assert.AreEqual(numCount, n, "Num counted must = num objects");
}
[Test]
public void InsertTwoTimes()
{
var obj1 = new TestObj() { Text = "GLaDOS loves testing!" };
var obj2 = new TestObj() { Text = "Keep testing, just keep testing" };
var numIn1 = _db.Insert(obj1);
var numIn2 = _db.Insert(obj2);
Assert.AreEqual(1, numIn1);
Assert.AreEqual(1, numIn2);
var result = _db.Query<TestObj>("select * from TestObj").ToList();
Assert.AreEqual(2, result.Count);
Assert.AreEqual(obj1.Text, result[0].Text);
Assert.AreEqual(obj2.Text, result[1].Text);
}
[Test]
public void InsertIntoTwoTables()
{
var obj1 = new TestObj() { Text = "GLaDOS loves testing!" };
var obj2 = new TestObj2() { Text = "Keep testing, just keep testing" };
var numIn1 = _db.Insert(obj1);
Assert.AreEqual(1, numIn1);
var numIn2 = _db.Insert(obj2);
Assert.AreEqual(1, numIn2);
var result1 = _db.Query<TestObj>("select * from TestObj").ToList();
Assert.AreEqual(numIn1, result1.Count);
Assert.AreEqual(obj1.Text, result1.First().Text);
var result2 = _db.Query<TestObj>("select * from TestObj2").ToList();
Assert.AreEqual(numIn2, result2.Count);
}
[Test]
public void InsertWithExtra()
{
var obj1 = new TestObj2() { Id=1, Text = "GLaDOS loves testing!" };
var obj2 = new TestObj2() { Id=1, Text = "Keep testing, just keep testing" };
var obj3 = new TestObj2() { Id=1, Text = "Done testing" };
_db.Insert(obj1);
try {
_db.Insert(obj2);
Assert.Fail("Expected unique constraint violation");
}
catch (SQLiteException) {
}
_db.Insert(obj2, "OR REPLACE");
try {
_db.Insert(obj3);
Assert.Fail("Expected unique constraint violation");
}
catch (SQLiteException) {
}
_db.Insert(obj3, "OR IGNORE");
var result = _db.Query<TestObj>("select * from TestObj2").ToList();
Assert.AreEqual(1, result.Count);
Assert.AreEqual(obj2.Text, result.First().Text);
}
[Test]
public void InsertIntoOneColumnAutoIncrementTable()
{
var obj = new OneColumnObj();
_db.Insert(obj);
var result = _db.Get<OneColumnObj>(1);
Assert.AreEqual(1, result.Id);
}
[Test]
public void InsertAllSuccessOutsideTransaction()
{
var testObjects = Enumerable.Range(1, 20).Select(i => new UniqueObj { Id = i }).ToList();
_db.InsertAll(testObjects);
Assert.AreEqual(testObjects.Count, _db.Table<UniqueObj>().Count());
}
[Test]
public void InsertAllFailureOutsideTransaction()
{
var testObjects = Enumerable.Range(1, 20).Select(i => new UniqueObj { Id = i }).ToList();
testObjects[testObjects.Count - 1].Id = 1; // causes the insert to fail because of duplicate key
ExceptionAssert.Throws<SQLiteException>(() => _db.InsertAll(testObjects));
Assert.AreEqual(0, _db.Table<UniqueObj>().Count());
}
[Test]
public void InsertAllSuccessInsideTransaction()
{
var testObjects = Enumerable.Range(1, 20).Select(i => new UniqueObj { Id = i }).ToList();
_db.RunInTransaction(() => {
_db.InsertAll(testObjects);
});
Assert.AreEqual(testObjects.Count, _db.Table<UniqueObj>().Count());
}
[Test]
public void InsertAllFailureInsideTransaction()
{
var testObjects = Enumerable.Range(1, 20).Select(i => new UniqueObj { Id = i }).ToList();
testObjects[testObjects.Count - 1].Id = 1; // causes the insert to fail because of duplicate key
ExceptionAssert.Throws<SQLiteException>(() => _db.RunInTransaction(() => {
_db.InsertAll(testObjects);
}));
Assert.AreEqual(0, _db.Table<UniqueObj>().Count());
}
[Test]
public void InsertOrReplace ()
{
_db.Trace = true;
_db.InsertAll (from i in Enumerable.Range(1, 20) select new TestObj { Text = "#" + i });
Assert.AreEqual (20, _db.Table<TestObj> ().Count ());
var t = new TestObj { Id = 5, Text = "Foo", };
_db.InsertOrReplace (t);
var r = (from x in _db.Table<TestObj> () orderby x.Id select x).ToList ();
Assert.AreEqual (20, r.Count);
Assert.AreEqual ("Foo", r[4].Text);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics.Contracts;
using Microsoft.Research.ClousotRegression;
namespace FrancescoGenericRepro
{
internal class Program
{
private static void Main(string[] args)
{
}
}
#region I contract binding
[ContractClass(typeof(IContract<>))]
public partial interface I<T>
{
void M(T t);
}
[ContractClassFor(typeof(I<>))]
internal abstract class IContract<T> : I<T>
{
public void M(T t)
{
Contract.Requires(t != null);
}
}
#endregion
internal class C<X, T> : I<T>
where X : class
{
public void M(T t2)
{
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 12, MethodILOffset = 19)]
public void Test(T t3)
{
Contract.Assume(t3 != null);
M(t3);
}
}
#region J contract binding
[ContractClass(typeof(JContract))]
public partial interface J
{
void M<T>(T x);
}
[ContractClassFor(typeof(J))]
internal abstract class JContract : J
{
public void M<T>(T x2)
{
Contract.Requires(x2 != null);
}
}
#endregion
internal class D<X> : J
where X : class
{
public void M<T>(T x3)
{
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 12, MethodILOffset = 19)]
public void Test(X x4)
{
Contract.Assume(x4 != null);
M(x4);
}
}
internal class A<X>
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 33, MethodILOffset = 39)]
public virtual X M(X x1)
{
Contract.Requires(x1 != null);
Contract.Ensures(Contract.Result<X>() != null);
return x1;
}
}
internal class B<Y, X> : A<X>
where Y : class
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 33, MethodILOffset = 1)]
public override X M(X x1)
{
return x1;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 12, MethodILOffset = 19)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 37, MethodILOffset = 0)]
public void Test(X x2)
{
Contract.Assume(x2 != null);
var result = M(x2);
Contract.Assert(result != null);
}
}
internal class C<Z, Y, X> : B<Y, X>
where Y : class
where Z : class
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 12, MethodILOffset = 2)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 33, MethodILOffset = 9)]
public override X M(X x1)
{
var result = base.M(x1);
return result;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 12, MethodILOffset = 19)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 37, MethodILOffset = 0)]
new public void Test(X x2)
{
Contract.Assume(x2 != null);
var result = M(x2);
Contract.Assert(result != null);
}
}
internal class D : C<string, string, int>
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 12, MethodILOffset = 15)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 33, MethodILOffset = 22)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 8, MethodILOffset = 22)]
public override int M(int x1)
{
Contract.Ensures(Contract.Result<int>() > 0);
var result = base.M(x1);
return 1;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 12, MethodILOffset = 11)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 21, MethodILOffset = 0)]
new public void Test(int x2)
{
Contract.Requires(x2 == 0);
var result = M(x2);
// ensures specialization needs to kick in
Contract.Assert(result > 0);
}
}
internal class Recursive<This>
where This : Recursive<This>
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 16, MethodILOffset = 27)]
private This GetInstance()
{
Contract.Ensures(Contract.Result<This>() != null);
return (This)this;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 32, MethodILOffset = 0)]
public void Test()
{
var result = GetInstance();
result.AddSomething();
Contract.Assert(result != null);
}
private void AddSomething()
{
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Runtime.Serialization;
using System.Management.Automation.Internal;
using Dbg = System.Management.Automation.Diagnostics;
#if CORECLR
// Use stub for SerializableAttribute and ISerializable related types.
using Microsoft.PowerShell.CoreClr.Stubs;
#endif
namespace System.Management.Automation.Host
{
/// <summary>
///
/// Defines the exception thrown when the Host cannot complete an operation
/// such as checking whether there is any input available.
///
/// </summary>
[Serializable]
public
class HostException : RuntimeException
{
#region ctors
/// <summary>
///
/// Initializes a new instance of the HostException class
///
/// </summary>
public
HostException() : base(
StringUtil.Format(HostInterfaceExceptionsStrings.DefaultCtorMessageTemplate, typeof(HostException).FullName))
{
SetDefaultErrorRecord();
}
/// <summary>
///
/// Initializes a new instance of the HostException class and defines the error message
///
/// </summary>
/// <param name="message">
///
/// The error message that explains the reason for the exception.
///
/// </param>
public
HostException(string message) : base(message)
{
SetDefaultErrorRecord();
}
/// <summary>
///
/// Initializes a new instance of the HostException class and defines the error message and
/// inner exception.
///
/// </summary>
/// <param name="message">
///
/// The error message that explains the reason for the exception.
///
/// </param>
/// <param name="innerException">
///
/// The exception that is the cause of the current exception. If the <paramref name="innerException"/>
/// parameter is not a null reference, the current exception is raised in a catch
/// block that handles the inner exception.
///
/// </param>
public
HostException(string message, Exception innerException)
: base(message, innerException)
{
SetDefaultErrorRecord();
}
/// <summary>
///
/// Initializes a new instance of the HostException class and defines the error message,
/// inner exception, the error ID, and the error category.
///
/// </summary>
/// <param name="message">
///
/// The error message that explains the reason for the exception.
///
/// </param>
/// <param name="innerException">
///
/// The exception that is the cause of the current exception. If the <paramref name="innerException"/>
/// parameter is not a null reference, the current exception is raised in a catch
/// block that handles the inner exception.
///
/// </param>
/// <param name="errorId">
///
/// The string that should uniquely identifies the situation where the exception is thrown.
/// The string should not contain white space.
///
/// </param>
/// <param name="errorCategory">
///
/// The ErrorCategory into which this exception situation falls
///
/// </param>
/// <remarks>
/// Intentionally public, third-party hosts can call this
/// </remarks>
public
HostException(string message, Exception innerException, string errorId, ErrorCategory errorCategory) :
base(message, innerException)
{
SetErrorId(errorId);
SetErrorCategory(errorCategory);
}
/// <summary>
///
/// Initializes a new instance of the HostException class and defines the SerializationInfo
/// and the StreamingContext.
///
/// </summary>
/// <param name="info">
///
/// The object that holds the serialized object data.
///
/// </param>
/// <param name="context">
///
/// The contextual information about the source or destination.
///
/// </param>
protected
HostException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endregion
#region private
private void SetDefaultErrorRecord()
{
SetErrorCategory(ErrorCategory.ResourceUnavailable);
SetErrorId(typeof(HostException).FullName);
}
#endregion
}
/// <summary>
///
/// Defines the exception thrown when an error occurs from prompting for a command parameter.
///
/// </summary>
[Serializable]
public
class PromptingException : HostException
{
#region ctors
/// <summary>
///
/// Initializes a new instance of the PromptingException class
///
/// </summary>
public
PromptingException() : base(StringUtil.Format(HostInterfaceExceptionsStrings.DefaultCtorMessageTemplate, typeof(PromptingException).FullName))
{
SetDefaultErrorRecord();
}
/// <summary>
///
/// Initializes a new instance of the PromptingException class and defines the error message
///
/// </summary>
/// <param name="message">
///
/// The error message that explains the reason for the exception.
///
/// </param>
public
PromptingException(string message) : base(message)
{
SetDefaultErrorRecord();
}
/// <summary>
///
/// Initializes a new instance of the PromptingException class and defines the error message and
/// inner exception.
///
/// </summary>
/// <param name="message">
///
/// The error message that explains the reason for the exception.
///
/// </param>
/// <param name="innerException">
///
/// The exception that is the cause of the current exception. If the <paramref name="innerException"/>
/// parameter is not a null reference, the current exception is raised in a catch
/// block that handles the inner exception.
///
/// </param>
public
PromptingException(string message, Exception innerException)
: base(message, innerException)
{
SetDefaultErrorRecord();
}
/// <summary>
///
/// Initializes a new instance of the PromptingException class and defines the error message,
/// inner exception, the error ID, and the error category.
///
/// </summary>
/// <param name="message">
///
/// The error message that explains the reason for the exception.
///
/// </param>
/// <param name="innerException">
///
/// The exception that is the cause of the current exception. If the <paramref name="innerException"/>
/// parameter is not a null reference, the current exception is raised in a catch
/// block that handles the inner exception.
///
/// </param>
/// <param name="errorId">
///
/// The string that should uniquely identifies the situation where the exception is thrown.
/// The string should not contain white space.
///
/// </param>
/// <param name="errorCategory">
///
/// The ErrorCategory into which this exception situation falls
///
/// </param>
/// <remarks>
/// Intentionally public, third-party hosts can call this
/// </remarks>
public
PromptingException(string message, Exception innerException, string errorId, ErrorCategory errorCategory) :
base(message, innerException, errorId, errorCategory)
{
}
/// <summary>
///
/// Initializes a new instance of the HostException class and defines the SerializationInfo
/// and the StreamingContext.
///
/// </summary>
/// <param name="info">
///
/// The object that holds the serialized object data.
///
/// </param>
/// <param name="context">
///
/// The contextual information about the source or destination.
///
/// </param>
protected
PromptingException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endregion
#region private
private void SetDefaultErrorRecord()
{
SetErrorCategory(ErrorCategory.ResourceUnavailable);
SetErrorId(typeof(PromptingException).FullName);
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SourceSpec.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.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace Akka.Streams.Tests.Dsl
{
public class SourceSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public SourceSpec(ITestOutputHelper helper) : base(helper)
{
Materializer = ActorMaterializer.Create(Sys);
}
[Fact]
public void Single_Source_must_produce_element()
{
var p = Source.Single(1).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c);
var sub = c.ExpectSubscription();
sub.Request(1);
c.ExpectNext(1);
c.ExpectComplete();
}
[Fact]
public void Single_Source_must_reject_later_subscriber()
{
var p = Source.Single(1).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c1 = this.CreateManualSubscriberProbe<int>();
var c2 = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c1);
var sub1 = c1.ExpectSubscription();
sub1.Request(1);
c1.ExpectNext(1);
c1.ExpectComplete();
p.Subscribe(c2);
c2.ExpectSubscriptionAndError();
}
[Fact]
public void Empty_Source_must_complete_immediately()
{
var p = Source.Empty<int>().RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c);
c.ExpectSubscriptionAndComplete();
//reject additional subscriber
var c2 = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c2);
c2.ExpectSubscriptionAndError();
}
[Fact]
public void Failed_Source_must_emit_error_immediately()
{
var ex = new Exception();
var p = Source.Failed<int>(ex).RunWith(Sink.AsPublisher<int>(false), Materializer);
var c = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c);
c.ExpectSubscriptionAndError();
//reject additional subscriber
var c2 = this.CreateManualSubscriberProbe<int>();
p.Subscribe(c2);
c2.ExpectSubscriptionAndError();
}
[Fact]
public void Maybe_Source_must_complete_materialized_future_with_None_when_stream_cancels()
{
this.AssertAllStagesStopped(() =>
{
var neverSource = Source.Maybe<object>();
var pubSink = Sink.AsPublisher<object>(false);
var t = neverSource.ToMaterialized(pubSink, Keep.Both).Run(Materializer);
var f = t.Item1;
var neverPub = t.Item2;
var c = this.CreateManualSubscriberProbe<object>();
neverPub.Subscribe(c);
var subs = c.ExpectSubscription();
subs.Request(1000);
c.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
subs.Cancel();
f.Task.AwaitResult().Should().Be(null);
}, Materializer);
}
[Fact]
public void Maybe_Source_must_allow_external_triggering_of_empty_completion()
{
this.AssertAllStagesStopped(() =>
{
var neverSource = Source.Maybe<int>().Where(_ => false);
var counterSink = Sink.Aggregate<int, int>(0, (acc, _) => acc + 1);
var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer);
var neverPromise = t.Item1;
var counterFuture = t.Item2;
//external cancellation
neverPromise.TrySetResult(0).Should().BeTrue();
counterFuture.AwaitResult().Should().Be(0);
}, Materializer);
}
[Fact]
public void Maybe_Source_must_allow_external_triggering_of_non_empty_completion()
{
this.AssertAllStagesStopped(() =>
{
var neverSource = Source.Maybe<int>();
var counterSink = Sink.First<int>();
var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer);
var neverPromise = t.Item1;
var counterFuture = t.Item2;
//external cancellation
neverPromise.TrySetResult(6).Should().BeTrue();
counterFuture.AwaitResult().Should().Be(6);
}, Materializer);
}
[Fact]
public void Maybe_Source_must_allow_external_triggering_of_OnError()
{
this.AssertAllStagesStopped(() =>
{
var neverSource = Source.Maybe<int>();
var counterSink = Sink.First<int>();
var t = neverSource.ToMaterialized(counterSink, Keep.Both).Run(Materializer);
var neverPromise = t.Item1;
var counterFuture = t.Item2;
//external cancellation
neverPromise.SetException(new Exception("Boom"));
counterFuture.Invoking(f => f.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Exception>()
.WithMessage("Boom");
}, Materializer);
}
[Fact]
public void Composite_Source_must_merge_from_many_inputs()
{
var probes = Enumerable.Range(1, 5).Select(_ => this.CreateManualPublisherProbe<int>()).ToList();
var source = Source.AsSubscriber<int>();
var outProbe = this.CreateManualSubscriberProbe<int>();
var s =
Source.FromGraph(GraphDsl.Create(source, source, source, source, source,
(a, b, c, d, e) => new[] {a, b, c, d, e},
(b, i0, i1, i2, i3, i4) =>
{
var m = b.Add(new Merge<int>(5));
b.From(i0.Outlet).To(m.In(0));
b.From(i1.Outlet).To(m.In(1));
b.From(i2.Outlet).To(m.In(2));
b.From(i3.Outlet).To(m.In(3));
b.From(i4.Outlet).To(m.In(4));
return new SourceShape<int>(m.Out);
})).To(Sink.FromSubscriber(outProbe)).Run(Materializer);
for (var i = 0; i < 5; i++)
probes[i].Subscribe(s[i]);
var sub = outProbe.ExpectSubscription();
sub.Request(10);
for (var i = 0; i < 5; i++)
{
var subscription = probes[i].ExpectSubscription();
subscription.ExpectRequest();
subscription.SendNext(i);
subscription.SendComplete();
}
var gotten = new List<int>();
for (var i = 0; i < 5; i++)
gotten.Add(outProbe.ExpectNext());
gotten.ShouldAllBeEquivalentTo(new[] {0, 1, 2, 3, 4});
outProbe.ExpectComplete();
}
[Fact]
public void Composite_Source_must_combine_from_many_inputs_with_simplified_API()
{
var probes = Enumerable.Range(1, 3).Select(_ => this.CreateManualPublisherProbe<int>()).ToList();
var source = probes.Select(Source.FromPublisher).ToList();
var outProbe = this.CreateManualSubscriberProbe<int>();
Source.Combine(source[0], source[1], i => new Merge<int, int>(i), source[2])
.To(Sink.FromSubscriber(outProbe))
.Run(Materializer);
var sub = outProbe.ExpectSubscription();
sub.Request(3);
for (var i = 0; i < 3; i++)
{
var s = probes[i].ExpectSubscription();
s.ExpectRequest();
s.SendNext(i);
s.SendComplete();
}
var gotten = new List<int>();
for (var i = 0; i < 3; i++)
gotten.Add(outProbe.ExpectNext());
gotten.ShouldAllBeEquivalentTo(new[] {0, 1, 2});
outProbe.ExpectComplete();
}
[Fact]
public void Composite_Source_must_combine_from_two_inputs_with_simplified_API()
{
var probes = Enumerable.Range(1, 2).Select(_ => this.CreateManualPublisherProbe<int>()).ToList();
var source = probes.Select(Source.FromPublisher).ToList();
var outProbe = this.CreateManualSubscriberProbe<int>();
Source.Combine(source[0], source[1], i => new Merge<int, int>(i))
.To(Sink.FromSubscriber(outProbe))
.Run(Materializer);
var sub = outProbe.ExpectSubscription();
sub.Request(3);
for (var i = 0; i < 2; i++)
{
var s = probes[i].ExpectSubscription();
s.ExpectRequest();
s.SendNext(i);
s.SendComplete();
}
var gotten = new List<int>();
for (var i = 0; i < 2; i++)
gotten.Add(outProbe.ExpectNext());
gotten.ShouldAllBeEquivalentTo(new[] {0, 1});
outProbe.ExpectComplete();
}
[Fact]
public void Repeat_Source_must_repeat_as_long_as_it_takes()
{
var f = Source.Repeat(42).Grouped(1000).RunWith(Sink.First<IEnumerable<int>>(), Materializer);
f.Result.Should().HaveCount(1000).And.Match(x => x.All(i => i == 42));
}
private static readonly int[] Expected = {
9227465, 5702887, 3524578, 2178309, 1346269, 832040, 514229, 317811, 196418, 121393, 75025, 46368, 28657, 17711,
10946, 6765, 4181, 2584, 1597, 987, 610, 377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0
};
[Fact]
public void Unfold_Source_must_generate_a_finite_fibonacci_sequence()
{
Source.Unfold(Tuple.Create(0, 1), tuple =>
{
var a = tuple.Item1;
var b = tuple.Item2;
if (a > 10000000)
return null;
return Tuple.Create(Tuple.Create(b, a + b), a);
}).RunAggregate(new LinkedList<int>(), (ints, i) =>
{
ints.AddFirst(i);
return ints;
}, Materializer).Result.Should().Equal(Expected);
}
[Fact]
public void Unfold_Source_must_terminate_with_a_failure_if_there_is_an_exception_thrown()
{
EventFilter.Exception<Exception>(message: "expected").ExpectOne(() =>
{
var task = Source.Unfold(Tuple.Create(0, 1), tuple =>
{
var a = tuple.Item1;
var b = tuple.Item2;
if (a > 10000000)
throw new Exception("expected");
return Tuple.Create(Tuple.Create(b, a + b), a);
}).RunAggregate(new LinkedList<int>(), (ints, i) =>
{
ints.AddFirst(i);
return ints;
}, Materializer);
task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3)))
.ShouldThrow<Exception>()
.WithMessage("expected");
});
}
[Fact]
public void Unfold_Source_must_generate_a_finite_fibonacci_sequence_asynchronously()
{
Source.UnfoldAsync(Tuple.Create(0, 1), tuple =>
{
var a = tuple.Item1;
var b = tuple.Item2;
if (a > 10000000)
return Task.FromResult<Tuple<Tuple<int, int>, int>>(null);
return Task.FromResult(Tuple.Create(Tuple.Create(b, a + b), a));
}).RunAggregate(new LinkedList<int>(), (ints, i) =>
{
ints.AddFirst(i);
return ints;
}, Materializer).Result.Should().Equal(Expected);
}
[Fact]
public void Unfold_Source_must_generate_a_unboundeed_fibonacci_sequence()
{
Source.Unfold(Tuple.Create(0, 1), tuple =>
{
var a = tuple.Item1;
var b = tuple.Item2;
return Tuple.Create(Tuple.Create(b, a + b), a);
})
.Take(36)
.RunAggregate(new LinkedList<int>(), (ints, i) =>
{
ints.AddFirst(i);
return ints;
}, Materializer).Result.Should().Equal(Expected);
}
[Fact]
public void Iterator_Source_must_properly_iterate()
{
var expected = new[] {false, true, false, true, false, true, false, true, false, true }.ToList();
Source.FromEnumerator(() => expected.GetEnumerator())
.Grouped(10)
.RunWith(Sink.First<IEnumerable<bool>>(), Materializer)
.Result.Should()
.Equal(expected);
}
[Fact]
public void Cycle_Source_must_continuously_generate_the_same_sequence()
{
var expected = new[] {1, 2, 3, 1, 2, 3, 1, 2, 3};
Source.Cycle(() => new[] {1, 2, 3}.AsEnumerable().GetEnumerator())
.Grouped(9)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer)
.AwaitResult()
.ShouldAllBeEquivalentTo(expected);
}
[Fact]
public void Cycle_Source_must_throw_an_exception_in_case_of_empty_Enumerator()
{
var empty = Enumerable.Empty<int>().GetEnumerator();
var task = Source.Cycle(()=>empty).RunWith(Sink.First<int>(), Materializer);
task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<ArgumentException>();
}
[Fact]
public void Cycle_Source_must_throw_an_exception_in_case_of_empty_Enumerator2()
{
var b = false;
var single = Enumerable.Repeat(1, 1).GetEnumerator();
var empty = Enumerable.Empty<int>().GetEnumerator();
var task = Source.Cycle(() =>
{
if (b)
return empty;
b = true;
return single;
}).RunWith(Sink.Last<int>(), Materializer);
task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<ArgumentException>();
}
[Fact]
public void A_Source_must_suitably_override_attribute_handling_methods()
{
Source.Single(42).Async().AddAttributes(Attributes.None).Named("");
}
[Fact]
public void A_ZipN_Source_must_properly_ZipN()
{
var sources = new[]
{
Source.From(new[] {1, 2, 3}),
Source.From(new[] {10, 20, 30}),
Source.From(new[] {100, 200, 300}),
};
Source.ZipN(sources)
.RunWith(Sink.Seq<IImmutableList<int>>(), Materializer)
.AwaitResult()
.ShouldAllBeEquivalentTo(new[]
{
new[] {1, 10, 100},
new[] {2, 20, 200},
new[] {3, 30, 300},
});
}
[Fact]
public void A_ZipWithN_Source_must_properly_ZipWithN()
{
var sources = new[]
{
Source.From(new[] {1, 2, 3}),
Source.From(new[] {10, 20, 30}),
Source.From(new[] {100, 200, 300}),
};
Source.ZipWithN(list => list.Sum(), sources)
.RunWith(Sink.Seq<int>(), Materializer)
.AwaitResult()
.ShouldAllBeEquivalentTo(new[] {111, 222, 333});
}
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com)
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using PdfSharp.Drawing;
namespace MigraDoc.Rendering
{
/// <summary>
/// Abstract base class for all areas to render in.
/// </summary>
internal abstract class Area
{
internal Area()
{
}
/// <summary>
/// Gets the left boundary of the area.
/// </summary>
internal abstract XUnit X
{
get;
set;
}
/// <summary>
/// Gets the top boundary of the area.
/// </summary>
internal abstract XUnit Y
{
get;
set;
}
/// <summary>
/// Gets the largest fitting rect with the given y position and height.
/// </summary>
/// <param name="yPosition">Top bound of the searched rectangle.</param>
/// <param name="height">Height of the searched rectangle.</param>
/// <returns>
/// The largest fitting rect with the given y position and height.
/// Null if yPosition exceeds the area.
/// </returns>
internal abstract Rectangle GetFittingRect(XUnit yPosition, XUnit height);
/// <summary>
/// Gets or sets the height of the smallest rectangle containing the area.
/// </summary>
internal abstract XUnit Height
{
get;
set;
}
/// <summary>
/// Gets or sets the width of the smallest rectangle containing the area.
/// </summary>
internal abstract XUnit Width
{
get;
set;
}
/// <summary>
/// Returns the union of this area snd the given one.
/// </summary>
/// <param name="area">The area to unite with.</param>
/// <returns>The union of the two areas.</returns>
internal abstract Area Unite(Area area);
/// <summary>
/// Lowers the area and makes it smaller.
/// </summary>
/// <param name="verticalOffset">The measure of lowering.</param>
/// <returns>The lowered Area.</returns>
internal abstract Area Lower(XUnit verticalOffset);
}
internal class Rectangle : Area
{
/// <summary>
/// Initializes a new rectangle object.
/// </summary>
/// <param name="x">Left bound of the rectangle.</param>
/// <param name="y">Upper bound of the rectangle.</param>
/// <param name="width">Width of the rectangle.</param>
/// <param name="height">Height of the rectangle.</param>
internal Rectangle(XUnit x, XUnit y, XUnit width, XUnit height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/// <summary>
/// Initializes a new Rectangle by copying its values.
/// </summary>
/// <param name="rect">The rectangle to copy.</param>
internal Rectangle(Rectangle rect)
{
this.x = rect.x;
this.y = rect.y;
this.width = rect.width;
this.height = rect.height;
}
/// <summary>
/// Gets the largest fitting rect with the given y position and height.
/// </summary>
/// <param name="yPosition">Top bound of the searched rectangle.</param>
/// <param name="height">Height of the searched rectangle.</param>
/// <returns>The largest fitting rect with the given y position and height</returns>
internal override Rectangle GetFittingRect(XUnit yPosition, XUnit height)
{
// BUG: Code removed because null is not handled in caller
#if true
if (yPosition + height > this.y + this.height + Renderer.Tolerance)
return null;
#endif
return new Rectangle(this.x, yPosition, this.width, height);
}
/// <summary>
/// Gets or sets the left boundary of the rectangle.
/// </summary>
internal override XUnit X
{
get { return this.x; }
set { this.x = value; }
}
XUnit x;
/// <summary>
/// Gets or sets the top boundary of the rectangle.
/// </summary>
internal override XUnit Y
{
get { return this.y; }
set { this.y = value; }
}
XUnit y;
/// <summary>
/// Gets or sets the top boundary of the rectangle.
/// </summary>
internal override XUnit Width
{
get { return this.width; }
set { this.width = value; }
}
XUnit width;
/// <summary>
/// Gets or sets the height of the rectangle.
/// </summary>
internal override XUnit Height
{
get { return this.height; }
set { this.height = value; }
}
XUnit height;
/// <summary>
/// Returns the union of the rectangle and the given area.
/// </summary>
/// <param name="area">The area to unite with.</param>
/// <returns>The union of the two areas.</returns>
internal override Area Unite(Area area)
{
if (area == null)
return this;
//This implementation is of course not correct, but it works for our purposes.
XUnit minTop = Math.Min(this.y, area.Y);
XUnit minLeft = Math.Min(this.x, area.X);
XUnit maxRight = Math.Max(this.x + this.width, area.X + area.Width);
XUnit maxBottom = Math.Max(this.y + this.height, area.Y + area.Height);
return new Rectangle(minLeft, minTop, maxRight - minLeft, maxBottom - minTop);
}
internal override Area Lower(XUnit verticalOffset)
{
return new Rectangle(this.x, this.y + verticalOffset, this.width, this.height - verticalOffset);
}
}
}
| |
using UnityEngine;
namespace Pathfinding
{
/** Holds a coordinate in integers */
public struct Int3 {
public int x;
public int y;
public int z;
//These should be set to the same value (only PrecisionFactor should be 1 divided by Precision)
/** Precision for the integer coordinates.
* One world unit is divided into [value] pieces. A value of 1000 would mean millimeter precision, a value of 1 would mean meter precision (assuming 1 world unit = 1 meter).
* This value affects the maximum coordinates for nodes as well as how large the cost values are for moving between two nodes.
* A higher value means that you also have to set all penalty values to a higher value to compensate since the normal cost of moving will be higher.
*/
public const int Precision = 1000;
/** #Precision as a float */
public const float FloatPrecision = 1000F;
/** 1 divided by #Precision */
public const float PrecisionFactor = 0.001F;
/* Factor to multiply cost with */
//public const float CostFactor = 0.01F;
private static Int3 _zero = new Int3(0,0,0);
public static Int3 zero { get { return _zero; } }
public Int3 (Vector3 position) {
x = (int)System.Math.Round (position.x*FloatPrecision);
y = (int)System.Math.Round (position.y*FloatPrecision);
z = (int)System.Math.Round (position.z*FloatPrecision);
//x = Mathf.RoundToInt (position.x);
//y = Mathf.RoundToInt (position.y);
//z = Mathf.RoundToInt (position.z);
}
public Int3 (int _x, int _y, int _z) {
x = _x;
y = _y;
z = _z;
}
public static bool operator == (Int3 lhs, Int3 rhs) {
return lhs.x == rhs.x &&
lhs.y == rhs.y &&
lhs.z == rhs.z;
}
public static bool operator != (Int3 lhs, Int3 rhs) {
return lhs.x != rhs.x ||
lhs.y != rhs.y ||
lhs.z != rhs.z;
}
public static explicit operator Int3 (Vector3 ob) {
return new Int3 (
(int)System.Math.Round (ob.x*FloatPrecision),
(int)System.Math.Round (ob.y*FloatPrecision),
(int)System.Math.Round (ob.z*FloatPrecision)
);
//return new Int3 (Mathf.RoundToInt (ob.x*FloatPrecision),Mathf.RoundToInt (ob.y*FloatPrecision),Mathf.RoundToInt (ob.z*FloatPrecision));
}
public static explicit operator Vector3 (Int3 ob) {
return new Vector3 (ob.x*PrecisionFactor,ob.y*PrecisionFactor,ob.z*PrecisionFactor);
}
public static Int3 operator - (Int3 lhs, Int3 rhs) {
lhs.x -= rhs.x;
lhs.y -= rhs.y;
lhs.z -= rhs.z;
return lhs;
}
public static Int3 operator - (Int3 lhs) {
lhs.x = -lhs.x;
lhs.y = -lhs.y;
lhs.z = -lhs.z;
return lhs;
}
public static Int3 operator + (Int3 lhs, Int3 rhs) {
lhs.x += rhs.x;
lhs.y += rhs.y;
lhs.z += rhs.z;
return lhs;
}
public static Int3 operator * (Int3 lhs, int rhs) {
lhs.x *= rhs;
lhs.y *= rhs;
lhs.z *= rhs;
return lhs;
}
public static Int3 operator * (Int3 lhs, float rhs) {
lhs.x = (int)System.Math.Round (lhs.x * rhs);
lhs.y = (int)System.Math.Round (lhs.y * rhs);
lhs.z = (int)System.Math.Round (lhs.z * rhs);
return lhs;
}
public static Int3 operator * (Int3 lhs, double rhs) {
lhs.x = (int)System.Math.Round (lhs.x * rhs);
lhs.y = (int)System.Math.Round (lhs.y * rhs);
lhs.z = (int)System.Math.Round (lhs.z * rhs);
return lhs;
}
public static Int3 operator * (Int3 lhs, Vector3 rhs) {
lhs.x = (int)System.Math.Round (lhs.x * rhs.x);
lhs.y = (int)System.Math.Round (lhs.y * rhs.y);
lhs.z = (int)System.Math.Round (lhs.z * rhs.z);
return lhs;
}
public static Int3 operator / (Int3 lhs, float rhs) {
lhs.x = (int)System.Math.Round (lhs.x / rhs);
lhs.y = (int)System.Math.Round (lhs.y / rhs);
lhs.z = (int)System.Math.Round (lhs.z / rhs);
return lhs;
}
public Int3 DivBy2 () {
x >>= 1;
y >>= 1;
z >>= 1;
return this;
}
public int this[int i] {
get {
return i == 0 ? x : (i == 1 ? y : z);
}
set {
if (i == 0) x = value;
else if (i == 1) y = value;
else z = value;
}
}
/** Angle between the vectors in radians */
public static float Angle (Int3 lhs, Int3 rhs) {
double cos = Dot(lhs,rhs)/ ((double)lhs.magnitude*(double)rhs.magnitude);
cos = cos < -1 ? -1 : ( cos > 1 ? 1 : cos );
return (float)System.Math.Acos( cos );
}
public static int Dot (Int3 lhs, Int3 rhs) {
return
lhs.x * rhs.x +
lhs.y * rhs.y +
lhs.z * rhs.z;
}
public static long DotLong (Int3 lhs, Int3 rhs) {
return
(long)lhs.x * (long)rhs.x +
(long)lhs.y * (long)rhs.y +
(long)lhs.z * (long)rhs.z;
}
/** Normal in 2D space (XZ).
* Equivalent to Cross(this, Int3(0,1,0) )
* except that the Y coordinate is left unchanged with this operation.
*/
public Int3 Normal2D () {
return new Int3 ( z, y, -x );
}
public Int3 NormalizeTo (int newMagn) {
float magn = magnitude;
if (magn == 0) {
return this;
}
x *= newMagn;
y *= newMagn;
z *= newMagn;
x = (int)System.Math.Round (x/magn);
y = (int)System.Math.Round (y/magn);
z = (int)System.Math.Round (z/magn);
return this;
}
/** Returns the magnitude of the vector. The magnitude is the 'length' of the vector from 0,0,0 to this point. Can be used for distance calculations:
* \code Debug.Log ("Distance between 3,4,5 and 6,7,8 is: "+(new Int3(3,4,5) - new Int3(6,7,8)).magnitude); \endcode
*/
public float magnitude {
get {
//It turns out that using doubles is just as fast as using ints with Mathf.Sqrt. And this can also handle larger numbers (possibly with small errors when using huge numbers)!
double _x = x;
double _y = y;
double _z = z;
return (float)System.Math.Sqrt (_x*_x+_y*_y+_z*_z);
//return Mathf.Sqrt (x*x+y*y+z*z);
}
}
/** Magnitude used for the cost between two nodes. The default cost between two nodes can be calculated like this:
* \code int cost = (node1.position-node2.position).costMagnitude; \endcode
*
* This is simply the magnitude, rounded to the nearest integer
*/
public int costMagnitude {
get {
return (int)System.Math.Round (magnitude);
}
}
/** The magnitude in world units */
public float worldMagnitude {
get {
double _x = x;
double _y = y;
double _z = z;
return (float)System.Math.Sqrt (_x*_x+_y*_y+_z*_z)*PrecisionFactor;
//Scale numbers down
/*float _x = x*PrecisionFactor;
float _y = y*PrecisionFactor;
float _z = z*PrecisionFactor;
return Mathf.Sqrt (_x*_x+_y*_y+_z*_z);*/
}
}
/** The squared magnitude of the vector */
public float sqrMagnitude {
get {
double _x = x;
double _y = y;
double _z = z;
return (float)(_x*_x+_y*_y+_z*_z);
//return x*x+y*y+z*z;
}
}
/** The squared magnitude of the vector */
public long sqrMagnitudeLong {
get {
long _x = x;
long _y = y;
long _z = z;
return (_x*_x+_y*_y+_z*_z);
//return x*x+y*y+z*z;
}
}
/** \warning Can cause number overflows if the magnitude is too large */
public int unsafeSqrMagnitude {
get {
return x*x+y*y+z*z;
}
}
/** To avoid number overflows. \deprecated Int3.magnitude now uses the same implementation */
[System.Obsolete ("Same implementation as .magnitude")]
public float safeMagnitude {
get {
//Of some reason, it is faster to use doubles (almost 40% faster)
double _x = x;
double _y = y;
double _z = z;
return (float)System.Math.Sqrt (_x*_x+_y*_y+_z*_z);
//Scale numbers down
/*float _x = x*PrecisionFactor;
float _y = y*PrecisionFactor;
float _z = z*PrecisionFactor;
//Find the root and scale it up again
return Mathf.Sqrt (_x*_x+_y*_y+_z*_z)*FloatPrecision;*/
}
}
/** To avoid number overflows. The returned value is the squared magnitude of the world distance (i.e divided by Precision)
* \deprecated .sqrMagnitude is now per default safe (Int3.unsafeSqrMagnitude can be used for unsafe operations) */
[System.Obsolete (".sqrMagnitude is now per default safe (.unsafeSqrMagnitude can be used for unsafe operations)")]
public float safeSqrMagnitude {
get {
float _x = x*PrecisionFactor;
float _y = y*PrecisionFactor;
float _z = z*PrecisionFactor;
return _x*_x+_y*_y+_z*_z;
}
}
public static implicit operator string (Int3 ob) {
return ob.ToString ();
}
/** Returns a nicely formatted string representing the vector */
public override string ToString () {
return "( "+x+", "+y+", "+z+")";
}
public override bool Equals (System.Object o) {
if (o == null) return false;
Int3 rhs = (Int3)o;
return x == rhs.x &&
y == rhs.y &&
z == rhs.z;
}
public override int GetHashCode () {
return x*9+y*10+z*11;
}
}
/** Two Dimensional Integer Coordinate Pair */
public struct Int2 {
public int x;
public int y;
public Int2 (int x, int y) {
this.x = x;
this.y = y;
}
public int sqrMagnitude {
get {
return x*x+y*y;
}
}
public long sqrMagnitudeLong {
get {
return (long)x*(long)x+(long)y*(long)y;
}
}
public static Int2 operator + (Int2 a, Int2 b) {
return new Int2 (a.x+b.x, a.y+b.y);
}
public static Int2 operator - (Int2 a, Int2 b) {
return new Int2 (a.x-b.x, a.y-b.y);
}
public static bool operator == (Int2 a, Int2 b) {
return a.x == b.x && a.y == b.y;
}
public static bool operator != (Int2 a, Int2 b) {
return a.x != b.x || a.y != b.y;
}
public static int Dot (Int2 a, Int2 b) {
return a.x*b.x + a.y*b.y;
}
public static long DotLong (Int2 a, Int2 b) {
return (long)a.x*(long)b.x + (long)a.y*(long)b.y;
}
public override bool Equals (System.Object o) {
if (o == null) return false;
Int2 rhs = (Int2)o;
return x == rhs.x && y == rhs.y;
}
public override int GetHashCode () {
return x*49157+y*98317;
}
/** Matrices for rotation.
* Each group of 4 elements is a 2x2 matrix.
* The XZ position is multiplied by this.
* So
* \code
* //A rotation by 90 degrees clockwise, second matrix in the array
* (5,2) * ((0, 1), (-1, 0)) = (2,-5)
* \endcode
*/
private static readonly int[] Rotations = {
1, 0, //Identity matrix
0, 1,
0, 1,
-1, 0,
-1, 0,
0,-1,
0,-1,
1, 0
};
/** Returns a new Int2 rotated 90*r degrees around the origin. */
public static Int2 Rotate ( Int2 v, int r ) {
r = r % 4;
return new Int2 ( v.x*Rotations[r*4+0] + v.y*Rotations[r*4+1], v.x*Rotations[r*4+2] + v.y*Rotations[r*4+3] );
}
public static Int2 Min (Int2 a, Int2 b) {
return new Int2 (System.Math.Min (a.x,b.x), System.Math.Min (a.y,b.y));
}
public static Int2 Max (Int2 a, Int2 b) {
return new Int2 (System.Math.Max (a.x,b.x), System.Math.Max (a.y,b.y));
}
public static Int2 FromInt3XZ (Int3 o) {
return new Int2 (o.x,o.z);
}
public static Int3 ToInt3XZ (Int2 o) {
return new Int3 (o.x,0,o.y);
}
public override string ToString ()
{
return "("+x+", " +y+")";
}
}
}
| |
/* Copyright (c) 2006 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 Using directives
#define USE_TRACING
using System;
using System.Xml;
using System.Net;
using System.Collections;
using System.IO;
using Microsoft.Win32;
#endregion
// <summary>Contains the MediaSources currently implemented</summary>
namespace Google.GData.Client {
/// <summary>
/// placeholder for a media object to be uploaded
/// the base class only defines some primitives like content type
/// </summary>
public abstract class MediaSource {
private string contentType;
private string contentName;
/// <summary>
/// constructs a media source based on a contenttype
/// </summary>
/// <param name="contenttype">the contenttype of the file</param>
/// <returns></returns>
public MediaSource(string contenttype) {
this.ContentType = contenttype;
}
/// <summary>
/// constructs a media source based on a contenttype and a name
/// </summary>
/// <param name="name">the name of the content</param>
/// <param name="contenttype">the contenttype of the file</param>
/// <returns></returns>
public MediaSource(string name, string contenttype) {
this.Name = name;
this.ContentType = contenttype;
}
/// <summary>
/// returns the length of the content of the media source
/// </summary>
/// <returns></returns>
public abstract long ContentLength {
get;
}
/// <summary>
/// the name value of the content influence directly the slug
/// header send
/// </summary>
/// <returns></returns>
public string Name {
get {
return this.contentName;
}
set {
this.contentName = value;
}
}
/// <summary>
/// returns the contenttype of the media source, like img/jpg
/// </summary>
/// <returns></returns>
public string ContentType {
get {
return this.contentType;
}
set {
this.contentType = value;
}
}
/// <summary>
/// returns a stream of the actual content that is base64 encoded
/// </summary>
/// <returns></returns>
[Obsolete("That name was misleading. Use GetDataStream() instead")]
public abstract Stream Data {
get;
}
/// <summary>
/// returns a stream of the actual content that is base64 encoded
/// </summary>
/// <returns></returns>
public abstract Stream GetDataStream();
}
/// <summary>
/// a file based implementation. Takes a filename as it's base working mode
/// </summary>
/// <returns></returns>
public class MediaFileSource : MediaSource {
private string file;
private Stream stream;
/// <summary>
/// constructor. note that you can override the slug header without influencing the filename
/// </summary>
/// <param name="fileName">the file to be used, this will be the default slug header</param>
/// <param name="contentType">the content type to be used</param>
/// <returns></returns>
public MediaFileSource(string fileName, string contentType)
: base(fileName, contentType) {
this.file = fileName;
//strip out the path from the Slug header
FileInfo fileInfo = new FileInfo(fileName);
this.Name = fileInfo.Name;
}
/// <summary>
/// constructor. note that you can override the slug header without influencing the filename
/// </summary>
/// <param name="data">The stream for the file. If this constructor is used, the filename is only
/// used for descriptive purposes, the data will be read from the passed stream</param>
/// <param name="fileName">the file to be used, this will be the default slug header</param>
/// <param name="contentType">the content type to be used</param>
/// <returns></returns>
public MediaFileSource(Stream data, string fileName, string contentType)
: base(fileName, contentType) {
this.stream = data;
}
/// <summary>
/// tries to get a contenttype for a filename by using the classesRoot
/// in the registry. Will FAIL if that filetype is not registered with a
/// contenttype
/// </summary>
/// <param name="fileName"></param>
/// <returns>NULL or the registered contenttype</returns>
public static string GetContentTypeForFileName(string fileName) {
string ext = System.IO.Path.GetExtension(fileName).ToLower();
using (RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(ext)) {
if (registryKey != null && registryKey.GetValue("Content Type") != null) {
return registryKey.GetValue("Content Type").ToString();
}
}
return null;
}
/// <summary>
/// returns the content lenght of the file
/// </summary>
/// <returns></returns>
public override long ContentLength {
get {
long result;
try {
Stream s = this.GetDataStream();
result = s.Length;
s.Close();
} catch (NotSupportedException) {
result = -1;
}
return result;
}
}
/// <summary>
/// returns the stream for the file. The file will be opened in readonly mode
/// note, the caller has to release the resource
/// </summary>
/// <returns></returns>
[Obsolete("That name was misleading. Use GetDataStream() instead")]
public override Stream Data {
get {
return GetDataStream();
}
}
/// <summary>
/// returns the stream for the file. The file will be opened in readonly mode
/// note, the caller has to release the resource
/// </summary>
/// <returns></returns>
public override Stream GetDataStream() {
if (!String.IsNullOrEmpty(this.file)) {
return File.OpenRead(this.file);
}
var newStream = new MemoryStream();
this.stream.Position = 0;
CopyStream(this.stream, newStream);
newStream.Position = 0;
return newStream;
}
private void CopyStream(Stream input, Stream output) {
byte[] buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0) {
output.Write(buffer, 0, read);
}
}
}
}
| |
/**
* @file
*
* This file defines the base class for message bus objects that
* are implemented and registered locally.
*
*/
/******************************************************************************
* Copyright (c) 2012-2013, AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
using System;
using System.Threading;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace AllJoynUnity
{
public partial class AllJoyn
{
/**
* Message Bus Object base class
*/
public class BusObject : IDisposable
{
/**
* %BusObject constructor.
*
* @param path Object path for object.
*/
public BusObject(string path) : this(path, false) { }
/**
* %BusObject constructor.
*
* @param path Object path for object.
* @param isPlaceholder Place-holder objects are created by the bus itself and serve only
* as parent objects (in the object path sense) to other objects.
*/
public BusObject(string path, bool isPlaceholder)
{
// Can't let the GC free these delegates so they must be members
_propertyGet = new InternalPropertyGetEventHandler(this._PropertyGet);
_propertySet = new InternalPropertySetEventHandler(this._PropertySet);
_objectRegistered = new InternalObjectRegisteredEventHandler(this._ObjectRegistered);
_objectUnregistered = new InternalObjectUnregisteredEventHandler(this._ObjectUnregistered);
// Ref holder for method handler internal delegates
_methodHandlerDelegateRefHolder = new List<InternalMethodHandler>();
callbacks.property_get = Marshal.GetFunctionPointerForDelegate(_propertyGet);
callbacks.property_set = Marshal.GetFunctionPointerForDelegate(_propertySet);
callbacks.object_registered = Marshal.GetFunctionPointerForDelegate(_objectRegistered);
callbacks.object_unregistered = Marshal.GetFunctionPointerForDelegate(_objectUnregistered);
main = GCHandle.Alloc(callbacks, GCHandleType.Pinned);
_busObject = alljoyn_busobject_create(path, isPlaceholder ? 1 : 0, main.AddrOfPinnedObject(), IntPtr.Zero);
}
/**
* %BusObject constructor.
*
* Use of this BusObject constructor is depricated and will be
* removed Please use other BusObject Constructor BusObject(string, bool)
*
* @param bus Bus that this object exists on.
* @param path Object path for object.
* @param isPlaceholder Place-holder objects are created by the bus itself and serve only
* as parent objects (in the object path sense) to other objects.
*/
[Obsolete("Creation of a BusObject no longer requires a BusAttachment.")]
public BusObject(BusAttachment bus, string path, bool isPlaceholder) : this(path, isPlaceholder){}
/**
* Request the raw pointer of the AllJoyn C BusObject
*
* @return the raw pointer of the AllJoyn C BusObject
*/
public IntPtr getAddr()
{
return _busObject;
}
/**
* Add an interface to this object. If the interface has properties this will also add the
* standard property access interface. An interface must be added before its method handlers can be
* added. Note that the Peer interface (org.freedesktop.DBus.peer) is implicit on all objects and
* cannot be explicitly added, and the Properties interface (org.freedesktop,DBus.Properties) is
* automatically added when needed and cannot be explicitly added.
*
* Once an object is registered, it should not add any additional interfaces. Doing so would
* confuse remote objects that may have already introspected this object.
*
* @param iface The interface to add
*
* @return
* - QStatus.OK if the interface was successfully added.
* - QStatus.BUS_IFACE_ALREADY_EXISTS if the interface already exists.
* - An error status otherwise
*/
public QStatus AddInterface(InterfaceDescription iface)
{
return alljoyn_busobject_addinterface(_busObject, iface.UnmanagedPtr);
}
/**
* Add a method handler to this object. The interface for the method handler must have already
* been added by calling AddInterface().
*
* @param member Interface member implemented by handler.
* @param handler Method handler.
*
* @return
* - QStatus.OK if the method handler was added.
* - An error status otherwise
*/
public QStatus AddMethodHandler(InterfaceDescription.Member member, MethodHandler handler)
{
InternalMethodHandler internalMethodHandler = (IntPtr bus, IntPtr m, IntPtr msg) =>
{
MethodHandler h = handler;
h(new InterfaceDescription.Member(m), new Message(msg));
};
_methodHandlerDelegateRefHolder.Add(internalMethodHandler);
GCHandle membGch = GCHandle.Alloc(member._member, GCHandleType.Pinned);
MethodEntry entry;
entry.member = membGch.AddrOfPinnedObject();
entry.method_handler = Marshal.GetFunctionPointerForDelegate(internalMethodHandler);
GCHandle gch = GCHandle.Alloc(entry, GCHandleType.Pinned);
QStatus ret = alljoyn_busobject_addmethodhandlers(_busObject, gch.AddrOfPinnedObject(), (UIntPtr)1);
gch.Free();
membGch.Free();
return ret;
}
/**
* Reply to a method call.
*
* @param message The method call message
* @param args The reply arguments (can be NULL)
* @return
* - QStatus.OK if successful
* - An error status otherwise
*/
[Obsolete("Usage of MethodReply that takes MsgArgs been depricated. Please use MsgArg inplace of MsgArgs")]
protected QStatus MethodReply(Message message, MsgArgs args)
{
return alljoyn_busobject_methodreply_args(_busObject, message.UnmanagedPtr, args.UnmanagedPtr,
(UIntPtr)args.Length);
}
/**
* Reply to a method call.
*
* @param message The method call message
* @param args The reply arguments (can be NULL)
* @return
* - QStatus.OK if successful
* - An error status otherwise
*/
protected QStatus MethodReply(Message message, MsgArg args)
{
return alljoyn_busobject_methodreply_args(_busObject, message.UnmanagedPtr, args.UnmanagedPtr,
(UIntPtr)args.Length);
}
/**
* Reply to a method call with an error message.
*
* @param message The method call message
* @param error The name of the error
* @param errorMessage An error message string
* @return
* - QStatus.OK if successful
* - An error status otherwise
*/
protected QStatus MethodReply(Message message, string error, string errorMessage)
{
return alljoyn_busobject_methodreply_err(_busObject, message.UnmanagedPtr, error,
errorMessage);
}
/**
* Reply to a method call with an error message.
*
* @param message The method call message
* @param status The status code for the error
* @return
* - QStatus.OK if successful
* - An error status otherwise
*/
protected QStatus MethodReply(Message message, QStatus status)
{
return alljoyn_busobject_methodreply_status(_busObject, message.UnmanagedPtr, status.value);
}
/**
* Send a signal.
*
* @param destination The unique or well-known bus name or the signal recipient (NULL for broadcast signals)
* @param sessionId A unique SessionId for this AllJoyn session instance
* @param signal Interface member of signal being emitted.
* @param args The arguments for the signal (can be NULL)
* @return
* - QStatus.OK if successful
* - An error status otherwise
*/
[Obsolete("Usage of Signal that takes MsgArgs been depricated. Please use MsgArg inplace of MsgArgs")]
protected QStatus Signal(string destination, uint sessionId, InterfaceDescription.Member signal, MsgArgs args)
{
return alljoyn_busobject_signal(_busObject, destination, sessionId, signal._member, args.UnmanagedPtr, (UIntPtr)args.Length, 0, 0, IntPtr.Zero);
}
/**
* Send a signal.
*
* @param destination The unique or well-known bus name or the signal recipient (NULL for broadcast signals)
* @param sessionId A unique SessionId for this AllJoyn session instance
* @param signal Interface member of signal being emitted.
* @param args The arguments for the signal (can be NULL)
* @return
* - QStatus.OK if successful
* - An error status otherwise
*/
protected QStatus Signal(string destination, uint sessionId, InterfaceDescription.Member signal, MsgArg args)
{
return alljoyn_busobject_signal(_busObject, destination, sessionId, signal._member, args.UnmanagedPtr, (UIntPtr)args.Length, 0, 0, IntPtr.Zero);
}
/**
* Send a signal.
*
* @param destination The unique or well-known bus name or the signal recipient (NULL for broadcast signals)
* @param sessionId A unique SessionId for this AllJoyn session instance
* @param signal Interface member of signal being emitted.
* @param args The arguments for the signal (can be NULL)
* @param msg The sent signal message is returned to the caller
* @return
* - QStatus.OK if successful
* - An error status otherwise
*/
protected QStatus Signal(string destination, uint sessionId, InterfaceDescription.Member signal, MsgArg args, Message msg)
{
return alljoyn_busobject_signal(_busObject, destination, sessionId, signal._member, args.UnmanagedPtr, (UIntPtr)args.Length, 0, 0, msg.UnmanagedPtr);
}
/**
* Send a signal.
*
* @param destination The unique or well-known bus name or the signal recipient (NULL for broadcast signals)
* @param sessionId A unique SessionId for this AllJoyn session instance
* @param signal Interface member of signal being emitted.
* @param args The arguments for the signal (can be NULL)
* @param timeToLife If non-zero this specifies the useful lifetime for this signal.
* The units are milliseconds for non-sessionless signals and seconds for
* sessionless signals. If delivery of the signal is delayed beyond the
* timeToLive due to network congestion or other factors the signal may
* be discarded. There is no guarantee that expired signals will not still
* be delivered.
* @param flags Logical OR of the message flags for this signals. The following flags apply to signals:
* - If ALLJOYN_FLAG_SESSIONLESS is set the signal will be sent out to any listener without requireing a connected session.
* - If ALLJOYN_FLAG_GLOBAL_BROADCAST is set broadcast signal (null destination) will be forwarded across bus-to-bus connections.
* - If ALLJOYN_FLAG_COMPRESSED is set the header is compressed for destinations that can handle header compression.
* - If ALLJOYN_FLAG_ENCRYPTED is set the message is authenticated and the payload if any is encrypted.
* @return
* - QStatus.OK if successful
* - An error status otherwise
*/
[Obsolete("Usage of Signal that takes MsgArgs been depricated. Please use MsgArg inplace of MsgArgs")]
protected QStatus Signal(string destination, uint sessionId, InterfaceDescription.Member signal,
MsgArgs args, ushort timeToLife, byte flags)
{
return alljoyn_busobject_signal(_busObject, destination, sessionId, signal._member, args.UnmanagedPtr, (UIntPtr)args.Length, timeToLife, flags, IntPtr.Zero);
}
/**
* Send a signal.
*
* @param destination The unique or well-known bus name or the signal recipient (NULL for broadcast signals)
* @param sessionId A unique SessionId for this AllJoyn session instance
* @param signal Interface member of signal being emitted.
* @param args The arguments for the signal (can be NULL)
* @param timeToLife If non-zero this specifies in milliseconds the useful lifetime for this
* signal. If delivery of the signal is delayed beyond the timeToLive due to
* network congestion or other factors the signal may be discarded. There is
* no guarantee that expired signals will not still be delivered.
* @param flags Logical OR of the message flags for this signals. The following flags apply to signals:
* - If ALLJOYN_FLAG_SESSIONLESS is set the signal will be sent out to any listener without requireing a connected session
* - If ALLJOYN_FLAG_GLOBAL_BROADCAST is set broadcast signal (null destination) will be
* forwarded across bus-to-bus connections.
* - If ALLJOYN_FLAG_COMPRESSED is set the header is compressed for destinations that can
* handle header compression.
* - If ALLJOYN_FLAG_ENCRYPTED is set the message is authenticated and the payload if any
* is encrypted.
* @return
* - QStatus.OK if successful
* - An error status otherwise
*/
protected QStatus Signal(string destination, uint sessionId, InterfaceDescription.Member signal,
MsgArg args, ushort timeToLife, byte flags)
{
return alljoyn_busobject_signal(_busObject, destination, sessionId, signal._member, args.UnmanagedPtr, (UIntPtr)args.Length, timeToLife, flags, IntPtr.Zero);
}
/**
* Send a signal.
*
* @param destination The unique or well-known bus name or the signal recipient (NULL for broadcast signals)
* @param sessionId A unique SessionId for this AllJoyn session instance
* @param signal Interface member of signal being emitted.
* @param args The arguments for the signal (can be NULL)
* @param timeToLife If non-zero this specifies in milliseconds the useful lifetime for this
* signal. If delivery of the signal is delayed beyond the timeToLive due to
* network congestion or other factors the signal may be discarded. There is
* no guarantee that expired signals will not still be delivered.
* @param flags Logical OR of the message flags for this signals. The following flags apply to signals:
* - If ALLJOYN_FLAG_SESSIONLESS is set the signal will be sent out to any listener without
* requireing a connected session
* - If ALLJOYN_FLAG_GLOBAL_BROADCAST is set broadcast signal (null destination) will be
* forwarded across bus-to-bus connections.
* - If ALLJOYN_FLAG_COMPRESSED is set the header is compressed for destinations that can
* handle header compression.
* - If ALLJOYN_FLAG_ENCRYPTED is set the message is authenticated and the payload if any
* is encrypted.
* @param msg The sent signal message is returned to the caller.
* @return
* - QStatus.OK if successful
* - An error status otherwise
*/
protected QStatus Signal(string destination, uint sessionId, InterfaceDescription.Member signal,
MsgArg args, ushort timeToLife, byte flags, Message msg)
{
return alljoyn_busobject_signal(_busObject, destination, sessionId, signal._member, args.UnmanagedPtr, (UIntPtr)args.Length, timeToLife, flags, msg.UnmanagedPtr);
}
/**
* Remove sessionless message sent from this object from local daemon's
* store/forward cache.
*
* @param serialNumber Serial number of previously sent sessionless signal.
* @return QStatus.OK if successful.
*/
public QStatus CancelSessionlessMessage(uint serialNumber)
{
return alljoyn_busobject_cancelsessionlessmessage_serial(_busObject, serialNumber);
}
/**
* Remove sessionless message sent from this object from local daemon's
* store/forward cache.
*
* @param msg Message to be removed.
* @return QStatus.OK if successful.
*/
public QStatus CancelSessionlessMessage(Message msg)
{
return alljoyn_busobject_cancelsessionlessmessage(_busObject, msg.UnmanagedPtr);
}
#region Properties
/**
* Return the path for the object
*
* @return Object path
*/
public string Path
{
get
{
return Marshal.PtrToStringAnsi(alljoyn_busobject_getpath(_busObject));
}
}
/**
* Get the name of this object.
* The name is the last component of the path.
*
* @return Last component of object path.
*/
public string Name
{
get
{
UIntPtr nameSz = alljoyn_busobject_getname(_busObject, IntPtr.Zero, (UIntPtr)0);
byte[] sink = new byte[(int)nameSz];
GCHandle gch = GCHandle.Alloc(sink, GCHandleType.Pinned);
alljoyn_busobject_getname(_busObject, gch.AddrOfPinnedObject(), nameSz);
gch.Free();
// The returned buffer will contain a nul character an so we must remove the last character.
if ((int)nameSz != 0)
{
return System.Text.ASCIIEncoding.ASCII.GetString(sink, 0, (Int32)nameSz - 1);
}
else
{
return "";
}
}
}
/**
* Indicates if this object is secure.
*
* @param bus The busobject we want to check for security
*
* @return Return QCC_TRUE if authentication is required to emit signals or
* call methods on this object.
*/
public bool IsSecure
{
get
{
return alljoyn_busobject_issecure(_busObject);
}
}
#endregion
#region Delegates
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
/**
* MethodHandlers are %MessageReceiver methods which are called by AllJoyn library
* to forward AllJoyn method_calls to AllJoyn library users.
*
* @param member Method interface member entry.
* @param message The received method call message.
*/
public delegate void MethodHandler(InterfaceDescription.Member member, Message message);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void InternalMethodHandler(IntPtr bus, IntPtr member, IntPtr message);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void InternalPropertyGetEventHandler(IntPtr context, IntPtr ifcName, IntPtr propName, IntPtr val);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void InternalPropertySetEventHandler(IntPtr context, IntPtr ifcName, IntPtr propName, IntPtr val);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void InternalObjectRegisteredEventHandler(IntPtr context);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void InternalObjectUnregisteredEventHandler(IntPtr context);
#endregion
#region Virtual Methods
/**
* Handle a bus request to read a property from this object.
* BusObjects that implement properties should override this method.
* The default version simply returns QStatus.BUS_NO_SUCH_PROPERTY
*
* @param ifcName Identifies the interface that the property is defined on
* @param propName Identifies the the property to get
* @param[out] val Returns the property value. The type of this value is the actual value
* type.
*/
protected virtual void OnPropertyGet(string ifcName, string propName, MsgArg val)
{
}
/**
* Handle a bus attempt to write a property value to this object.
* BusObjects that implement properties should override this method.
* This default version just replies with QStatus.BUS_NO_SUCH_PROPERTY
*
* @param ifcName Identifies the interface that the property is defined on
* @param propName Identifies the the property to set
* @param val The property value to set. The type of this value is the actual value
* type.
*/
protected virtual void OnPropertySet(string ifcName, string propName, MsgArg val)
{
}
/**
* Called by the message bus when the object has been successfully registered. The object can
* perform any initialization such as adding match rules at this time.
*/
protected virtual void OnObjectRegistered()
{
}
/**
* Called by the message bus when the object has been successfully unregistered
* @remark
* This base class implementation @b must be called explicitly by any overriding derived class.
*/
protected virtual void OnObjectUnregistered()
{
}
#endregion
#region Callbacks
private void _PropertyGet(IntPtr context, IntPtr ifcName, IntPtr propName, IntPtr val)
{
OnPropertyGet(Marshal.PtrToStringAnsi(ifcName),
Marshal.PtrToStringAnsi(propName), new MsgArg(val));
}
private void _PropertySet(IntPtr context, IntPtr ifcName, IntPtr propName, IntPtr val)
{
OnPropertySet(Marshal.PtrToStringAnsi(ifcName),
Marshal.PtrToStringAnsi(propName), new MsgArg(val));
}
private void _ObjectRegistered(IntPtr context)
{
OnObjectRegistered();
}
private void _ObjectUnregistered(IntPtr context)
{
OnObjectUnregistered();
}
#endregion
#region DLL Imports
[DllImport(DLL_IMPORT_TARGET)]
private extern static IntPtr alljoyn_busobject_create(
[MarshalAs(UnmanagedType.LPStr)] string path,
int isPlaceholder,
IntPtr callbacks_in,
IntPtr context_in);
[DllImport(DLL_IMPORT_TARGET)]
private extern static IntPtr alljoyn_busobject_destroy(IntPtr bus);
[DllImport(DLL_IMPORT_TARGET)]
private extern static IntPtr alljoyn_busobject_getpath(IntPtr bus);
[DllImport(DLL_IMPORT_TARGET)]
private extern static UIntPtr alljoyn_busobject_getname(IntPtr bus, IntPtr buffer, UIntPtr bufferSz);
[DllImport(DLL_IMPORT_TARGET)]
private extern static int alljoyn_busobject_addinterface(IntPtr bus, IntPtr iface);
[DllImport(DLL_IMPORT_TARGET)]
private extern static int alljoyn_busobject_addmethodhandlers(IntPtr bus,
IntPtr entries, UIntPtr numEntries);
[DllImport(DLL_IMPORT_TARGET)]
private extern static int alljoyn_busobject_methodreply_args(IntPtr bus,
IntPtr msg, IntPtr msgArgs, UIntPtr numArgs);
[DllImport(DLL_IMPORT_TARGET)]
private extern static int alljoyn_busobject_methodreply_err(IntPtr bus, IntPtr msg,
[MarshalAs(UnmanagedType.LPStr)] string error,
[MarshalAs(UnmanagedType.LPStr)] string errorMsg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static int alljoyn_busobject_methodreply_status(IntPtr bus, IntPtr msg, int status);
[DllImport(DLL_IMPORT_TARGET)]
private extern static int alljoyn_busobject_signal(IntPtr bus,
[MarshalAs(UnmanagedType.LPStr)] string destination,
uint sessionId,
InterfaceDescription._Member signal,
IntPtr msgArgs, UIntPtr numArgs,
ushort timeToLive, byte flags, IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
private extern static int alljoyn_busobject_cancelsessionlessmessage_serial(IntPtr bus, uint serialNumber);
[DllImport(DLL_IMPORT_TARGET)]
private extern static int alljoyn_busobject_cancelsessionlessmessage(IntPtr bus, IntPtr msg);
[DllImport(DLL_IMPORT_TARGET)]
[return: MarshalAs(UnmanagedType.U1)]
private extern static bool alljoyn_busobject_issecure(IntPtr bus);
#endregion
#region IDisposable
~BusObject()
{
Dispose(false);
}
/**
* Dispose the BusObject
* @param disposing describes if its activly being disposed
*/
protected virtual void Dispose(bool disposing)
{
if(!_isDisposed)
{
Thread destroyThread = new Thread((object o) => {
alljoyn_busobject_destroy(_busObject);
});
destroyThread.Start();
while(destroyThread.IsAlive)
{
AllJoyn.TriggerCallbacks();
Thread.Sleep(0);
}
_busObject = IntPtr.Zero;
main.Free();
}
_isDisposed = true;
}
/**
* Dispose the BusObject
*/
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Structs
[StructLayout(LayoutKind.Sequential)]
private struct BusObjectCallbacks
{
public IntPtr property_get;
public IntPtr property_set;
public IntPtr object_registered;
public IntPtr object_unregistered;
}
[StructLayout(LayoutKind.Sequential)]
private struct MethodEntry
{
public IntPtr member;
public IntPtr method_handler;
}
#endregion
#region Internal Properties
internal IntPtr UnmanagedPtr
{
get
{
return _busObject;
}
}
#endregion
#region Data
IntPtr _busObject;
bool _isDisposed = false;
GCHandle main;
InternalPropertyGetEventHandler _propertyGet;
InternalPropertySetEventHandler _propertySet;
InternalObjectRegisteredEventHandler _objectRegistered;
InternalObjectUnregisteredEventHandler _objectUnregistered;
BusObjectCallbacks callbacks;
List<InternalMethodHandler> _methodHandlerDelegateRefHolder;
#endregion
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*=============================================================================
**
** Class: UCOMITypeInfo
**
**
** Purpose: UCOMITypeInfo interface definition.
**
**
=============================================================================*/
namespace System.Runtime.InteropServices
{
using System;
[Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[Serializable]
public enum TYPEKIND
{
TKIND_ENUM = 0,
TKIND_RECORD = TKIND_ENUM + 1,
TKIND_MODULE = TKIND_RECORD + 1,
TKIND_INTERFACE = TKIND_MODULE + 1,
TKIND_DISPATCH = TKIND_INTERFACE + 1,
TKIND_COCLASS = TKIND_DISPATCH + 1,
TKIND_ALIAS = TKIND_COCLASS + 1,
TKIND_UNION = TKIND_ALIAS + 1,
TKIND_MAX = TKIND_UNION + 1
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[Serializable]
[Flags()]
public enum TYPEFLAGS : short
{
TYPEFLAG_FAPPOBJECT = 0x1,
TYPEFLAG_FCANCREATE = 0x2,
TYPEFLAG_FLICENSED = 0x4,
TYPEFLAG_FPREDECLID = 0x8,
TYPEFLAG_FHIDDEN = 0x10,
TYPEFLAG_FCONTROL = 0x20,
TYPEFLAG_FDUAL = 0x40,
TYPEFLAG_FNONEXTENSIBLE = 0x80,
TYPEFLAG_FOLEAUTOMATION = 0x100,
TYPEFLAG_FRESTRICTED = 0x200,
TYPEFLAG_FAGGREGATABLE = 0x400,
TYPEFLAG_FREPLACEABLE = 0x800,
TYPEFLAG_FDISPATCHABLE = 0x1000,
TYPEFLAG_FREVERSEBIND = 0x2000,
TYPEFLAG_FPROXY = 0x4000
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.IMPLTYPEFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[Serializable]
[Flags()]
public enum IMPLTYPEFLAGS
{
IMPLTYPEFLAG_FDEFAULT = 0x1,
IMPLTYPEFLAG_FSOURCE = 0x2,
IMPLTYPEFLAG_FRESTRICTED = 0x4,
IMPLTYPEFLAG_FDEFAULTVTABLE = 0x8,
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEATTR instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct TYPEATTR
{
// Constant used with the memid fields.
public const int MEMBER_ID_NIL = unchecked((int)0xFFFFFFFF);
// Actual fields of the TypeAttr struct.
public Guid guid;
public Int32 lcid;
public Int32 dwReserved;
public Int32 memidConstructor;
public Int32 memidDestructor;
public IntPtr lpstrSchema;
public Int32 cbSizeInstance;
public TYPEKIND typekind;
public Int16 cFuncs;
public Int16 cVars;
public Int16 cImplTypes;
public Int16 cbSizeVft;
public Int16 cbAlignment;
public TYPEFLAGS wTypeFlags;
public Int16 wMajorVerNum;
public Int16 wMinorVerNum;
public TYPEDESC tdescAlias;
public IDLDESC idldescType;
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.FUNCDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[StructLayout(LayoutKind.Sequential)]
public struct FUNCDESC
{
public int memid; //MEMBERID memid;
public IntPtr lprgscode; // /* [size_is(cScodes)] */ SCODE RPC_FAR *lprgscode;
public IntPtr lprgelemdescParam; // /* [size_is(cParams)] */ ELEMDESC __RPC_FAR *lprgelemdescParam;
public FUNCKIND funckind; //FUNCKIND funckind;
public INVOKEKIND invkind; //INVOKEKIND invkind;
public CALLCONV callconv; //CALLCONV callconv;
public Int16 cParams; //short cParams;
public Int16 cParamsOpt; //short cParamsOpt;
public Int16 oVft; //short oVft;
public Int16 cScodes; //short cScodes;
public ELEMDESC elemdescFunc; //ELEMDESC elemdescFunc;
public Int16 wFuncFlags; //WORD wFuncFlags;
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.IDLFLAG instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[Serializable]
[Flags()]
public enum IDLFLAG : short
{
IDLFLAG_NONE = PARAMFLAG.PARAMFLAG_NONE,
IDLFLAG_FIN = PARAMFLAG.PARAMFLAG_FIN,
IDLFLAG_FOUT = PARAMFLAG.PARAMFLAG_FOUT,
IDLFLAG_FLCID = PARAMFLAG.PARAMFLAG_FLCID,
IDLFLAG_FRETVAL = PARAMFLAG.PARAMFLAG_FRETVAL
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.IDLDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct IDLDESC
{
public int dwReserved;
public IDLFLAG wIDLFlags;
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.PARAMFLAG instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[Serializable]
[Flags()]
public enum PARAMFLAG :short
{
PARAMFLAG_NONE = 0,
PARAMFLAG_FIN = 0x1,
PARAMFLAG_FOUT = 0x2,
PARAMFLAG_FLCID = 0x4,
PARAMFLAG_FRETVAL = 0x8,
PARAMFLAG_FOPT = 0x10,
PARAMFLAG_FHASDEFAULT = 0x20,
PARAMFLAG_FHASCUSTDATA = 0x40
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.PARAMDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct PARAMDESC
{
public IntPtr lpVarValue;
public PARAMFLAG wParamFlags;
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.TYPEDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct TYPEDESC
{
public IntPtr lpValue;
public Int16 vt;
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.ELEMDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct ELEMDESC
{
public TYPEDESC tdesc;
[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
[ComVisible(false)]
public struct DESCUNION
{
[FieldOffset(0)]
public IDLDESC idldesc;
[FieldOffset(0)]
public PARAMDESC paramdesc;
};
public DESCUNION desc;
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.VARDESC instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct VARDESC
{
public int memid;
public String lpstrSchema;
[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
[ComVisible(false)]
public struct DESCUNION
{
[FieldOffset(0)]
public int oInst;
[FieldOffset(0)]
public IntPtr lpvarValue;
};
public ELEMDESC elemdescVar;
public short wVarFlags;
public VarEnum varkind;
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.DISPPARAMS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct DISPPARAMS
{
public IntPtr rgvarg;
public IntPtr rgdispidNamedArgs;
public int cArgs;
public int cNamedArgs;
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.EXCEPINFO instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct EXCEPINFO
{
public Int16 wCode;
public Int16 wReserved;
[MarshalAs(UnmanagedType.BStr)] public String bstrSource;
[MarshalAs(UnmanagedType.BStr)] public String bstrDescription;
[MarshalAs(UnmanagedType.BStr)] public String bstrHelpFile;
public int dwHelpContext;
public IntPtr pvReserved;
public IntPtr pfnDeferredFillIn;
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.FUNCKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[Serializable]
public enum FUNCKIND : int
{
FUNC_VIRTUAL = 0,
FUNC_PUREVIRTUAL = 1,
FUNC_NONVIRTUAL = 2,
FUNC_STATIC = 3,
FUNC_DISPATCH = 4
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.INVOKEKIND instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[Serializable]
public enum INVOKEKIND : int
{
INVOKE_FUNC = 0x1,
INVOKE_PROPERTYGET = 0x2,
INVOKE_PROPERTYPUT = 0x4,
INVOKE_PROPERTYPUTREF = 0x8
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.CALLCONV instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[Serializable]
public enum CALLCONV : int
{
CC_CDECL =1,
CC_MSCPASCAL=2,
CC_PASCAL =CC_MSCPASCAL,
CC_MACPASCAL=3,
CC_STDCALL =4,
CC_RESERVED =5,
CC_SYSCALL =6,
CC_MPWCDECL =7,
CC_MPWPASCAL=8,
CC_MAX =9
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.FUNCFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[Serializable]
[Flags()]
public enum FUNCFLAGS : short
{
FUNCFLAG_FRESTRICTED= 0x1,
FUNCFLAG_FSOURCE = 0x2,
FUNCFLAG_FBINDABLE = 0x4,
FUNCFLAG_FREQUESTEDIT = 0x8,
FUNCFLAG_FDISPLAYBIND = 0x10,
FUNCFLAG_FDEFAULTBIND = 0x20,
FUNCFLAG_FHIDDEN = 0x40,
FUNCFLAG_FUSESGETLASTERROR= 0x80,
FUNCFLAG_FDEFAULTCOLLELEM= 0x100,
FUNCFLAG_FUIDEFAULT = 0x200,
FUNCFLAG_FNONBROWSABLE = 0x400,
FUNCFLAG_FREPLACEABLE = 0x800,
FUNCFLAG_FIMMEDIATEBIND = 0x1000
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.VARFLAGS instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[Serializable]
[Flags()]
public enum VARFLAGS : short
{
VARFLAG_FREADONLY =0x1,
VARFLAG_FSOURCE =0x2,
VARFLAG_FBINDABLE =0x4,
VARFLAG_FREQUESTEDIT =0x8,
VARFLAG_FDISPLAYBIND =0x10,
VARFLAG_FDEFAULTBIND =0x20,
VARFLAG_FHIDDEN =0x40,
VARFLAG_FRESTRICTED =0x80,
VARFLAG_FDEFAULTCOLLELEM =0x100,
VARFLAG_FUIDEFAULT =0x200,
VARFLAG_FNONBROWSABLE =0x400,
VARFLAG_FREPLACEABLE =0x800,
VARFLAG_FIMMEDIATEBIND =0x1000
}
[Obsolete("Use System.Runtime.InteropServices.ComTypes.ITypeInfo instead. http://go.microsoft.com/fwlink/?linkid=14202", false)]
[Guid("00020401-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface UCOMITypeInfo
{
void GetTypeAttr(out IntPtr ppTypeAttr);
void GetTypeComp(out UCOMITypeComp ppTComp);
void GetFuncDesc(int index, out IntPtr ppFuncDesc);
void GetVarDesc(int index, out IntPtr ppVarDesc);
void GetNames(int memid, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2), Out] String[] rgBstrNames, int cMaxNames, out int pcNames);
void GetRefTypeOfImplType(int index, out int href);
void GetImplTypeFlags(int index, out int pImplTypeFlags);
void GetIDsOfNames([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1), In] String[] rgszNames, int cNames, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] int[] pMemId);
void Invoke([MarshalAs(UnmanagedType.IUnknown)] Object pvInstance, int memid, Int16 wFlags, ref DISPPARAMS pDispParams, out Object pVarResult, out EXCEPINFO pExcepInfo, out int puArgErr);
void GetDocumentation(int index, out String strName, out String strDocString, out int dwHelpContext, out String strHelpFile);
void GetDllEntry(int memid, INVOKEKIND invKind, out String pBstrDllName, out String pBstrName, out Int16 pwOrdinal);
void GetRefTypeInfo(int hRef, out UCOMITypeInfo ppTI);
void AddressOfMember(int memid, INVOKEKIND invKind, out IntPtr ppv);
void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] Object pUnkOuter, ref Guid riid, [MarshalAs(UnmanagedType.IUnknown), Out] out Object ppvObj);
void GetMops(int memid, out String pBstrMops);
void GetContainingTypeLib(out UCOMITypeLib ppTLB, out int pIndex);
void ReleaseTypeAttr(IntPtr pTypeAttr);
void ReleaseFuncDesc(IntPtr pFuncDesc);
void ReleaseVarDesc(IntPtr pVarDesc);
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Alistair Leslie-Hughes
*
* 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.Runtime.InteropServices;
namespace Microsoft.DirectX.Direct3D
{
public struct Caps
{
[StructLayout(LayoutKind.Sequential)]
internal struct D3DVSHADERCAPS2_0
{
public uint Caps;
public int DynamicFlowControlDepth;
public int NumTemps;
public int StaticFlowControlDepth;
}
[StructLayout(LayoutKind.Sequential)]
internal struct D3DPSHADERCAPS2_0
{
public uint Caps;
public int DynamicFlowControlDepth;
public int NumTemps;
public int StaticFlowControlDepth;
public int NumInstructionSlots;
}
[StructLayout(LayoutKind.Sequential)]
internal struct D3DCAPS9
{
public uint DeviceType;
public uint AdapterOrdinal;
public uint Caps;
public uint Caps2;
public uint Caps3;
public uint PresentationIntervals;
public uint CursorCaps;
public uint DevCaps;
public uint PrimitiveMiscCaps;
public uint RasterCaps;
public uint ZCmpCaps;
public uint SrcBlendCaps;
public uint DestBlendCaps;
public uint AlphaCmpCaps;
public uint ShadeCaps;
public uint TextureCaps;
public uint TextureFilterCaps;
public uint CubeTextureFilterCaps;
public uint VolumeTextureFilterCaps;
public uint TextureAddressCaps;
public uint VolumeTextureAddressCaps;
public uint LineCaps;
public uint MaxTextureWidth;
public uint MaxTextureHeight;
public uint MaxVolumeExtent;
public uint MaxTextureRepeat;
public uint MaxTextureAspectRatio;
public uint MaxAnisotropy;
public float MaxVertexW;
public float GuardBandLeft;
public float GuardBandTop;
public float GuardBandRight;
public float GuardBandBottom;
public float ExtentsAdjust;
public uint StencilCaps;
public uint FVFCaps;
public uint TextureOpCaps;
public uint MaxTextureBlendStages;
public uint MaxSimultaneousTextures;
public uint VertexProcessingCaps;
public uint MaxActiveLights;
public uint MaxUserClipPlanes;
public uint MaxVertexBlendMatrices;
public uint MaxVertexBlendMatrixIndex;
public float MaxPointSize;
public uint MaxPrimitiveCount;
public uint MaxVertexIndex;
public uint MaxStreams;
public uint MaxStreamStride;
public uint VertexShaderVersion;
public uint MaxVertexShaderConst;
public uint PixelShaderVersion;
public float PixelShader1xMaxValue;
public uint DevCaps2;
public float MaxNpatchTessellationLevel;
public uint Reserved5;
public uint MasterAdapterOrdinal;
public uint AdapterOrdinalInGroup;
public uint NumberOfAdaptersInGroup;
public uint DeclTypes;
public uint NumSimultaneousRTs;
public uint StretchRectFilterCaps;
public D3DVSHADERCAPS2_0 VS20Caps;
public D3DPSHADERCAPS2_0 PS20Caps;
public uint VertexTextureFilterCaps;
public uint MaxVShaderInstructionsExecuted;
public uint MaxPShaderInstructionsExecuted;
public uint MaxVertexShader30InstructionSlots;
public uint MaxPixelShader30InstructionSlots;
}
private D3DCAPS9 _caps;
internal Caps(D3DCAPS9 caps)
{
_caps = caps;
}
public PixelShaderCaps PixelShaderCaps {
get {
throw new NotImplementedException ();
}
}
public VertexShaderCaps VertexShaderCaps {
get {
throw new NotImplementedException ();
}
}
public int MaxPixelShader30InstructionSlots {
get {
return (int)_caps.MaxPixelShader30InstructionSlots;
}
}
public int MaxVertexShader30InstructionSlots {
get {
return (int)_caps.MaxVertexShader30InstructionSlots;
}
}
public Version PixelShaderVersion {
get {
return new Version((int)(_caps.PixelShaderVersion >> 8) & 0xff, (int)_caps.PixelShaderVersion & 0xff);
}
}
public Version VertexShaderVersion {
get {
return new Version((int)(_caps.VertexShaderVersion >> 8) & 0xff, (int)_caps.VertexShaderVersion & 0xff);
}
}
public DeclarationTypeCaps DeclTypes {
get {
throw new NotImplementedException ();
}
}
public VertexProcessingCaps VertexProcessingCaps {
get {
throw new NotImplementedException ();
}
}
public VertexFormatCaps VertexFormatCaps {
get {
throw new NotImplementedException ();
}
}
public TextureOperationCaps TextureOperationCaps {
get {
throw new NotImplementedException ();
}
}
public StencilCaps StencilCaps {
get {
throw new NotImplementedException ();
}
}
public AddressCaps VolumeTextureAddressCaps {
get {
throw new NotImplementedException ();
}
}
public AddressCaps TextureAddressCaps {
get {
throw new NotImplementedException ();
}
}
public FilterCaps VolumeTextureFilterCaps {
get {
throw new NotImplementedException ();
}
}
public FilterCaps CubeTextureFilterCaps {
get {
throw new NotImplementedException ();
}
}
public FilterCaps TextureFilterCaps {
get {
throw new NotImplementedException ();
}
}
public FilterCaps VertexTextureFilterCaps {
get {
throw new NotImplementedException ();
}
}
public FilterCaps StretchRectangleFilterCaps {
get {
throw new NotImplementedException ();
}
}
public TextureCaps TextureCaps {
get {
throw new NotImplementedException ();
}
}
public int NumberOfAdaptersInGroup {
get {
return (int)_caps.NumberOfAdaptersInGroup;
}
}
public int AdapterOrdinalInGroup {
get {
return (int)_caps.AdapterOrdinalInGroup;
}
}
public int MasterAdapterOrdinal {
get {
return (int)_caps.MasterAdapterOrdinal;
}
}
public int MaxVertexShaderConst {
get {
return (int)_caps.MaxVertexShaderConst;
}
}
public int MaxSimultaneousTextures {
get {
return (int)_caps.MaxSimultaneousTextures;
;
}
}
public int MaxTextureBlendStages {
get {
return (int)_caps.MaxTextureBlendStages;
}
}
public ShadeCaps ShadeCaps {
get {
throw new NotImplementedException ();
}
}
public LineCaps LineCaps {
get {
throw new NotImplementedException ();
}
}
public int NumberSimultaneousRts {
get {
return (int)_caps.NumSimultaneousRTs;
}
}
public float PixelShader1xMaxValue {
get {
return _caps.PixelShader1xMaxValue;
}
}
public int MaxStreamStride {
get {
return (int)_caps.MaxStreamStride;
}
}
public int MaxStreams {
get {
return (int)_caps.MaxStreams;
}
}
public int MaxVertexIndex {
get {
return (int)_caps.MaxVertexIndex;
}
}
public int MaxPrimitiveCount {
get {
return (int)_caps.MaxPrimitiveCount;
}
}
public float MaxPointSize {
get {
return _caps.MaxPointSize;
}
}
public int MaxVertexBlendMatrixIndex {
get {
return (int)_caps.MaxVertexBlendMatrixIndex;
}
}
public int MaxVertexBlendMatrices {
get {
return (int)_caps.MaxVertexBlendMatrices;
}
}
public int MaxUserClipPlanes {
get {
return (int)_caps.MaxUserClipPlanes;
}
}
public int MaxActiveLights {
get {
return (int)_caps.MaxActiveLights;
}
}
public float ExtentsAdjust {
get {
return _caps.ExtentsAdjust;
}
}
public float GuardBandBottom {
get {
return _caps.GuardBandBottom;
}
}
public float GuardBandRight {
get {
return _caps.GuardBandRight;
}
}
public float GuardBandTop {
get {
return _caps.GuardBandTop;
}
}
public float GuardBandLeft {
get {
return _caps.GuardBandLeft;
}
}
public float MaxVertexW {
get {
return _caps.MaxVertexW;
}
}
public int MaxAnisotropy {
get {
return (int)_caps.MaxAnisotropy;
}
}
public int MaxTextureAspectRatio {
get {
return (int)_caps.MaxTextureAspectRatio;
}
}
public int MaxTextureRepeat {
get {
return (int)_caps.MaxTextureRepeat;
}
}
public int MaxVolumeExtent {
get {
return (int)_caps.MaxVolumeExtent;
}
}
public int MaxTextureHeight {
get {
return (int)_caps.MaxTextureHeight;
}
}
public int MaxTextureWidth {
get {
return (int)_caps.MaxTextureWidth;
}
}
public BlendCaps DestinationBlendCaps {
get {
throw new NotImplementedException ();
}
}
public BlendCaps SourceBlendCaps {
get {
throw new NotImplementedException ();
}
}
public ComparisonCaps AlphaCompareCaps {
get {
throw new NotImplementedException ();
}
}
public ComparisonCaps ZCompareCaps {
get {
throw new NotImplementedException ();
}
}
public RasterCaps RasterCaps {
get {
throw new NotImplementedException ();
}
}
public MiscCaps PrimitiveMiscCaps {
get {
throw new NotImplementedException ();
}
}
public DeviceCaps DeviceCaps {
get {
return new DeviceCaps(_caps.DevCaps, _caps.DevCaps2);
}
}
public CursorCaps CursorCaps {
get {
throw new NotImplementedException ();
}
}
public PresentInterval PresentationIntervals {
get {
return (PresentInterval)_caps.PresentationIntervals;
}
}
public DriverCaps DriverCaps {
get {
throw new NotImplementedException ();
}
}
public int AdapterOrdinal {
get {
return (int)_caps.AdapterOrdinal;
}
}
public DeviceType DeviceType {
get {
throw new NotImplementedException ();
}
}
public float MaxNPatchTessellationLevel {
get {
return _caps.MaxNpatchTessellationLevel;
}
}
public override string ToString ()
{
throw new NotImplementedException ();
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Iam.Credentials.V1.Snippets
{
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedIAMCredentialsClientSnippets
{
/// <summary>Snippet for GenerateAccessToken</summary>
public void GenerateAccessTokenRequestObject()
{
// Snippet: GenerateAccessToken(GenerateAccessTokenRequest, CallSettings)
// Create client
IAMCredentialsClient iAMCredentialsClient = IAMCredentialsClient.Create();
// Initialize request argument(s)
GenerateAccessTokenRequest request = new GenerateAccessTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates = { "", },
Scope = { "", },
Lifetime = new Duration(),
};
// Make the request
GenerateAccessTokenResponse response = iAMCredentialsClient.GenerateAccessToken(request);
// End snippet
}
/// <summary>Snippet for GenerateAccessTokenAsync</summary>
public async Task GenerateAccessTokenRequestObjectAsync()
{
// Snippet: GenerateAccessTokenAsync(GenerateAccessTokenRequest, CallSettings)
// Additional: GenerateAccessTokenAsync(GenerateAccessTokenRequest, CancellationToken)
// Create client
IAMCredentialsClient iAMCredentialsClient = await IAMCredentialsClient.CreateAsync();
// Initialize request argument(s)
GenerateAccessTokenRequest request = new GenerateAccessTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates = { "", },
Scope = { "", },
Lifetime = new Duration(),
};
// Make the request
GenerateAccessTokenResponse response = await iAMCredentialsClient.GenerateAccessTokenAsync(request);
// End snippet
}
/// <summary>Snippet for GenerateAccessToken</summary>
public void GenerateAccessToken()
{
// Snippet: GenerateAccessToken(string, IEnumerable<string>, IEnumerable<string>, Duration, CallSettings)
// Create client
IAMCredentialsClient iAMCredentialsClient = IAMCredentialsClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/serviceAccounts/[SERVICE_ACCOUNT]";
IEnumerable<string> delegates = new string[] { "", };
IEnumerable<string> scope = new string[] { "", };
Duration lifetime = new Duration();
// Make the request
GenerateAccessTokenResponse response = iAMCredentialsClient.GenerateAccessToken(name, delegates, scope, lifetime);
// End snippet
}
/// <summary>Snippet for GenerateAccessTokenAsync</summary>
public async Task GenerateAccessTokenAsync()
{
// Snippet: GenerateAccessTokenAsync(string, IEnumerable<string>, IEnumerable<string>, Duration, CallSettings)
// Additional: GenerateAccessTokenAsync(string, IEnumerable<string>, IEnumerable<string>, Duration, CancellationToken)
// Create client
IAMCredentialsClient iAMCredentialsClient = await IAMCredentialsClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/serviceAccounts/[SERVICE_ACCOUNT]";
IEnumerable<string> delegates = new string[] { "", };
IEnumerable<string> scope = new string[] { "", };
Duration lifetime = new Duration();
// Make the request
GenerateAccessTokenResponse response = await iAMCredentialsClient.GenerateAccessTokenAsync(name, delegates, scope, lifetime);
// End snippet
}
/// <summary>Snippet for GenerateAccessToken</summary>
public void GenerateAccessTokenResourceNames()
{
// Snippet: GenerateAccessToken(ServiceAccountName, IEnumerable<string>, IEnumerable<string>, Duration, CallSettings)
// Create client
IAMCredentialsClient iAMCredentialsClient = IAMCredentialsClient.Create();
// Initialize request argument(s)
ServiceAccountName name = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]");
IEnumerable<string> delegates = new string[] { "", };
IEnumerable<string> scope = new string[] { "", };
Duration lifetime = new Duration();
// Make the request
GenerateAccessTokenResponse response = iAMCredentialsClient.GenerateAccessToken(name, delegates, scope, lifetime);
// End snippet
}
/// <summary>Snippet for GenerateAccessTokenAsync</summary>
public async Task GenerateAccessTokenResourceNamesAsync()
{
// Snippet: GenerateAccessTokenAsync(ServiceAccountName, IEnumerable<string>, IEnumerable<string>, Duration, CallSettings)
// Additional: GenerateAccessTokenAsync(ServiceAccountName, IEnumerable<string>, IEnumerable<string>, Duration, CancellationToken)
// Create client
IAMCredentialsClient iAMCredentialsClient = await IAMCredentialsClient.CreateAsync();
// Initialize request argument(s)
ServiceAccountName name = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]");
IEnumerable<string> delegates = new string[] { "", };
IEnumerable<string> scope = new string[] { "", };
Duration lifetime = new Duration();
// Make the request
GenerateAccessTokenResponse response = await iAMCredentialsClient.GenerateAccessTokenAsync(name, delegates, scope, lifetime);
// End snippet
}
/// <summary>Snippet for GenerateIdToken</summary>
public void GenerateIdTokenRequestObject()
{
// Snippet: GenerateIdToken(GenerateIdTokenRequest, CallSettings)
// Create client
IAMCredentialsClient iAMCredentialsClient = IAMCredentialsClient.Create();
// Initialize request argument(s)
GenerateIdTokenRequest request = new GenerateIdTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates = { "", },
Audience = "",
IncludeEmail = false,
};
// Make the request
GenerateIdTokenResponse response = iAMCredentialsClient.GenerateIdToken(request);
// End snippet
}
/// <summary>Snippet for GenerateIdTokenAsync</summary>
public async Task GenerateIdTokenRequestObjectAsync()
{
// Snippet: GenerateIdTokenAsync(GenerateIdTokenRequest, CallSettings)
// Additional: GenerateIdTokenAsync(GenerateIdTokenRequest, CancellationToken)
// Create client
IAMCredentialsClient iAMCredentialsClient = await IAMCredentialsClient.CreateAsync();
// Initialize request argument(s)
GenerateIdTokenRequest request = new GenerateIdTokenRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates = { "", },
Audience = "",
IncludeEmail = false,
};
// Make the request
GenerateIdTokenResponse response = await iAMCredentialsClient.GenerateIdTokenAsync(request);
// End snippet
}
/// <summary>Snippet for GenerateIdToken</summary>
public void GenerateIdToken()
{
// Snippet: GenerateIdToken(string, IEnumerable<string>, string, bool, CallSettings)
// Create client
IAMCredentialsClient iAMCredentialsClient = IAMCredentialsClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/serviceAccounts/[SERVICE_ACCOUNT]";
IEnumerable<string> delegates = new string[] { "", };
string audience = "";
bool includeEmail = false;
// Make the request
GenerateIdTokenResponse response = iAMCredentialsClient.GenerateIdToken(name, delegates, audience, includeEmail);
// End snippet
}
/// <summary>Snippet for GenerateIdTokenAsync</summary>
public async Task GenerateIdTokenAsync()
{
// Snippet: GenerateIdTokenAsync(string, IEnumerable<string>, string, bool, CallSettings)
// Additional: GenerateIdTokenAsync(string, IEnumerable<string>, string, bool, CancellationToken)
// Create client
IAMCredentialsClient iAMCredentialsClient = await IAMCredentialsClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/serviceAccounts/[SERVICE_ACCOUNT]";
IEnumerable<string> delegates = new string[] { "", };
string audience = "";
bool includeEmail = false;
// Make the request
GenerateIdTokenResponse response = await iAMCredentialsClient.GenerateIdTokenAsync(name, delegates, audience, includeEmail);
// End snippet
}
/// <summary>Snippet for GenerateIdToken</summary>
public void GenerateIdTokenResourceNames()
{
// Snippet: GenerateIdToken(ServiceAccountName, IEnumerable<string>, string, bool, CallSettings)
// Create client
IAMCredentialsClient iAMCredentialsClient = IAMCredentialsClient.Create();
// Initialize request argument(s)
ServiceAccountName name = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]");
IEnumerable<string> delegates = new string[] { "", };
string audience = "";
bool includeEmail = false;
// Make the request
GenerateIdTokenResponse response = iAMCredentialsClient.GenerateIdToken(name, delegates, audience, includeEmail);
// End snippet
}
/// <summary>Snippet for GenerateIdTokenAsync</summary>
public async Task GenerateIdTokenResourceNamesAsync()
{
// Snippet: GenerateIdTokenAsync(ServiceAccountName, IEnumerable<string>, string, bool, CallSettings)
// Additional: GenerateIdTokenAsync(ServiceAccountName, IEnumerable<string>, string, bool, CancellationToken)
// Create client
IAMCredentialsClient iAMCredentialsClient = await IAMCredentialsClient.CreateAsync();
// Initialize request argument(s)
ServiceAccountName name = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]");
IEnumerable<string> delegates = new string[] { "", };
string audience = "";
bool includeEmail = false;
// Make the request
GenerateIdTokenResponse response = await iAMCredentialsClient.GenerateIdTokenAsync(name, delegates, audience, includeEmail);
// End snippet
}
/// <summary>Snippet for SignBlob</summary>
public void SignBlobRequestObject()
{
// Snippet: SignBlob(SignBlobRequest, CallSettings)
// Create client
IAMCredentialsClient iAMCredentialsClient = IAMCredentialsClient.Create();
// Initialize request argument(s)
SignBlobRequest request = new SignBlobRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates = { "", },
Payload = ByteString.Empty,
};
// Make the request
SignBlobResponse response = iAMCredentialsClient.SignBlob(request);
// End snippet
}
/// <summary>Snippet for SignBlobAsync</summary>
public async Task SignBlobRequestObjectAsync()
{
// Snippet: SignBlobAsync(SignBlobRequest, CallSettings)
// Additional: SignBlobAsync(SignBlobRequest, CancellationToken)
// Create client
IAMCredentialsClient iAMCredentialsClient = await IAMCredentialsClient.CreateAsync();
// Initialize request argument(s)
SignBlobRequest request = new SignBlobRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates = { "", },
Payload = ByteString.Empty,
};
// Make the request
SignBlobResponse response = await iAMCredentialsClient.SignBlobAsync(request);
// End snippet
}
/// <summary>Snippet for SignBlob</summary>
public void SignBlob()
{
// Snippet: SignBlob(string, IEnumerable<string>, ByteString, CallSettings)
// Create client
IAMCredentialsClient iAMCredentialsClient = IAMCredentialsClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/serviceAccounts/[SERVICE_ACCOUNT]";
IEnumerable<string> delegates = new string[] { "", };
ByteString payload = ByteString.Empty;
// Make the request
SignBlobResponse response = iAMCredentialsClient.SignBlob(name, delegates, payload);
// End snippet
}
/// <summary>Snippet for SignBlobAsync</summary>
public async Task SignBlobAsync()
{
// Snippet: SignBlobAsync(string, IEnumerable<string>, ByteString, CallSettings)
// Additional: SignBlobAsync(string, IEnumerable<string>, ByteString, CancellationToken)
// Create client
IAMCredentialsClient iAMCredentialsClient = await IAMCredentialsClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/serviceAccounts/[SERVICE_ACCOUNT]";
IEnumerable<string> delegates = new string[] { "", };
ByteString payload = ByteString.Empty;
// Make the request
SignBlobResponse response = await iAMCredentialsClient.SignBlobAsync(name, delegates, payload);
// End snippet
}
/// <summary>Snippet for SignBlob</summary>
public void SignBlobResourceNames()
{
// Snippet: SignBlob(ServiceAccountName, IEnumerable<string>, ByteString, CallSettings)
// Create client
IAMCredentialsClient iAMCredentialsClient = IAMCredentialsClient.Create();
// Initialize request argument(s)
ServiceAccountName name = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]");
IEnumerable<string> delegates = new string[] { "", };
ByteString payload = ByteString.Empty;
// Make the request
SignBlobResponse response = iAMCredentialsClient.SignBlob(name, delegates, payload);
// End snippet
}
/// <summary>Snippet for SignBlobAsync</summary>
public async Task SignBlobResourceNamesAsync()
{
// Snippet: SignBlobAsync(ServiceAccountName, IEnumerable<string>, ByteString, CallSettings)
// Additional: SignBlobAsync(ServiceAccountName, IEnumerable<string>, ByteString, CancellationToken)
// Create client
IAMCredentialsClient iAMCredentialsClient = await IAMCredentialsClient.CreateAsync();
// Initialize request argument(s)
ServiceAccountName name = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]");
IEnumerable<string> delegates = new string[] { "", };
ByteString payload = ByteString.Empty;
// Make the request
SignBlobResponse response = await iAMCredentialsClient.SignBlobAsync(name, delegates, payload);
// End snippet
}
/// <summary>Snippet for SignJwt</summary>
public void SignJwtRequestObject()
{
// Snippet: SignJwt(SignJwtRequest, CallSettings)
// Create client
IAMCredentialsClient iAMCredentialsClient = IAMCredentialsClient.Create();
// Initialize request argument(s)
SignJwtRequest request = new SignJwtRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates = { "", },
Payload = "",
};
// Make the request
SignJwtResponse response = iAMCredentialsClient.SignJwt(request);
// End snippet
}
/// <summary>Snippet for SignJwtAsync</summary>
public async Task SignJwtRequestObjectAsync()
{
// Snippet: SignJwtAsync(SignJwtRequest, CallSettings)
// Additional: SignJwtAsync(SignJwtRequest, CancellationToken)
// Create client
IAMCredentialsClient iAMCredentialsClient = await IAMCredentialsClient.CreateAsync();
// Initialize request argument(s)
SignJwtRequest request = new SignJwtRequest
{
ServiceAccountName = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]"),
Delegates = { "", },
Payload = "",
};
// Make the request
SignJwtResponse response = await iAMCredentialsClient.SignJwtAsync(request);
// End snippet
}
/// <summary>Snippet for SignJwt</summary>
public void SignJwt()
{
// Snippet: SignJwt(string, IEnumerable<string>, string, CallSettings)
// Create client
IAMCredentialsClient iAMCredentialsClient = IAMCredentialsClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/serviceAccounts/[SERVICE_ACCOUNT]";
IEnumerable<string> delegates = new string[] { "", };
string payload = "";
// Make the request
SignJwtResponse response = iAMCredentialsClient.SignJwt(name, delegates, payload);
// End snippet
}
/// <summary>Snippet for SignJwtAsync</summary>
public async Task SignJwtAsync()
{
// Snippet: SignJwtAsync(string, IEnumerable<string>, string, CallSettings)
// Additional: SignJwtAsync(string, IEnumerable<string>, string, CancellationToken)
// Create client
IAMCredentialsClient iAMCredentialsClient = await IAMCredentialsClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/serviceAccounts/[SERVICE_ACCOUNT]";
IEnumerable<string> delegates = new string[] { "", };
string payload = "";
// Make the request
SignJwtResponse response = await iAMCredentialsClient.SignJwtAsync(name, delegates, payload);
// End snippet
}
/// <summary>Snippet for SignJwt</summary>
public void SignJwtResourceNames()
{
// Snippet: SignJwt(ServiceAccountName, IEnumerable<string>, string, CallSettings)
// Create client
IAMCredentialsClient iAMCredentialsClient = IAMCredentialsClient.Create();
// Initialize request argument(s)
ServiceAccountName name = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]");
IEnumerable<string> delegates = new string[] { "", };
string payload = "";
// Make the request
SignJwtResponse response = iAMCredentialsClient.SignJwt(name, delegates, payload);
// End snippet
}
/// <summary>Snippet for SignJwtAsync</summary>
public async Task SignJwtResourceNamesAsync()
{
// Snippet: SignJwtAsync(ServiceAccountName, IEnumerable<string>, string, CallSettings)
// Additional: SignJwtAsync(ServiceAccountName, IEnumerable<string>, string, CancellationToken)
// Create client
IAMCredentialsClient iAMCredentialsClient = await IAMCredentialsClient.CreateAsync();
// Initialize request argument(s)
ServiceAccountName name = ServiceAccountName.FromProjectServiceAccount("[PROJECT]", "[SERVICE_ACCOUNT]");
IEnumerable<string> delegates = new string[] { "", };
string payload = "";
// Make the request
SignJwtResponse response = await iAMCredentialsClient.SignJwtAsync(name, delegates, payload);
// End snippet
}
}
}
| |
//
// Copyright 2012, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
#if !PLATFORM_WINPHONE && ! PORTABLE && ! NETFX_CORE && ! WINDOWS_PHONE
using System.Runtime.Serialization.Formatters.Binary;
#endif
namespace Xamarin.Auth
{
/// <summary>
/// An Account that represents an authenticated user of a social network.
/// </summary>
#if XAMARIN_AUTH_INTERNAL
internal class Account
#else
public class Account
#endif
{
/// <summary>
/// The username used as a key when storing this account.
/// </summary>
public virtual string Username { get; set; }
/// <summary>
/// A key-value store associated with this account. These get encrypted when the account is stored.
/// </summary>
public virtual Dictionary<string, string> Properties { get; private set; }
/// <summary>
/// Cookies that are stored with the account for web services that control access using cookies.
/// </summary>
public virtual CookieContainer Cookies { get; private set; }
/// <summary>
/// Initializes a new blank <see cref="Xamarin.Auth.Account"/>.
/// </summary>
public Account ()
: this ("", null, null)
{
}
/// <summary>
/// Initializes an <see cref="Xamarin.Auth.Account"/> with the given username.
/// </summary>
/// <param name='username'>
/// The username for the account.
/// </param>
public Account (string username)
: this (username, null, null)
{
}
/// <summary>
/// Initializes an <see cref="Xamarin.Auth.Account"/> with the given username and cookies.
/// </summary>
/// <param name='username'>
/// The username for the account.
/// </param>
/// <param name='cookies'>
/// The cookies to be stored with the account.
/// </param>
public Account (string username, CookieContainer cookies)
: this (username, null, cookies)
{
}
/// <summary>
/// Initializes an <see cref="Xamarin.Auth.Account"/> with the given username and cookies.
/// </summary>
/// <param name='username'>
/// The username for the account.
/// </param>
/// <param name='properties'>
/// Properties for the account.
/// </param>
public Account (string username, IDictionary<string, string> properties)
: this (username, properties, null)
{
}
/// <summary>
/// Initializes an <see cref="Xamarin.Auth.Account"/> with the given username and cookies.
/// </summary>
/// <param name='username'>
/// The username for the account.
/// </param>
/// <param name='properties'>
/// Properties for the account.
/// </param>
/// <param name='cookies'>
/// The cookies to be stored with the account.
/// </param>
public Account (string username, IDictionary<string, string> properties, CookieContainer cookies)
{
Username = username;
Properties = (properties == null) ?
new Dictionary<string, string> () :
new Dictionary<string, string> (properties);
Cookies = (cookies == null) ?
new CookieContainer () :
cookies;
}
/// <summary>
/// Serialize this account into a string that can be deserialized.
/// </summary>
/// <returns>A <c>string</c> representing the <see cref="Account"/> instance.</returns>
/// <seealso cref="Deserialize"/>
public string Serialize ()
{
var sb = new StringBuilder ();
sb.Append ("__username__=");
sb.Append (Uri.EscapeDataString (Username));
foreach (var p in Properties) {
sb.Append ("&");
sb.Append (Uri.EscapeDataString (p.Key));
sb.Append ("=");
sb.Append (Uri.EscapeDataString (p.Value));
}
if (Cookies.Count > 0) {
sb.Append ("&__cookies__=");
sb.Append (Uri.EscapeDataString (SerializeCookies ()));
}
return sb.ToString ();
}
/// <summary>
/// Restores an account from its serialized string representation.
/// </summary>
/// <param name='serializedString'>The serialized account generated by <see cref="Serialize"/>.</param>
/// <returns>An <see cref="Account"/> instance represented by <paramref name="serializedString"/>.</returns>
/// <seealso cref="Serialize"/>
public static Account Deserialize (string serializedString)
{
var acct = new Account ();
foreach (var p in serializedString.Split ('&')) {
var kv = p.Split ('=');
var key = Uri.UnescapeDataString (kv [0]);
var val = kv.Length > 1 ? Uri.UnescapeDataString (kv [1]) : "";
if (key == "__cookies__") {
acct.Cookies = DeserializeCookies (val);
} else if (key == "__username__") {
acct.Username = val;
} else {
acct.Properties [key] = val;
}
}
return acct;
}
string SerializeCookies ()
{
#if !PLATFORM_WINPHONE && !PORTABLE && !NETFX_CORE && ! WINDOWS_PHONE
var f = new BinaryFormatter ();
using (var s = new MemoryStream ()) {
f.Serialize (s, Cookies);
return Convert.ToBase64String (s.GetBuffer (), 0, (int)s.Length);
}
#else
return String.Empty;
#endif
}
static CookieContainer DeserializeCookies (string cookiesString)
{
#if !PLATFORM_WINPHONE && !PORTABLE && !NETFX_CORE && ! WINDOWS_PHONE
var f = new BinaryFormatter ();
using (var s = new MemoryStream (Convert.FromBase64String (cookiesString))) {
return (CookieContainer)f.Deserialize (s);
}
#else
return new CookieContainer();
#endif
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="Xamarin.Auth.Account"/>.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents the current <see cref="Xamarin.Auth.Account"/>.
/// </returns>
public override string ToString ()
{
return Serialize ();
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// WriteOnceBlock.cs
//
//
// A propagator block capable of receiving and storing only one message, ever.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Threading.Tasks.Dataflow.Internal;
namespace System.Threading.Tasks.Dataflow
{
/// <summary>Provides a buffer for receiving and storing at most one element in a network of dataflow blocks.</summary>
/// <typeparam name="T">Specifies the type of the data buffered by this dataflow block.</typeparam>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
[DebuggerTypeProxy(typeof(WriteOnceBlock<>.DebugView))]
public sealed class WriteOnceBlock<T> : IPropagatorBlock<T, T>, IReceivableSourceBlock<T>, IDebuggerDisplay
{
/// <summary>A registry used to store all linked targets and information about them.</summary>
private readonly TargetRegistry<T> _targetRegistry;
/// <summary>The cloning function.</summary>
private readonly Func<T, T> _cloningFunction;
/// <summary>The options used to configure this block's execution.</summary>
private readonly DataflowBlockOptions _dataflowBlockOptions;
/// <summary>Lazily initialized task completion source that produces the actual completion task when needed.</summary>
private TaskCompletionSource<VoidResult> _lazyCompletionTaskSource;
/// <summary>Whether all future messages should be declined.</summary>
private bool _decliningPermanently;
/// <summary>Whether block completion is disallowed.</summary>
private bool _completionReserved;
/// <summary>The header of the singly-assigned value.</summary>
private DataflowMessageHeader _header;
/// <summary>The singly-assigned value.</summary>
private T _value;
/// <summary>Gets the object used as the value lock.</summary>
private object ValueLock { get { return _targetRegistry; } }
/// <summary>Initializes the <see cref="WriteOnceBlock{T}"/>.</summary>
/// <param name="cloningFunction">
/// The function to use to clone the data when offered to other blocks.
/// This may be null to indicate that no cloning need be performed.
/// </param>
public WriteOnceBlock(Func<T, T> cloningFunction) :
this(cloningFunction, DataflowBlockOptions.Default)
{ }
/// <summary>Initializes the <see cref="WriteOnceBlock{T}"/> with the specified <see cref="DataflowBlockOptions"/>.</summary>
/// <param name="cloningFunction">
/// The function to use to clone the data when offered to other blocks.
/// This may be null to indicate that no cloning need be performed.
/// </param>
/// <param name="dataflowBlockOptions">The options with which to configure this <see cref="WriteOnceBlock{T}"/>.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception>
public WriteOnceBlock(Func<T, T> cloningFunction, DataflowBlockOptions dataflowBlockOptions)
{
// Validate arguments
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
// Store the option
_cloningFunction = cloningFunction;
_dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();
// The target registry also serves as our ValueLock,
// and thus must always be initialized, even if the block is pre-canceled, as
// subsequent usage of the block may run through code paths that try to take this lock.
_targetRegistry = new TargetRegistry<T>(this);
// If a cancelable CancellationToken has been passed in,
// we need to initialize the completion task's TCS now.
if (dataflowBlockOptions.CancellationToken.CanBeCanceled)
{
_lazyCompletionTaskSource = new TaskCompletionSource<VoidResult>();
// If we've already had cancellation requested, do as little work as we have to
// in order to be done.
if (dataflowBlockOptions.CancellationToken.IsCancellationRequested)
{
_completionReserved = _decliningPermanently = true;
// Cancel the completion task's TCS
_lazyCompletionTaskSource.SetCanceled();
}
else
{
// Handle async cancellation requests by declining on the target
Common.WireCancellationToComplete(
dataflowBlockOptions.CancellationToken, _lazyCompletionTaskSource.Task, state => ((WriteOnceBlock<T>)state).Complete(), this);
}
}
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.DataflowBlockCreated(this, dataflowBlockOptions);
}
#endif
}
/// <summary>Asynchronously completes the block on another task.</summary>
/// <remarks>
/// This must only be called once all of the completion conditions are met.
/// </remarks>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private void CompleteBlockAsync(IList<Exception> exceptions)
{
Debug.Assert(_decliningPermanently, "We may get here only after we have started to decline permanently.");
Debug.Assert(_completionReserved, "We may get here only after we have reserved completion.");
Common.ContractAssertMonitorStatus(ValueLock, held: false);
// If there is no exceptions list, we offer the message around, and then complete.
// If there is an exception list, we complete without offering the message.
if (exceptions == null)
{
// Offer the message to any linked targets and complete the block asynchronously to avoid blocking the caller
var taskForOutputProcessing = new Task(state => ((WriteOnceBlock<T>)state).OfferToTargetsAndCompleteBlock(), this,
Common.GetCreationOptionsForTask());
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TaskLaunchedForMessageHandling(
this, taskForOutputProcessing, DataflowEtwProvider.TaskLaunchedReason.OfferingOutputMessages, _header.IsValid ? 1 : 0);
}
#endif
// Start the task handling scheduling exceptions
Exception exception = Common.StartTaskSafe(taskForOutputProcessing, _dataflowBlockOptions.TaskScheduler);
if (exception != null) CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: true);
}
else
{
// Complete the block asynchronously to avoid blocking the caller
Task.Factory.StartNew(state =>
{
Tuple<WriteOnceBlock<T>, IList<Exception>> blockAndList = (Tuple<WriteOnceBlock<T>, IList<Exception>>)state;
blockAndList.Item1.CompleteBlock(blockAndList.Item2);
},
Tuple.Create(this, exceptions), CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default);
}
}
/// <summary>Offers the message and completes the block.</summary>
/// <remarks>
/// This is called only once.
/// </remarks>
private void OfferToTargetsAndCompleteBlock()
{
// OfferToTargets calls to potentially multiple targets, each of which
// could be faulty and throw an exception. OfferToTargets creates a
// list of all such exceptions and returns it.
// If _value is null, OfferToTargets does nothing.
List<Exception> exceptions = OfferToTargets();
CompleteBlock(exceptions);
}
/// <summary>Completes the block.</summary>
/// <remarks>
/// This is called only once.
/// </remarks>
private void CompleteBlock(IList<Exception> exceptions)
{
// Do not invoke the CompletionTaskSource property if there is a chance that _lazyCompletionTaskSource
// has not been initialized yet and we may have to complete normally, because that would defeat the
// sole purpose of the TCS being lazily initialized.
Debug.Assert(_lazyCompletionTaskSource == null || !_lazyCompletionTaskSource.Task.IsCompleted, "The task completion source must not be completed. This must be the only thread that ever completes the block.");
// Save the linked list of targets so that it could be traversed later to propagate completion
TargetRegistry<T>.LinkedTargetInfo linkedTargets = _targetRegistry.ClearEntryPoints();
// Complete the block's completion task
if (exceptions != null && exceptions.Count > 0)
{
CompletionTaskSource.TrySetException(exceptions);
}
else if (_dataflowBlockOptions.CancellationToken.IsCancellationRequested)
{
CompletionTaskSource.TrySetCanceled();
}
else
{
// Safely try to initialize the completion task's TCS with a cached completed TCS.
// If our attempt succeeds (CompareExchange returns null), we have nothing more to do.
// If the completion task's TCS was already initialized (CompareExchange returns non-null),
// we have to complete that TCS instance.
if (Interlocked.CompareExchange(ref _lazyCompletionTaskSource, Common.CompletedVoidResultTaskCompletionSource, null) != null)
{
_lazyCompletionTaskSource.TrySetResult(default(VoidResult));
}
}
// Now that the completion task is completed, we may propagate completion to the linked targets
_targetRegistry.PropagateCompletion(linkedTargets);
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.DataflowBlockCompleted(this);
}
#endif
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' />
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' />
public void Complete()
{
CompleteCore(exception: null, storeExceptionEvenIfAlreadyCompleting: false);
}
private void CompleteCore(Exception exception, bool storeExceptionEvenIfAlreadyCompleting)
{
Debug.Assert(exception != null || !storeExceptionEvenIfAlreadyCompleting,
"When storeExceptionEvenIfAlreadyCompleting is set to true, an exception must be provided.");
bool thisThreadReservedCompletion = false;
lock (ValueLock)
{
// Faulting from outside is allowed until we start declining permanently
if (_decliningPermanently && !storeExceptionEvenIfAlreadyCompleting) return;
// Decline further messages
_decliningPermanently = true;
// Reserve Completion.
// If storeExceptionEvenIfAlreadyCompleting is true, we are here to fault the block,
// because we couldn't launch the offer-and-complete task.
// We have to retry to just complete. We do that by pretending completion wasn't reserved.
if (!_completionReserved || storeExceptionEvenIfAlreadyCompleting) thisThreadReservedCompletion = _completionReserved = true;
}
// This call caused us to start declining further messages,
// there's nothing more this block needs to do... complete it if we just reserved completion.
if (thisThreadReservedCompletion)
{
List<Exception> exceptions = null;
if (exception != null)
{
exceptions = new List<Exception>();
exceptions.Add(exception);
}
CompleteBlockAsync(exceptions);
}
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' />
public bool TryReceive(Predicate<T> filter, out T item)
{
// No need to take the outgoing lock, as we don't need to synchronize with other
// targets, and _value only ever goes from null to non-null, not the other way around.
// If we have a value, give it up. All receives on a successfully
// completed WriteOnceBlock will return true, as long as the message
// passes the filter (all messages pass a null filter).
if (_header.IsValid && (filter == null || filter(_value)))
{
item = CloneItem(_value);
return true;
}
// Otherwise, nothing to receive
else
{
item = default(T);
return false;
}
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' />
bool IReceivableSourceBlock<T>.TryReceiveAll(out IList<T> items)
{
// Try to receive the one item this block may have.
// If we can, give back an array of one item. Otherwise,
// give back null.
T item;
if (TryReceive(null, out item))
{
items = new T[] { item };
return true;
}
else
{
items = null;
return false;
}
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' />
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public IDisposable LinkTo(ITargetBlock<T> target, DataflowLinkOptions linkOptions)
{
// Validate arguments
if (target == null) throw new ArgumentNullException(nameof(target));
if (linkOptions == null) throw new ArgumentNullException(nameof(linkOptions));
bool hasValue;
bool isCompleted;
lock (ValueLock)
{
hasValue = HasValue;
isCompleted = _completionReserved;
// If we haven't gotten a value yet and the block is not complete, add the target and bail
if (!hasValue && !isCompleted)
{
_targetRegistry.Add(ref target, linkOptions);
return Common.CreateUnlinker(ValueLock, _targetRegistry, target);
}
}
// If we already have a value, send it along to the linking target
if (hasValue)
{
bool useCloning = _cloningFunction != null;
target.OfferMessage(_header, _value, this, consumeToAccept: useCloning);
}
// If completion propagation has been requested, do it safely.
// The Completion property will ensure the lazy TCS is initialized.
if (linkOptions.PropagateCompletion) Common.PropagateCompletionOnceCompleted(Completion, target);
return Disposables.Nop;
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
public Task Completion { get { return CompletionTaskSource.Task; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' />
DataflowMessageStatus ITargetBlock<T>.OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, bool consumeToAccept)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
bool thisThreadReservedCompletion = false;
lock (ValueLock)
{
// If we are declining messages, bail
if (_decliningPermanently) return DataflowMessageStatus.DecliningPermanently;
// Consume the message from the source if necessary. We do this while holding ValueLock to prevent multiple concurrent
// offers from all succeeding.
if (consumeToAccept)
{
bool consumed;
messageValue = source.ConsumeMessage(messageHeader, this, out consumed);
if (!consumed) return DataflowMessageStatus.NotAvailable;
}
// Update the header and the value
_header = Common.SingleMessageHeader;
_value = messageValue;
// We got what we needed. Start declining permanently.
_decliningPermanently = true;
// Reserve Completion
if (!_completionReserved) thisThreadReservedCompletion = _completionReserved = true;
}
// Since this call to OfferMessage succeeded (and only one can ever), complete the block
// (but asynchronously so as not to block the Post call while offering to
// targets, running synchronous continuations off of the completion task, etc.)
if (thisThreadReservedCompletion) CompleteBlockAsync(exceptions: null);
return DataflowMessageStatus.Accepted;
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' />
T ISourceBlock<T>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target, out bool messageConsumed)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
// As long as the message being requested is the one we have, allow it to be consumed,
// but make a copy using the provided cloning function.
if (_header.Id == messageHeader.Id)
{
messageConsumed = true;
return CloneItem(_value);
}
else
{
messageConsumed = false;
return default(T);
}
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' />
bool ISourceBlock<T>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
// As long as the message is the one we have, it can be "reserved."
// Reservations on a WriteOnceBlock are not exclusive, because
// everyone who wants a copy can get one.
return _header.Id == messageHeader.Id;
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' />
void ISourceBlock<T>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<T> target)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
// As long as the message is the one we have, everything's fine.
if (_header.Id != messageHeader.Id) throw new InvalidOperationException(SR.InvalidOperation_MessageNotReservedByTarget);
// In other blocks, upon release we typically re-offer the message to all linked targets.
// We need to do the same thing for WriteOnceBlock, in order to account for cases where the block
// may be linked to a join or similar block, such that the join could never again be satisfied
// if it didn't receive another offer from this source. However, since the message is broadcast
// and all targets can get a copy, we don't need to broadcast to all targets, only to
// the target that released the message. Note that we don't care whether it's accepted
// or not, nor do we care about any exceptions which may emerge (they should just propagate).
Debug.Assert(_header.IsValid, "A valid header is required.");
bool useCloning = _cloningFunction != null;
target.OfferMessage(_header, _value, this, consumeToAccept: useCloning);
}
/// <summary>Clones the item.</summary>
/// <param name="item">The item to clone.</param>
/// <returns>The cloned item.</returns>
private T CloneItem(T item)
{
return _cloningFunction != null ?
_cloningFunction(item) :
item;
}
/// <summary>Offers the WriteOnceBlock's message to all targets.</summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private List<Exception> OfferToTargets()
{
Common.ContractAssertMonitorStatus(ValueLock, held: false);
// If there is a message, offer it to everyone. Return values
// don't matter, because we only get one message and then complete,
// and everyone who wants a copy can get a copy.
List<Exception> exceptions = null;
if (HasValue)
{
TargetRegistry<T>.LinkedTargetInfo cur = _targetRegistry.FirstTargetNode;
while (cur != null)
{
TargetRegistry<T>.LinkedTargetInfo next = cur.Next;
ITargetBlock<T> target = cur.Target;
try
{
// Offer the message. If there's a cloning function, we force the target to
// come back to us to consume the message, allowing us the opportunity to run
// the cloning function once we know they want the data. If there is no cloning
// function, there's no reason for them to call back here.
bool useCloning = _cloningFunction != null;
target.OfferMessage(_header, _value, this, consumeToAccept: useCloning);
}
catch (Exception exc)
{
// Track any erroneous exceptions that may occur
// and return them to the caller so that they may
// be logged in the completion task.
Common.StoreDataflowMessageValueIntoExceptionData(exc, _value);
Common.AddException(ref exceptions, exc);
}
cur = next;
}
}
return exceptions;
}
/// <summary>Ensures the completion task's TCS is initialized.</summary>
/// <returns>The completion task's TCS.</returns>
private TaskCompletionSource<VoidResult> CompletionTaskSource
{
get
{
// If the completion task's TCS has not been initialized by now, safely try to initialize it.
// It is very important that once a completion task/source instance has been handed out,
// it remains the block's completion task.
if (_lazyCompletionTaskSource == null)
{
Interlocked.CompareExchange(ref _lazyCompletionTaskSource, new TaskCompletionSource<VoidResult>(), null);
}
return _lazyCompletionTaskSource;
}
}
/// <summary>Gets whether the block is storing a value.</summary>
private bool HasValue { get { return _header.IsValid; } }
/// <summary>Gets the value being stored by the block.</summary>
private T Value { get { return _header.IsValid ? _value : default(T); } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' />
public override string ToString() { return Common.GetNameForDebugger(this, _dataflowBlockOptions); }
/// <summary>The data to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
return string.Format("{0}, HasValue={1}, Value={2}",
Common.GetNameForDebugger(this, _dataflowBlockOptions), HasValue, Value);
}
}
/// <summary>Gets the data to display in the debugger display attribute for this instance.</summary>
object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }
/// <summary>Provides a debugger type proxy for WriteOnceBlock.</summary>
private sealed class DebugView
{
/// <summary>The WriteOnceBlock being viewed.</summary>
private readonly WriteOnceBlock<T> _writeOnceBlock;
/// <summary>Initializes the debug view.</summary>
/// <param name="writeOnceBlock">The WriteOnceBlock to view.</param>
public DebugView(WriteOnceBlock<T> writeOnceBlock)
{
Debug.Assert(writeOnceBlock != null, "Need a block with which to construct the debug view.");
_writeOnceBlock = writeOnceBlock;
}
/// <summary>Gets whether the WriteOnceBlock has completed.</summary>
public bool IsCompleted { get { return _writeOnceBlock.Completion.IsCompleted; } }
/// <summary>Gets the block's Id.</summary>
public int Id { get { return Common.GetBlockId(_writeOnceBlock); } }
/// <summary>Gets whether the WriteOnceBlock has a value.</summary>
public bool HasValue { get { return _writeOnceBlock.HasValue; } }
/// <summary>Gets the WriteOnceBlock's value if it has one, or default(T) if it doesn't.</summary>
public T Value { get { return _writeOnceBlock.Value; } }
/// <summary>Gets the DataflowBlockOptions used to configure this block.</summary>
public DataflowBlockOptions DataflowBlockOptions { get { return _writeOnceBlock._dataflowBlockOptions; } }
/// <summary>Gets the set of all targets linked from this block.</summary>
public TargetRegistry<T> LinkedTargets { get { return _writeOnceBlock._targetRegistry; } }
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Scripting.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// Represents a runtime execution context for C# scripts.
/// </summary>
internal class ScriptBuilder
{
/// <summary>
/// Unique prefix for generated uncollectible assemblies.
/// </summary>
/// <remarks>
/// The full names of uncollectible assemblies generated by this context must be unique,
/// so that we can resolve references among them. Note that CLR can load two different assemblies of the very
/// identity into the same load context.
///
/// We are using a certain naming scheme for the generated assemblies (a fixed name prefix followed by a number).
/// If we allowed the compiled code to add references that match this exact pattern it might happen that
/// the user supplied reference identity conflicts with the identity we use for our generated assemblies and
/// the AppDomain assembly resolve event won't be able to correctly identify the target assembly.
///
/// To avoid this problem we use a prefix for assemblies we generate that is unlikely to conflict with user specified references.
/// We also check that no user provided references are allowed to be used in the compiled code and report an error ("reserved assembly name").
/// </remarks>
private static readonly string s_globalAssemblyNamePrefix;
private static int s_engineIdDispenser;
private int _submissionIdDispenser = -1;
private readonly string _assemblyNamePrefix;
// dynamic code storage
//
// TODO (tomat): Dynamic assembly allocation strategy. A dynamic assembly is a unit of
// collection. We need to find a balance between creating a new assembly per execution
// (potentially shorter code lifetime) and reusing a single assembly for all executions
// (less overhead per execution).
private readonly UncollectibleCodeManager _uncollectibleCodeManager;
private readonly CollectibleCodeManager _collectibleCodeManager;
/// <summary>
/// Lockable object only instance is knowledgeable about.
/// </summary>
private readonly object _gate = new object();
#region Testing and Debugging
private const string CollectibleModuleFileName = "CollectibleModule.dll";
private const string UncollectibleModuleFileName = "UncollectibleModule.dll";
// Setting this flag will add DebuggableAttribute on the emitted code that disables JIT optimizations.
// With optimizations disabled JIT will verify the method before it compiles it so we can easily
// discover incorrect code.
internal static bool DisableJitOptimizations;
#if DEBUG
// Flags to make debugging of emitted code easier.
// Enables saving the dynamic assemblies to disk. Must be called before any code is compiled.
internal static bool EnableAssemblySave;
// Helps debugging issues in emitted code. If set the next call to Execute/Compile will save the dynamic assemblies to disk.
internal static bool SaveCompiledAssemblies;
#endif
#endregion
static ScriptBuilder()
{
s_globalAssemblyNamePrefix = "\u211B*" + Guid.NewGuid().ToString() + "-";
}
public ScriptBuilder(AssemblyLoader assemblyLoader = null)
{
if (assemblyLoader == null)
{
assemblyLoader = new InteractiveAssemblyLoader();
}
_assemblyNamePrefix = s_globalAssemblyNamePrefix + "#" + Interlocked.Increment(ref s_engineIdDispenser).ToString();
_collectibleCodeManager = new CollectibleCodeManager(assemblyLoader, _assemblyNamePrefix);
_uncollectibleCodeManager = new UncollectibleCodeManager(assemblyLoader, _assemblyNamePrefix);
}
public AssemblyLoader AssemblyLoader
{
get { return _collectibleCodeManager.assemblyLoader; }
}
internal string AssemblyNamePrefix
{
get { return _assemblyNamePrefix; }
}
internal static bool IsReservedAssemblyName(AssemblyIdentity identity)
{
return identity.Name.StartsWith(s_globalAssemblyNamePrefix, StringComparison.Ordinal);
}
public int GenerateSubmissionId(out string assemblyName, out string typeName)
{
int id = Interlocked.Increment(ref _submissionIdDispenser);
string idAsString = id.ToString();
assemblyName = _assemblyNamePrefix + idAsString;
typeName = "Submission#" + idAsString;
return id;
}
/// <summary>
/// Builds a delegate that will execute just this scripts code.
/// </summary>
public Func<object[], object> Build(
Script script,
DiagnosticBag diagnostics,
CancellationToken cancellationToken)
{
var compilation = script.GetCompilation();
var options = script.Options;
DiagnosticBag emitDiagnostics = DiagnosticBag.GetInstance();
byte[] compiledAssemblyImage;
MethodInfo entryPoint;
bool success = compilation.Emit(
GetOrCreateDynamicModule(options.IsCollectible),
assemblyLoader: GetAssemblyLoader(options.IsCollectible),
assemblySymbolMapper: symbol => MapAssemblySymbol(symbol, options.IsCollectible),
recoverOnError: true,
diagnostics: emitDiagnostics,
cancellationToken: cancellationToken,
entryPoint: out entryPoint,
compiledAssemblyImage: out compiledAssemblyImage
);
if (diagnostics != null)
{
diagnostics.AddRange(emitDiagnostics);
}
bool hadEmitErrors = emitDiagnostics.HasAnyErrors();
emitDiagnostics.Free();
// emit can fail due to compilation errors or because there is nothing to emit:
if (!success)
{
return null;
}
Debug.Assert(entryPoint != null);
if (compiledAssemblyImage != null)
{
// Ref.Emit wasn't able to emit the assembly
_uncollectibleCodeManager.AddFallBackAssembly(entryPoint.DeclaringType.Assembly);
}
#if DEBUG
if (SaveCompiledAssemblies)
{
_uncollectibleCodeManager.Save(UncollectibleModuleFileName);
_collectibleCodeManager.Save(CollectibleModuleFileName);
}
#endif
return (Func<object[], object>)Delegate.CreateDelegate(typeof(Func<object[], object>), entryPoint);
}
internal ModuleBuilder GetOrCreateDynamicModule(bool collectible)
{
if (collectible)
{
return _collectibleCodeManager.GetOrCreateDynamicModule();
}
else
{
return _uncollectibleCodeManager.GetOrCreateDynamicModule();
}
}
private static ModuleBuilder CreateDynamicModule(AssemblyBuilderAccess access, AssemblyIdentity name, string fileName)
{
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name.ToAssemblyName(), access);
if (DisableJitOptimizations)
{
assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(
typeof(DebuggableAttribute).GetConstructor(new[] { typeof(DebuggableAttribute.DebuggingModes) }),
new object[] { DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations }));
}
const string moduleName = "InteractiveModule";
if (access == AssemblyBuilderAccess.RunAndSave)
{
return assemblyBuilder.DefineDynamicModule(moduleName, fileName, emitSymbolInfo: false);
}
else
{
return assemblyBuilder.DefineDynamicModule(moduleName, emitSymbolInfo: false);
}
}
/// <summary>
/// Maps given assembly symbol to an assembly ref.
/// </summary>
/// <remarks>
/// The compiler represents every submission by a compilation instance for which it creates a distinct source assembly symbol.
/// However multiple submissions might compile into a single dynamic assembly and so we need to map the corresponding assembly symbols to
/// the name of the dynamic assembly.
/// </remarks>
internal AssemblyIdentity MapAssemblySymbol(IAssemblySymbol symbol, bool collectible)
{
if (symbol.IsInteractive)
{
if (collectible)
{
// collectible assemblies can't reference other generated assemblies
throw ExceptionUtilities.Unreachable;
}
else if (!_uncollectibleCodeManager.ContainsAssembly(symbol.Identity.Name))
{
// uncollectible assemblies can reference uncollectible dynamic or uncollectible CCI generated assemblies:
return _uncollectibleCodeManager.dynamicAssemblyName;
}
}
return symbol.Identity;
}
internal AssemblyLoader GetAssemblyLoader(bool collectible)
{
return collectible ? (AssemblyLoader)_collectibleCodeManager : _uncollectibleCodeManager;
}
// TODO (tomat): the code managers can be improved - common base class, less locking, etc.
private sealed class CollectibleCodeManager : AssemblyLoader
{
internal readonly AssemblyLoader assemblyLoader;
private readonly AssemblyIdentity _dynamicAssemblyName;
/// <summary>
/// lock(_gate) on access.
/// </summary>
private readonly object _gate = new object();
/// <summary>
/// lock(_gate) on access.
/// </summary>
internal ModuleBuilder dynamicModule;
public CollectibleCodeManager(AssemblyLoader assemblyLoader, string assemblyNamePrefix)
{
this.assemblyLoader = assemblyLoader;
_dynamicAssemblyName = new AssemblyIdentity(name: assemblyNamePrefix + "CD");
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(Resolve);
}
internal ModuleBuilder GetOrCreateDynamicModule()
{
if (dynamicModule == null)
{
lock (_gate)
{
if (dynamicModule == null)
{
dynamicModule = CreateDynamicModule(
#if DEBUG
EnableAssemblySave ? AssemblyBuilderAccess.RunAndSave :
#endif
AssemblyBuilderAccess.RunAndCollect, _dynamicAssemblyName, CollectibleModuleFileName);
}
}
}
return dynamicModule;
}
internal void Save(string fileName)
{
if (dynamicModule != null)
{
((AssemblyBuilder)dynamicModule.Assembly).Save(fileName);
}
}
private Assembly Resolve(object sender, ResolveEventArgs args)
{
if (args.Name != _dynamicAssemblyName.GetDisplayName())
{
return null;
}
lock (_gate)
{
return (dynamicModule != null) ? dynamicModule.Assembly : null;
}
}
public override Assembly Load(AssemblyIdentity identity, string location = null)
{
if (dynamicModule != null && identity.Name == _dynamicAssemblyName.Name)
{
return dynamicModule.Assembly;
}
return assemblyLoader.Load(identity, location);
}
}
/// <summary>
/// Manages uncollectible assemblies and resolves assembly references baked into CCI generated metadata.
/// The resolution is triggered by the CLR Type Loader.
/// </summary>
private sealed class UncollectibleCodeManager : AssemblyLoader
{
private readonly AssemblyLoader _assemblyLoader;
private readonly string _assemblyNamePrefix;
internal readonly AssemblyIdentity dynamicAssemblyName;
// lock(_gate) on access
private ModuleBuilder _dynamicModule; // primary uncollectible assembly
private HashSet<Assembly> _fallBackAssemblies; // additional uncollectible assemblies created due to a Ref.Emit falling back to CCI
private Dictionary<string, Assembly> _mapping; // { simple name -> fall-back assembly }
/// <summary>
/// Lockable object only instance is knowledgeable about.
/// </summary>
private readonly object _gate = new object();
internal UncollectibleCodeManager(AssemblyLoader assemblyLoader, string assemblyNamePrefix)
{
_assemblyLoader = assemblyLoader;
_assemblyNamePrefix = assemblyNamePrefix;
this.dynamicAssemblyName = new AssemblyIdentity(name: assemblyNamePrefix + "UD");
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(Resolve);
}
internal ModuleBuilder GetOrCreateDynamicModule()
{
if (_dynamicModule == null)
{
lock (_gate)
{
if (_dynamicModule == null)
{
_dynamicModule = CreateDynamicModule(
#if DEBUG
EnableAssemblySave ? AssemblyBuilderAccess.RunAndSave :
#endif
AssemblyBuilderAccess.Run, dynamicAssemblyName, UncollectibleModuleFileName);
}
}
}
return _dynamicModule;
}
internal void Save(string fileName)
{
if (_dynamicModule != null)
{
((AssemblyBuilder)_dynamicModule.Assembly).Save(fileName);
}
}
internal void AddFallBackAssembly(Assembly assembly)
{
lock (_gate)
{
if (_fallBackAssemblies == null)
{
Debug.Assert(_mapping == null);
_fallBackAssemblies = new HashSet<Assembly>();
_mapping = new Dictionary<string, Assembly>();
}
_fallBackAssemblies.Add(assembly);
_mapping[assembly.GetName().Name] = assembly;
}
}
internal bool ContainsAssembly(string simpleName)
{
if (_mapping == null)
{
return false;
}
lock (_gate)
{
return _mapping.ContainsKey(simpleName);
}
}
private Assembly Resolve(object sender, ResolveEventArgs args)
{
if (!args.Name.StartsWith(_assemblyNamePrefix, StringComparison.Ordinal))
{
return null;
}
lock (_gate)
{
if (args.Name == dynamicAssemblyName.GetDisplayName())
{
return _dynamicModule != null ? _dynamicModule.Assembly : null;
}
if (_dynamicModule != null && _dynamicModule.Assembly == args.RequestingAssembly ||
_fallBackAssemblies != null && _fallBackAssemblies.Contains(args.RequestingAssembly))
{
int comma = args.Name.IndexOf(',');
return ResolveNoLock(args.Name.Substring(0, (comma != -1) ? comma : args.Name.Length));
}
}
return null;
}
private Assembly Resolve(string simpleName)
{
lock (_gate)
{
return ResolveNoLock(simpleName);
}
}
private Assembly ResolveNoLock(string simpleName)
{
if (_dynamicModule != null && simpleName == dynamicAssemblyName.Name)
{
return _dynamicModule.Assembly;
}
Assembly assembly;
if (_mapping != null && _mapping.TryGetValue(simpleName, out assembly))
{
return assembly;
}
return null;
}
public override Assembly Load(AssemblyIdentity identity, string location = null)
{
return Resolve(identity.Name) ?? _assemblyLoader.Load(identity, location);
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Windows.Forms;
namespace VRS.UI.Controls {
/// <summary>
/// EditBox control.
/// </summary>
public class WEditBox : WControlBase {
private WTextBoxBase m_pTextBox;
private System.Windows.Forms.Timer timer1;
private System.ComponentModel.IContainer components = null;
public event EventHandler EnterKeyPressed = null;
public new event WValidate_EventHandler Validate = null;
//private bool m_Modified = false;
private bool m_ReadOnly = false;
private int m_FlasCounter = 0;
/// <summary>
/// Default constructor.
/// </summary>
public WEditBox() {
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// TODO: Add any initialization after the InitForm call
m_pTextBox.LostFocus += new System.EventHandler(this.m_pTextBox_OnLostFocus);
m_pTextBox.GotFocus += new System.EventHandler(this.m_pTextBox_OnGotFocus);
this.BackColor = Color.White;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing ) {
if( disposing ) {
if(components != null){
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.components = new System.ComponentModel.Container();
this.m_pTextBox = new VRS.UI.Controls.WTextBoxBase();
this.timer1 = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.m_pTextBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
this.SuspendLayout();
//
// m_pTextBox
//
this.m_pTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.m_pTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.m_pTextBox.DecimalPlaces = 2;
this.m_pTextBox.DecMaxValue = 999999999;
this.m_pTextBox.DecMinValue = -999999999;
this.m_pTextBox.Location = new System.Drawing.Point(3, 2);
this.m_pTextBox.Mask = VRS.UI.Controls.WEditBox_Mask.Text;
this.m_pTextBox.Name = "m_pTextBox";
this.m_pTextBox.Size = new System.Drawing.Size(94, 13);
this.m_pTextBox.TabIndex = 0;
this.m_pTextBox.Text = "";
this.m_pTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.m_pTextBox_KeyDown);
this.m_pTextBox.TextChanged += new System.EventHandler(this.m_pTextBox_TextChanged);
//
// timer1
//
this.timer1.Interval = 150;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// WEditBox
//
this.Controls.Add(this.m_pTextBox);
this.Name = "WEditBox";
this.Size = new System.Drawing.Size(100, 20);
this.ViewStyle.EditReadOnlyColor = System.Drawing.Color.White;
((System.ComponentModel.ISupportInitialize)(this.m_pTextBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
this.ResumeLayout(false);
}
#endregion
#region Events handling
#region function m_pTextBox_OnGotFocus
private void m_pTextBox_OnGotFocus(object sender, System.EventArgs e) {
this.BackColor = m_ViewStyle.EditFocusedColor;
}
#endregion
#region function m_pTextBox_OnLostFocus
private void m_pTextBox_OnLostFocus(object sender, System.EventArgs e) {
this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled);
OnValidate();
DrawControl(this.ContainsFocus);
}
#endregion
#region function m_pTextBox_TextChanged
private void m_pTextBox_TextChanged(object sender, System.EventArgs e) {
base.OnTextChanged(new System.EventArgs());
}
#endregion
#region function timer1_Tick
private void timer1_Tick(object sender, System.EventArgs e) {
if(m_pTextBox.BackColor == this.BackColor){
m_pTextBox.BackColor = m_ViewStyle.FlashColor;
}
else{
m_pTextBox.BackColor = this.BackColor;
}
m_FlasCounter++;
if(m_FlasCounter > 8){
m_pTextBox.BackColor = this.BackColor;
timer1.Enabled = false;
}
}
#endregion
#region function OnViewStyleChanged
protected override void OnViewStyleChanged(ViewStyle_EventArgs e) {
switch(e.PropertyName) {
case "EditColor":
this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled);
break;
case "EditReadOnlyColor":
this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled);
break;
case "EditDisabledColor":
this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled);
break;
}
this.Invalidate(false);
}
#endregion
#endregion
#region function ProcessDialogKey
protected override bool ProcessDialogKey(System.Windows.Forms.Keys keyData) {
System.Windows.Forms.Keys key = keyData;
if(key == System.Windows.Forms.Keys.Enter){
this.OnEnterKeyPressed();
return true;
}
return base.ProcessDialogKey(keyData);
}
#endregion
#region override OnEndedInitialize
public override void OnEndedInitialize() {
this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled);
if(this.Text.Length == 0){
this.Text = "";
}
}
#endregion
#region override OnEnabledChanged
protected override void OnEnabledChanged(EventArgs e) {
base.OnEnabledChanged(e);
// m_pTextBox.Enabled = this.Enabled;
this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled);
}
#endregion
#region Public functions
#region function FlashControl
public void FlashControl() {
if(!timer1.Enabled){
m_FlasCounter = 0;
timer1.Enabled = true;
}
}
#endregion
#endregion
#region Properties Implementation
#region Color stuff
/// <summary>
///
/// </summary>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new Color BackColor {
get{ return base.BackColor; }
set{
base.BackColor = value;
m_pTextBox.BackColor = value;
}
}
/// <summary>
///
/// </summary>
public override Color ForeColor {
get{ return base.ForeColor; }
set{
base.ForeColor = value;
m_pTextBox.ForeColor = value;
}
}
#endregion
/// <summary>
///
/// </summary>
public WEditBox_Mask Mask {
get{ return m_pTextBox.Mask; }
set{ m_pTextBox.Mask = value; }
}
/// <summary>
///
/// </summary>
public int DecimalPlaces {
get{ return m_pTextBox.DecimalPlaces; }
set{ m_pTextBox.DecimalPlaces = value; }
}
/// <summary>
///
/// </summary>
public int MaxLength {
get{ return m_pTextBox.MaxLength; }
set{ m_pTextBox.MaxLength = value; }
}
public int DecMinValue {
get{ return m_pTextBox.DecMinValue; }
set{ m_pTextBox.DecMinValue = value; }
}
public int DecMaxValue {
get{ return m_pTextBox.DecMaxValue; }
set{ m_pTextBox.DecMaxValue = value; }
}
/// <summary>
///
/// </summary>
public char PasswordChar {
get{ return m_pTextBox.PasswordChar; }
set { m_pTextBox.PasswordChar = value; }
}
/// <summary>
///
/// </summary>
public HorizontalAlignment TextAlign {
get{ return m_pTextBox.TextAlign; }
set{ m_pTextBox.TextAlign = value; }
}
/// <summary>
///
/// </summary>
public bool Multiline {
get{ return m_pTextBox.Multiline; }
set{
m_pTextBox.Multiline = value;
m_pTextBox.AcceptsReturn = true;
}
}
/// <summary>
///
/// </summary>
public new int Height {
get{ return base.Height; }
set{
if(value > m_pTextBox.Height + 1){
base.Height = value;
if(!this.Multiline){
int yPos = (value - m_pTextBox.Height) / 2;
m_pTextBox.Top = yPos;
}
else{
m_pTextBox.Top = 2;
m_pTextBox.Height = this.Height - 4;
}
}
}
}
/// <summary>
///
/// </summary>
public new Size Size {
get{ return base.Size; }
set{
if(value.Height > m_pTextBox.Height + 1){
base.Size = value;
if(!this.Multiline){
int yPos = (value.Height - m_pTextBox.Height) / 2;
m_pTextBox.Top = yPos;
}
else{
m_pTextBox.Top = 2;
m_pTextBox.Height = this.Height - 4;
}
}
}
}
/// <summary>
///
/// </summary>
public bool ReadOnly {
get{ return m_ReadOnly; }
set{
m_ReadOnly = value;
m_pTextBox.ReadOnly = value;
if(value){
this.BackColor = m_ViewStyle.EditReadOnlyColor;
}
else{
if(this.ContainsFocus){
this.BackColor = m_ViewStyle.EditFocusedColor;
}
else{
this.BackColor = m_ViewStyle.EditColor;
}
}
}
}
/// <summary>
///
/// </summary>
[
Browsable(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)
]
public override string Text {
get{ return m_pTextBox.Text; }
set{ m_pTextBox.Text = value; }
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public decimal DecValue {
get{ return m_pTextBox.DecValue; }
set{ m_pTextBox.DecValue = value; }
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public bool IsModified {
get{ return m_pTextBox.Modified; }
set{ m_pTextBox.Modified = value; }
}
#endregion
#region Events Implementation
#region function OnEnterKeyPressed
protected virtual void OnEnterKeyPressed() {
System.EventArgs oArg = new System.EventArgs();
if(this.EnterKeyPressed != null){
this.EnterKeyPressed(this, oArg);
}
}
#endregion
#region function OnValidate
protected virtual void OnValidate() {
// Raises the Validate change event;
WValidate_EventArgs oArg = new WValidate_EventArgs(this.Name,this.Text);
if(this.Validate != null){
this.Validate(this, oArg);
}
//---- If validation failed ----//
if(!oArg.IsValid){
if(oArg.FlashControl){
this.FlashControl();
}
if(!oArg.AllowMoveFocus){
this.Focus();
}
}
//------------------------------//
}
#endregion
private void m_pTextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) {
base.OnKeyDown(e);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="RecordBuilder.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Xsl.XsltOld {
using Res = System.Xml.Utils.Res;
using System;
using System.Diagnostics;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Collections;
internal sealed class RecordBuilder {
private int outputState;
private RecordBuilder next;
RecordOutput output;
// Atomization:
private XmlNameTable nameTable;
private OutKeywords atoms;
// Namespace manager for output
private OutputScopeManager scopeManager;
// Main node + Fields Collection
private BuilderInfo mainNode = new BuilderInfo();
private ArrayList attributeList = new ArrayList();
private int attributeCount;
private ArrayList namespaceList = new ArrayList();
private int namespaceCount;
private BuilderInfo dummy = new BuilderInfo();
// Current position in the list
private BuilderInfo currentInfo;
// Builder state
private bool popScope;
private int recordState;
private int recordDepth;
private const int NoRecord = 0; // No part of a new record was generated (old record was cleared out)
private const int SomeRecord = 1; // Record was generated partially (can be eventually record)
private const int HaveRecord = 2; // Record was fully generated
private const char s_Minus = '-';
private const string s_Space = " ";
private const string s_SpaceMinus = " -";
private const char s_Question = '?';
private const char s_Greater = '>';
private const string s_SpaceGreater = " >";
private const string PrefixFormat = "xp_{0}";
internal RecordBuilder(RecordOutput output, XmlNameTable nameTable) {
Debug.Assert(output != null);
this.output = output;
this.nameTable = nameTable != null ? nameTable : new NameTable();
this.atoms = new OutKeywords(this.nameTable);
this.scopeManager = new OutputScopeManager(this.nameTable, this.atoms);
}
//
// Internal properties
//
internal int OutputState {
get { return this.outputState; }
set { this.outputState = value; }
}
internal RecordBuilder Next {
get { return this.next; }
set { this.next = value; }
}
internal RecordOutput Output {
get { return this.output; }
}
internal BuilderInfo MainNode {
get { return this.mainNode; }
}
internal ArrayList AttributeList {
get { return this.attributeList; }
}
internal int AttributeCount {
get { return this.attributeCount; }
}
internal OutputScopeManager Manager {
get { return this.scopeManager; }
}
private void ValueAppend(string s, bool disableOutputEscaping) {
this.currentInfo.ValueAppend(s, disableOutputEscaping);
}
private bool CanOutput(int state) {
Debug.Assert(this.recordState != HaveRecord);
// If we have no record cached or the next event doesn't start new record, we are OK
if (this.recordState == NoRecord || (state & StateMachine.BeginRecord) == 0) {
return true;
}
else {
this.recordState = HaveRecord;
FinalizeRecord();
SetEmptyFlag(state);
return this.output.RecordDone(this) == Processor.OutputResult.Continue;
}
}
internal Processor.OutputResult BeginEvent(int state, XPathNodeType nodeType, string prefix, string name, string nspace, bool empty, Object htmlProps, bool search) {
if (! CanOutput(state)) {
return Processor.OutputResult.Overflow;
}
Debug.Assert(this.recordState == NoRecord || (state & StateMachine.BeginRecord) == 0);
AdjustDepth(state);
ResetRecord(state);
PopElementScope();
prefix = (prefix != null) ? this.nameTable.Add(prefix) : this.atoms.Empty;
name = (name != null) ? this.nameTable.Add(name) : this.atoms.Empty;
nspace = (nspace != null) ? this.nameTable.Add(nspace) : this.atoms.Empty;
switch (nodeType) {
case XPathNodeType.Element:
this.mainNode.htmlProps = htmlProps as HtmlElementProps;
this.mainNode.search = search;
BeginElement(prefix, name, nspace, empty);
break;
case XPathNodeType.Attribute:
BeginAttribute(prefix, name, nspace, htmlProps, search);
break;
case XPathNodeType.Namespace:
BeginNamespace(name, nspace);
break;
case XPathNodeType.Text:
break;
case XPathNodeType.ProcessingInstruction:
if (BeginProcessingInstruction(prefix, name, nspace) == false) {
return Processor.OutputResult.Error;
}
break;
case XPathNodeType.Comment:
BeginComment();
break;
case XPathNodeType.Root:
break;
case XPathNodeType.Whitespace:
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.All:
break;
}
return CheckRecordBegin(state);
}
internal Processor.OutputResult TextEvent(int state, string text, bool disableOutputEscaping) {
if (! CanOutput(state)) {
return Processor.OutputResult.Overflow;
}
Debug.Assert(this.recordState == NoRecord || (state & StateMachine.BeginRecord) == 0);
AdjustDepth(state);
ResetRecord(state);
PopElementScope();
if ((state & StateMachine.BeginRecord) != 0) {
this.currentInfo.Depth = this.recordDepth;
this.currentInfo.NodeType = XmlNodeType.Text;
}
ValueAppend(text, disableOutputEscaping);
return CheckRecordBegin(state);
}
internal Processor.OutputResult EndEvent(int state, XPathNodeType nodeType) {
if (! CanOutput(state)) {
return Processor.OutputResult.Overflow;
}
AdjustDepth(state);
PopElementScope();
this.popScope = (state & StateMachine.PopScope) != 0;
if ((state & StateMachine.EmptyTag) != 0 && this.mainNode.IsEmptyTag == true) {
return Processor.OutputResult.Continue;
}
ResetRecord(state);
if ((state & StateMachine.BeginRecord) != 0) {
if(nodeType == XPathNodeType.Element) {
EndElement();
}
}
return CheckRecordEnd(state);
}
internal void Reset() {
if (this.recordState == HaveRecord) {
this.recordState = NoRecord;
}
}
internal void TheEnd() {
if (this.recordState == SomeRecord) {
this.recordState = HaveRecord;
FinalizeRecord();
this.output.RecordDone(this);
}
this.output.TheEnd();
}
//
// Utility implementation methods
//
private int FindAttribute(string name, string nspace, ref string prefix) {
Debug.Assert(this.attributeCount <= this.attributeList.Count);
for (int attrib = 0; attrib < this.attributeCount; attrib ++) {
Debug.Assert(this.attributeList[attrib] != null && this.attributeList[attrib] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo) this.attributeList[attrib];
if (Ref.Equal(attribute.LocalName, name)) {
if (Ref.Equal(attribute.NamespaceURI, nspace)) {
return attrib;
}
if (Ref.Equal(attribute.Prefix, prefix)) {
// prefix conflict. Should be renamed.
prefix = string.Empty;
}
}
}
return -1;
}
private void BeginElement(string prefix, string name, string nspace, bool empty) {
Debug.Assert(this.attributeCount == 0);
this.currentInfo.NodeType = XmlNodeType.Element;
this.currentInfo.Prefix = prefix;
this.currentInfo.LocalName = name;
this.currentInfo.NamespaceURI = nspace;
this.currentInfo.Depth = this.recordDepth;
this.currentInfo.IsEmptyTag = empty;
this.scopeManager.PushScope(name, nspace, prefix);
}
private void EndElement() {
Debug.Assert(this.attributeCount == 0);
OutputScope elementScope = this.scopeManager.CurrentElementScope;
this.currentInfo.NodeType = XmlNodeType.EndElement;
this.currentInfo.Prefix = elementScope.Prefix;
this.currentInfo.LocalName = elementScope.Name;
this.currentInfo.NamespaceURI = elementScope.Namespace;
this.currentInfo.Depth = this.recordDepth;
}
private int NewAttribute() {
if (this.attributeCount >= this.attributeList.Count) {
Debug.Assert(this.attributeCount == this.attributeList.Count);
this.attributeList.Add(new BuilderInfo());
}
return this.attributeCount ++;
}
private void BeginAttribute(string prefix, string name, string nspace, Object htmlAttrProps, bool search) {
int attrib = FindAttribute(name, nspace, ref prefix);
if (attrib == -1) {
attrib = NewAttribute();
}
Debug.Assert(this.attributeList[attrib] != null && this.attributeList[attrib] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo) this.attributeList[attrib];
attribute.Initialize(prefix, name, nspace);
attribute.Depth = this.recordDepth;
attribute.NodeType = XmlNodeType.Attribute;
attribute.htmlAttrProps = htmlAttrProps as HtmlAttributeProps;
attribute.search = search;
this.currentInfo = attribute;
}
private void BeginNamespace(string name, string nspace) {
bool thisScope = false;
if (Ref.Equal(name, this.atoms.Empty)) {
if (Ref.Equal(nspace, this.scopeManager.DefaultNamespace)) {
// Main Node is OK
}
else if (Ref.Equal(this.mainNode.NamespaceURI, this.atoms.Empty)) {
// http://www.w3.org/1999/11/REC-xslt-19991116-errata/ E25
// Should throw an error but ingnoring it in Everett.
// Would be a breaking change
}
else {
DeclareNamespace(nspace, name);
}
}
else {
string nspaceDeclared = this.scopeManager.ResolveNamespace(name, out thisScope);
if (nspaceDeclared != null) {
if (! Ref.Equal(nspace, nspaceDeclared)) {
if(!thisScope) {
DeclareNamespace(nspace, name);
}
}
}
else {
DeclareNamespace(nspace, name);
}
}
this.currentInfo = dummy;
currentInfo.NodeType = XmlNodeType.Attribute;
}
private bool BeginProcessingInstruction(string prefix, string name, string nspace) {
this.currentInfo.NodeType = XmlNodeType.ProcessingInstruction;
this.currentInfo.Prefix = prefix;
this.currentInfo.LocalName = name;
this.currentInfo.NamespaceURI = nspace;
this.currentInfo.Depth = this.recordDepth;
return true;
}
private void BeginComment() {
this.currentInfo.NodeType = XmlNodeType.Comment;
this.currentInfo.Depth = this.recordDepth;
}
private void AdjustDepth(int state) {
switch (state & StateMachine.DepthMask) {
case StateMachine.DepthUp:
this.recordDepth ++;
break;
case StateMachine.DepthDown:
this.recordDepth --;
break;
default:
break;
}
}
private void ResetRecord(int state) {
Debug.Assert(this.recordState == NoRecord || this.recordState == SomeRecord);
if ((state & StateMachine.BeginRecord) != 0) {
this.attributeCount = 0;
this.namespaceCount = 0;
this.currentInfo = this.mainNode;
this.currentInfo.Initialize(this.atoms.Empty, this.atoms.Empty, this.atoms.Empty);
this.currentInfo.NodeType = XmlNodeType.None;
this.currentInfo.IsEmptyTag = false;
this.currentInfo.htmlProps = null;
this.currentInfo.htmlAttrProps = null;
}
}
private void PopElementScope() {
if (this.popScope) {
this.scopeManager.PopScope();
this.popScope = false;
}
}
private Processor.OutputResult CheckRecordBegin(int state) {
Debug.Assert(this.recordState == NoRecord || this.recordState == SomeRecord);
if ((state & StateMachine.EndRecord) != 0) {
this.recordState = HaveRecord;
FinalizeRecord();
SetEmptyFlag(state);
return this.output.RecordDone(this);
}
else {
this.recordState = SomeRecord;
return Processor.OutputResult.Continue;
}
}
private Processor.OutputResult CheckRecordEnd(int state) {
Debug.Assert(this.recordState == NoRecord || this.recordState == SomeRecord);
if ((state & StateMachine.EndRecord) != 0) {
this.recordState = HaveRecord;
FinalizeRecord();
SetEmptyFlag(state);
return this.output.RecordDone(this);
}
else {
// For end event, if there is no end token, don't force token
return Processor.OutputResult.Continue;
}
}
private void SetEmptyFlag(int state) {
Debug.Assert(this.mainNode != null);
if ((state & StateMachine.BeginChild) != 0) {
this.mainNode.IsEmptyTag = false;
}
}
private void AnalyzeSpaceLang() {
Debug.Assert(this.mainNode.NodeType == XmlNodeType.Element);
for (int attr = 0; attr < this.attributeCount; attr ++) {
Debug.Assert(this.attributeList[attr] is BuilderInfo);
BuilderInfo info = (BuilderInfo) this.attributeList[attr];
if (Ref.Equal(info.Prefix, this.atoms.Xml)) {
OutputScope scope = this.scopeManager.CurrentElementScope;
if (Ref.Equal(info.LocalName, this.atoms.Lang)) {
scope.Lang = info.Value;
}
else if (Ref.Equal(info.LocalName, this.atoms.Space)) {
scope.Space = TranslateXmlSpace(info.Value);
}
}
}
}
private void FixupElement() {
Debug.Assert(this.mainNode.NodeType == XmlNodeType.Element);
if (Ref.Equal(this.mainNode.NamespaceURI, this.atoms.Empty)) {
this.mainNode.Prefix = this.atoms.Empty;
}
if (Ref.Equal(this.mainNode.Prefix, this.atoms.Empty)) {
if (Ref.Equal(this.mainNode.NamespaceURI, this.scopeManager.DefaultNamespace)) {
// Main Node is OK
}
else {
DeclareNamespace(this.mainNode.NamespaceURI, this.mainNode.Prefix);
}
}
else {
bool thisScope = false;
string nspace = this.scopeManager.ResolveNamespace(this.mainNode.Prefix, out thisScope);
if (nspace != null) {
if (! Ref.Equal(this.mainNode.NamespaceURI, nspace)) {
if (thisScope) { // Prefix conflict
this.mainNode.Prefix = GetPrefixForNamespace(this.mainNode.NamespaceURI);
}
else {
DeclareNamespace(this.mainNode.NamespaceURI, this.mainNode.Prefix);
}
}
}
else {
DeclareNamespace(this.mainNode.NamespaceURI, this.mainNode.Prefix);
}
}
OutputScope elementScope = this.scopeManager.CurrentElementScope;
elementScope.Prefix = this.mainNode.Prefix;
}
private void FixupAttributes(int attributeCount) {
for (int attr = 0; attr < attributeCount; attr ++) {
Debug.Assert(this.attributeList[attr] is BuilderInfo);
BuilderInfo info = (BuilderInfo) this.attributeList[attr];
if (Ref.Equal(info.NamespaceURI, this.atoms.Empty)) {
info.Prefix = this.atoms.Empty;
}
else {
if (Ref.Equal(info.Prefix, this.atoms.Empty)) {
info.Prefix = GetPrefixForNamespace(info.NamespaceURI);
}
else {
bool thisScope = false;
string nspace = this.scopeManager.ResolveNamespace(info.Prefix, out thisScope);
if (nspace != null) {
if (! Ref.Equal(info.NamespaceURI, nspace)) {
if(thisScope) { // prefix conflict
info.Prefix = GetPrefixForNamespace(info.NamespaceURI);
}
else {
DeclareNamespace(info.NamespaceURI, info.Prefix);
}
}
}
else {
DeclareNamespace(info.NamespaceURI, info.Prefix);
}
}
}
}
}
private void AppendNamespaces() {
for (int i = this.namespaceCount - 1; i >= 0; i --) {
BuilderInfo attribute = (BuilderInfo) this.attributeList[NewAttribute()];
attribute.Initialize((BuilderInfo)this.namespaceList[i]);
}
}
private void AnalyzeComment() {
Debug.Assert(this.mainNode.NodeType == XmlNodeType.Comment);
Debug.Assert((object) this.currentInfo == (object) this.mainNode);
StringBuilder newComment = null;
string comment = this.mainNode.Value;
bool minus = false;
int index = 0, begin = 0;
for (; index < comment.Length; index ++) {
switch (comment[index]) {
case s_Minus:
if (minus) {
if (newComment == null)
newComment = new StringBuilder(comment, begin, index, 2 * comment.Length);
else
newComment.Append(comment, begin, index - begin);
newComment.Append(s_SpaceMinus);
begin = index + 1;
}
minus = true;
break;
default:
minus = false;
break;
}
}
if (newComment != null) {
if (begin < comment.Length)
newComment.Append(comment, begin, comment.Length - begin);
if (minus)
newComment.Append(s_Space);
this.mainNode.Value = newComment.ToString();
}
else if (minus) {
this.mainNode.ValueAppend(s_Space, false);
}
}
private void AnalyzeProcessingInstruction() {
Debug.Assert(this.mainNode.NodeType == XmlNodeType.ProcessingInstruction || this.mainNode.NodeType == XmlNodeType.XmlDeclaration);
//Debug.Assert((object) this.currentInfo == (object) this.mainNode);
StringBuilder newPI = null;
string pi = this.mainNode.Value;
bool question = false;
int index = 0, begin = 0;
for (; index < pi.Length; index ++) {
switch (pi[index]) {
case s_Question:
question = true;
break;
case s_Greater:
if (question) {
if (newPI == null) {
newPI = new StringBuilder(pi, begin, index, 2 * pi.Length);
}
else {
newPI.Append(pi, begin, index - begin);
}
newPI.Append(s_SpaceGreater);
begin = index + 1;
}
question = false;
break;
default:
question = false;
break;
}
}
if (newPI != null) {
if (begin < pi.Length) {
newPI.Append(pi, begin, pi.Length - begin);
}
this.mainNode.Value = newPI.ToString();
}
}
private void FinalizeRecord() {
switch (this.mainNode.NodeType) {
case XmlNodeType.Element:
// Save count since FixupElement can add attribute...
int attributeCount = this.attributeCount;
FixupElement();
FixupAttributes(attributeCount);
AnalyzeSpaceLang();
AppendNamespaces();
break;
case XmlNodeType.Comment:
AnalyzeComment();
break;
case XmlNodeType.ProcessingInstruction:
AnalyzeProcessingInstruction();
break;
}
}
private int NewNamespace() {
if (this.namespaceCount >= this.namespaceList.Count) {
Debug.Assert(this.namespaceCount == this.namespaceList.Count);
this.namespaceList.Add(new BuilderInfo());
}
return this.namespaceCount ++;
}
private void DeclareNamespace(string nspace, string prefix) {
int index = NewNamespace();
Debug.Assert(this.namespaceList[index] != null && this.namespaceList[index] is BuilderInfo);
BuilderInfo ns = (BuilderInfo) this.namespaceList[index];
if (prefix == this.atoms.Empty) {
ns.Initialize(this.atoms.Empty, this.atoms.Xmlns, this.atoms.XmlnsNamespace);
}
else {
ns.Initialize(this.atoms.Xmlns, prefix, this.atoms.XmlnsNamespace);
}
ns.Depth = this.recordDepth;
ns.NodeType = XmlNodeType.Attribute;
ns.Value = nspace;
this.scopeManager.PushNamespace(prefix, nspace);
}
private string DeclareNewNamespace(string nspace) {
string prefix = this.scopeManager.GeneratePrefix(PrefixFormat);
DeclareNamespace(nspace, prefix);
return prefix;
}
internal string GetPrefixForNamespace(string nspace) {
string prefix = null;
if (this.scopeManager.FindPrefix(nspace, out prefix)) {
Debug.Assert(prefix != null && prefix.Length > 0);
return prefix;
}
else {
return DeclareNewNamespace(nspace);
}
}
private static XmlSpace TranslateXmlSpace(string space) {
if (space == "default") {
return XmlSpace.Default;
}
else if (space == "preserve") {
return XmlSpace.Preserve;
}
else {
return XmlSpace.None;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
**
**
**
** Purpose: The BitArray class manages a compact array of bit values.
**
**
=============================================================================*/
namespace System.Collections {
using System;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
// A vector of bits. Use this to store bits efficiently, without having to do bit
// shifting yourself.
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable()] public sealed class BitArray : ICollection, ICloneable {
private BitArray() {
}
/*=========================================================================
** Allocates space to hold length bit values. All of the values in the bit
** array are set to false.
**
** Exceptions: ArgumentException if length < 0.
=========================================================================*/
public BitArray(int length)
: this(length, false) {
}
/*=========================================================================
** Allocates space to hold length bit values. All of the values in the bit
** array are set to defaultValue.
**
** Exceptions: ArgumentOutOfRangeException if length < 0.
=========================================================================*/
public BitArray(int length, bool defaultValue) {
if (length < 0) {
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
m_array = new int[GetArrayLength(length, BitsPerInt32)];
m_length = length;
int fillValue = defaultValue ? unchecked(((int)0xffffffff)) : 0;
for (int i = 0; i < m_array.Length; i++) {
m_array[i] = fillValue;
}
_version = 0;
}
/*=========================================================================
** Allocates space to hold the bit values in bytes. bytes[0] represents
** bits 0 - 7, bytes[1] represents bits 8 - 15, etc. The LSB of each byte
** represents the lowest index value; bytes[0] & 1 represents bit 0,
** bytes[0] & 2 represents bit 1, bytes[0] & 4 represents bit 2, etc.
**
** Exceptions: ArgumentException if bytes == null.
=========================================================================*/
public BitArray(byte[] bytes) {
if (bytes == null) {
throw new ArgumentNullException("bytes");
}
Contract.EndContractBlock();
// this value is chosen to prevent overflow when computing m_length.
// m_length is of type int32 and is exposed as a property, so
// type of m_length can't be changed to accommodate.
if (bytes.Length > Int32.MaxValue / BitsPerByte) {
throw new ArgumentException(Environment.GetResourceString("Argument_ArrayTooLarge", BitsPerByte), "bytes");
}
m_array = new int[GetArrayLength(bytes.Length, BytesPerInt32)];
m_length = bytes.Length * BitsPerByte;
int i = 0;
int j = 0;
while (bytes.Length - j >= 4) {
m_array[i++] = (bytes[j] & 0xff) |
((bytes[j + 1] & 0xff) << 8) |
((bytes[j + 2] & 0xff) << 16) |
((bytes[j + 3] & 0xff) << 24);
j += 4;
}
Contract.Assert(bytes.Length - j >= 0, "BitArray byteLength problem");
Contract.Assert(bytes.Length - j < 4, "BitArray byteLength problem #2");
switch (bytes.Length - j) {
case 3:
m_array[i] = ((bytes[j + 2] & 0xff) << 16);
goto case 2;
// fall through
case 2:
m_array[i] |= ((bytes[j + 1] & 0xff) << 8);
goto case 1;
// fall through
case 1:
m_array[i] |= (bytes[j] & 0xff);
break;
}
_version = 0;
}
public BitArray(bool[] values) {
if (values == null) {
throw new ArgumentNullException("values");
}
Contract.EndContractBlock();
m_array = new int[GetArrayLength(values.Length, BitsPerInt32)];
m_length = values.Length;
for (int i = 0;i<values.Length;i++) {
if (values[i])
m_array[i/32] |= (1 << (i%32));
}
_version = 0;
}
/*=========================================================================
** Allocates space to hold the bit values in values. values[0] represents
** bits 0 - 31, values[1] represents bits 32 - 63, etc. The LSB of each
** integer represents the lowest index value; values[0] & 1 represents bit
** 0, values[0] & 2 represents bit 1, values[0] & 4 represents bit 2, etc.
**
** Exceptions: ArgumentException if values == null.
=========================================================================*/
public BitArray(int[] values) {
if (values == null) {
throw new ArgumentNullException("values");
}
Contract.EndContractBlock();
// this value is chosen to prevent overflow when computing m_length
if (values.Length > Int32.MaxValue / BitsPerInt32) {
throw new ArgumentException(Environment.GetResourceString("Argument_ArrayTooLarge", BitsPerInt32), "values");
}
m_array = new int[values.Length];
m_length = values.Length * BitsPerInt32;
Array.Copy(values, m_array, values.Length);
_version = 0;
}
/*=========================================================================
** Allocates a new BitArray with the same length and bit values as bits.
**
** Exceptions: ArgumentException if bits == null.
=========================================================================*/
public BitArray(BitArray bits) {
if (bits == null) {
throw new ArgumentNullException("bits");
}
Contract.EndContractBlock();
int arrayLength = GetArrayLength(bits.m_length, BitsPerInt32);
m_array = new int[arrayLength];
m_length = bits.m_length;
Array.Copy(bits.m_array, m_array, arrayLength);
_version = bits._version;
}
public bool this[int index] {
get {
return Get(index);
}
set {
Set(index,value);
}
}
/*=========================================================================
** Returns the bit value at position index.
**
** Exceptions: ArgumentOutOfRangeException if index < 0 or
** index >= GetLength().
=========================================================================*/
public bool Get(int index) {
if (index < 0 || index >= Length) {
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
return (m_array[index / 32] & (1 << (index % 32))) != 0;
}
/*=========================================================================
** Sets the bit value at position index to value.
**
** Exceptions: ArgumentOutOfRangeException if index < 0 or
** index >= GetLength().
=========================================================================*/
public void Set(int index, bool value) {
if (index < 0 || index >= Length) {
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
if (value) {
m_array[index / 32] |= (1 << (index % 32));
} else {
m_array[index / 32] &= ~(1 << (index % 32));
}
_version++;
}
/*=========================================================================
** Sets all the bit values to value.
=========================================================================*/
public void SetAll(bool value) {
int fillValue = value ? unchecked(((int)0xffffffff)) : 0;
int ints = GetArrayLength(m_length, BitsPerInt32);
for (int i = 0; i < ints; i++) {
m_array[i] = fillValue;
}
_version++;
}
/*=========================================================================
** Returns a reference to the current instance ANDed with value.
**
** Exceptions: ArgumentException if value == null or
** value.Length != this.Length.
=========================================================================*/
public BitArray And(BitArray value) {
if (value==null)
throw new ArgumentNullException("value");
if (Length != value.Length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"));
Contract.EndContractBlock();
int ints = GetArrayLength(m_length, BitsPerInt32);
for (int i = 0; i < ints; i++) {
m_array[i] &= value.m_array[i];
}
_version++;
return this;
}
/*=========================================================================
** Returns a reference to the current instance ORed with value.
**
** Exceptions: ArgumentException if value == null or
** value.Length != this.Length.
=========================================================================*/
public BitArray Or(BitArray value) {
if (value==null)
throw new ArgumentNullException("value");
if (Length != value.Length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"));
Contract.EndContractBlock();
int ints = GetArrayLength(m_length, BitsPerInt32);
for (int i = 0; i < ints; i++) {
m_array[i] |= value.m_array[i];
}
_version++;
return this;
}
/*=========================================================================
** Returns a reference to the current instance XORed with value.
**
** Exceptions: ArgumentException if value == null or
** value.Length != this.Length.
=========================================================================*/
public BitArray Xor(BitArray value) {
if (value==null)
throw new ArgumentNullException("value");
if (Length != value.Length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"));
Contract.EndContractBlock();
int ints = GetArrayLength(m_length, BitsPerInt32);
for (int i = 0; i < ints; i++) {
m_array[i] ^= value.m_array[i];
}
_version++;
return this;
}
/*=========================================================================
** Inverts all the bit values. On/true bit values are converted to
** off/false. Off/false bit values are turned on/true. The current instance
** is updated and returned.
=========================================================================*/
public BitArray Not() {
int ints = GetArrayLength(m_length, BitsPerInt32);
for (int i = 0; i < ints; i++) {
m_array[i] = ~m_array[i];
}
_version++;
return this;
}
public int Length {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
return m_length;
}
set {
if (value < 0) {
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
int newints = GetArrayLength(value, BitsPerInt32);
if (newints > m_array.Length || newints + _ShrinkThreshold < m_array.Length) {
// grow or shrink (if wasting more than _ShrinkThreshold ints)
int[] newarray = new int[newints];
Array.Copy(m_array, newarray, newints > m_array.Length ? m_array.Length : newints);
m_array = newarray;
}
if (value > m_length) {
// clear high bit values in the last int
int last = GetArrayLength(m_length, BitsPerInt32) - 1;
int bits = m_length % 32;
if (bits > 0) {
m_array[last] &= (1 << bits) - 1;
}
// clear remaining int values
Array.Clear(m_array, last + 1, newints - last - 1);
}
m_length = value;
_version++;
}
}
// ICollection implementation
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
Contract.EndContractBlock();
if (array is int[])
{
Array.Copy(m_array, 0, array, index, GetArrayLength(m_length, BitsPerInt32));
}
else if (array is byte[])
{
int arrayLength = GetArrayLength(m_length, BitsPerByte);
if ((array.Length - index) < arrayLength)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
byte [] b = (byte[])array;
for (int i = 0; i < arrayLength; i++)
b[index + i] = (byte)((m_array[i/4] >> ((i%4)*8)) & 0x000000FF); // Shift to bring the required byte to LSB, then mask
}
else if (array is bool[])
{
if (array.Length - index < m_length)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
bool [] b = (bool[])array;
for (int i = 0;i<m_length;i++)
b[index + i] = ((m_array[i/32] >> (i%32)) & 0x00000001) != 0;
}
else
throw new ArgumentException(Environment.GetResourceString("Arg_BitArrayTypeUnsupported"));
}
public int Count
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return m_length;
}
}
public Object Clone()
{
Contract.Ensures(Contract.Result<Object>() != null);
Contract.Ensures(((BitArray)Contract.Result<Object>()).Length == this.Length);
return new BitArray(this);
}
public Object SyncRoot
{
get
{
if( _syncRoot == null) {
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public IEnumerator GetEnumerator()
{
return new BitArrayEnumeratorSimple(this);
}
// XPerY=n means that n Xs can be stored in 1 Y.
private const int BitsPerInt32 = 32;
private const int BytesPerInt32 = 4;
private const int BitsPerByte = 8;
/// <summary>
/// Used for conversion between different representations of bit array.
/// Returns (n+(div-1))/div, rearranged to avoid arithmetic overflow.
/// For example, in the bit to int case, the straightforward calc would
/// be (n+31)/32, but that would cause overflow. So instead it's
/// rearranged to ((n-1)/32) + 1, with special casing for 0.
///
/// Usage:
/// GetArrayLength(77, BitsPerInt32): returns how many ints must be
/// allocated to store 77 bits.
/// </summary>
/// <param name="n"></param>
/// <param name="div">use a conversion constant, e.g. BytesPerInt32 to get
/// how many ints are required to store n bytes</param>
/// <returns></returns>
private static int GetArrayLength(int n, int div) {
Contract.Assert(div > 0, "GetArrayLength: div arg must be greater than 0");
return n > 0 ? (((n - 1) / div) + 1) : 0;
}
[Serializable]
private class BitArrayEnumeratorSimple : IEnumerator, ICloneable
{
private BitArray bitarray;
private int index;
private int version;
private bool currentElement;
internal BitArrayEnumeratorSimple(BitArray bitarray) {
this.bitarray = bitarray;
this.index = -1;
version = bitarray._version;
}
public Object Clone() {
return MemberwiseClone();
}
public virtual bool MoveNext() {
if (version != bitarray._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
if (index < (bitarray.Count-1)) {
index++;
currentElement = bitarray.Get(index);
return true;
}
else
index = bitarray.Count;
return false;
}
public virtual Object Current {
get {
if (index == -1)
throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
if (index >= bitarray.Count)
throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
return currentElement;
}
}
public void Reset() {
if (version != bitarray._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
index = -1;
}
}
private int[] m_array;
private int m_length;
private int _version;
[NonSerialized]
private Object _syncRoot;
private const int _ShrinkThreshold = 256;
}
}
| |
//
// StringUtil.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2006-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
using System.Text.RegularExpressions;
namespace Hyena
{
public static class StringUtil
{
private static CompareOptions compare_options =
CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth;
public static int RelaxedIndexOf (string haystack, string needle)
{
return CultureInfo.CurrentCulture.CompareInfo.IndexOf (haystack, needle, compare_options);
}
public static int RelaxedCompare (string a, string b)
{
if (a == null && b == null) {
return 0;
} else if (a != null && b == null) {
return 1;
} else if (a == null && b != null) {
return -1;
}
int a_offset = a.StartsWith ("the ") ? 4 : 0;
int b_offset = b.StartsWith ("the ") ? 4 : 0;
return CultureInfo.CurrentCulture.CompareInfo.Compare (a, a_offset, a.Length - a_offset,
b, b_offset, b.Length - b_offset, compare_options);
}
public static string CamelCaseToUnderCase (string s)
{
return CamelCaseToUnderCase (s, '_');
}
private static Regex camelcase = new Regex ("([A-Z]{1}[a-z]+)", RegexOptions.Compiled);
public static string CamelCaseToUnderCase (string s, char underscore)
{
if (String.IsNullOrEmpty (s)) {
return null;
}
StringBuilder undercase = new StringBuilder ();
string [] tokens = camelcase.Split (s);
for (int i = 0; i < tokens.Length; i++) {
if (tokens[i] == String.Empty) {
continue;
}
undercase.Append (tokens[i].ToLower (System.Globalization.CultureInfo.InvariantCulture));
if (i < tokens.Length - 2) {
undercase.Append (underscore);
}
}
return undercase.ToString ();
}
public static string UnderCaseToCamelCase (string s)
{
if (String.IsNullOrEmpty (s)) {
return null;
}
StringBuilder builder = new StringBuilder ();
for (int i = 0, n = s.Length, b = -1; i < n; i++) {
if (b < 0 && s[i] != '_') {
builder.Append (Char.ToUpper (s[i]));
b = i;
} else if (s[i] == '_' && i + 1 < n && s[i + 1] != '_') {
if (builder.Length > 0 && Char.IsUpper (builder[builder.Length - 1])) {
builder.Append (Char.ToLower (s[i + 1]));
} else {
builder.Append (Char.ToUpper (s[i + 1]));
}
i++;
b = i;
} else if (s[i] != '_') {
builder.Append (Char.ToLower (s[i]));
b = i;
}
}
return builder.ToString ();
}
public static string RemoveNewlines (string input)
{
if (input != null) {
return input.Replace ("\r\n", String.Empty).Replace ("\n", String.Empty);
}
return null;
}
private static Regex tags = new Regex ("<[^>]+>", RegexOptions.Compiled | RegexOptions.Multiline);
public static string RemoveHtml (string input)
{
if (input == null) {
return input;
}
return tags.Replace (input, String.Empty);
}
public static string DoubleToTenthsPrecision (double num)
{
return DoubleToTenthsPrecision (num, false);
}
public static string DoubleToTenthsPrecision (double num, bool always_decimal)
{
return DoubleToTenthsPrecision (num, always_decimal, NumberFormatInfo.CurrentInfo);
}
public static string DoubleToTenthsPrecision (double num, bool always_decimal, IFormatProvider provider)
{
num = Math.Round (num, 1, MidpointRounding.ToEven);
return String.Format (provider, !always_decimal && num == (int)num ? "{0:N0}" : "{0:N1}", num);
}
// This method helps us pluralize doubles. Probably a horrible i18n idea.
public static int DoubleToPluralInt (double num)
{
if (num == (int)num)
return (int)num;
else
return (int)num + 1;
}
// A mapping of non-Latin characters to be considered the same as
// a Latin equivalent.
private static Dictionary<char, char> BuildSpecialCases ()
{
Dictionary<char, char> dict = new Dictionary<char, char> ();
dict['\u00f8'] = 'o';
dict['\u0142'] = 'l';
return dict;
}
private static Dictionary<char, char> searchkey_special_cases = BuildSpecialCases ();
// Removes accents from Latin characters, and some kinds of punctuation.
public static string SearchKey (string val)
{
if (String.IsNullOrEmpty (val)) {
return val;
}
val = val.ToLower ();
StringBuilder sb = new StringBuilder ();
UnicodeCategory category;
bool previous_was_latin = false;
bool got_space = false;
// Normalizing to KD splits into (base, combining) so we can check for Latin
// characters and then strip off any NonSpacingMarks following them
foreach (char orig_c in val.TrimStart ().Normalize (NormalizationForm.FormKD)) {
// Check for a special case *before* whitespace. This way, if
// a special case is ever added that maps to ' ' or '\t', it
// won't cause a run of whitespace in the result.
char c = orig_c;
if (searchkey_special_cases.ContainsKey (c)) {
c = searchkey_special_cases[c];
}
if (c == ' ' || c == '\t') {
got_space = true;
continue;
}
category = Char.GetUnicodeCategory (c);
if (category == UnicodeCategory.OtherPunctuation) {
// Skip punctuation
} else if (!(previous_was_latin && category == UnicodeCategory.NonSpacingMark)) {
if (got_space) {
sb.Append (" ");
got_space = false;
}
sb.Append (c);
}
// Can ignore A-Z because we've already lowercased the char
previous_was_latin = (c >= 'a' && c <= 'z');
}
string result = sb.ToString ();
try {
result = result.Normalize (NormalizationForm.FormKC);
}
catch {
// FIXME: work-around, see http://bugzilla.gnome.org/show_bug.cgi?id=590478
}
return result;
}
private static Regex invalid_path_regex = BuildInvalidPathRegex ();
private static Regex BuildInvalidPathRegex ()
{
char [] invalid_path_characters = new char [] {
// Control characters: there's no reason to ever have one of these in a track name anyway,
// and they're invalid in all Windows filesystems.
'\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
'\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F',
'\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
'\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D', '\x1E', '\x1F',
// Invalid in FAT32 / NTFS: " \ / : * | ? < >
// Invalid in HFS :
// Invalid in ext3 /
'"', '\\', '/', ':', '*', '|', '?', '<', '>'
};
string regex_str = "[";
for (int i = 0; i < invalid_path_characters.Length; i++) {
regex_str += "\\" + invalid_path_characters[i];
}
regex_str += "]+";
return new Regex (regex_str, RegexOptions.Compiled);
}
private static CompareInfo culture_compare_info = CultureInfo.CurrentCulture.CompareInfo;
public static byte[] SortKey (string orig)
{
if (orig == null) { return null; }
return culture_compare_info.GetSortKey (orig, CompareOptions.IgnoreCase).KeyData;
}
private static readonly char[] escape_path_trim_chars = new char[] {'.', '\x20'};
public static string EscapeFilename (string input)
{
if (input == null)
return "";
// Remove leading and trailing dots and spaces.
input = input.Trim (escape_path_trim_chars);
return invalid_path_regex.Replace (input, "_");
}
public static string EscapePath (string input)
{
if (input == null)
return "";
// This method should be called before the full path is constructed.
if (Path.IsPathRooted (input)) {
return input;
}
StringBuilder builder = new StringBuilder ();
foreach (string name in input.Split (Path.DirectorySeparatorChar)) {
// Escape the directory or the file name.
string escaped = EscapeFilename (name);
// Skip empty names.
if (escaped.Length > 0) {
builder.Append (escaped);
builder.Append (Path.DirectorySeparatorChar);
}
}
// Chop off the last character.
if (builder.Length > 0) {
builder.Length--;
}
return builder.ToString ();
}
public static string MaybeFallback (string input, string fallback)
{
string trimmed = input == null ? null : input.Trim ();
return String.IsNullOrEmpty (trimmed) ? fallback : trimmed;
}
public static uint SubstringCount (string haystack, string needle)
{
if (String.IsNullOrEmpty (haystack) || String.IsNullOrEmpty (needle)) {
return 0;
}
int position = 0;
uint count = 0;
while (true) {
int index = haystack.IndexOf (needle, position);
if (index < 0) {
return count;
}
count++;
position = index + 1;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using Xunit;
public static class GuidTests
{
private static readonly Guid _testGuid = new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff");
[Fact]
public static void Testctor()
{
// Void Guid..ctor(Byte[])
var g1 = new Guid(_testGuid.ToByteArray());
Assert.Equal(_testGuid, g1);
// Void Guid..ctor(Int32, Int16, Int16, Byte, Byte, Byte, Byte, Byte, Byte, Byte, Byte)
var g2 = new Guid(unchecked((int)0xa8a110d5), unchecked((short)0xfc49), (short)0x43c5, 0xbf, 0x46, 0x80, 0x2d, 0xb8, 0xf8, 0x43, 0xff);
Assert.Equal(_testGuid, g2);
// Void Guid..ctor(Int32, Int16, Int16, Byte[])
var g3 = new Guid(unchecked((int)0xa8a110d5), unchecked((short)0xfc49), (short)0x43c5, new byte[] { 0xbf, 0x46, 0x80, 0x2d, 0xb8, 0xf8, 0x43, 0xff });
Assert.Equal(_testGuid, g3);
// Void Guid..ctor(String)
var g4 = new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff");
Assert.Equal(_testGuid, g4);
}
[Fact]
public static void TestEquals()
{
// Boolean Guid.Equals(Guid)
Assert.True(_testGuid.Equals(_testGuid));
Assert.False(_testGuid.Equals(Guid.Empty));
Assert.False(Guid.Empty.Equals(_testGuid));
// Boolean Guid.Equals(Object)
Assert.False(_testGuid.Equals(null));
Assert.False(_testGuid.Equals("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
// Boolean Guid.op_Equality(Guid, Guid)
Assert.True(_testGuid == new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
Assert.True(Guid.Empty == new Guid(0, 0, 0, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }));
// Boolean Guid.op_Inequality(Guid, Guid)
Assert.True(_testGuid != Guid.Empty);
Assert.True(Guid.Empty != _testGuid);
}
[Fact]
public static void TestCompareTo()
{
// Int32 Guid.CompareTo(Guid)
Assert.True(_testGuid.CompareTo(new Guid("98a110d5-fc49-43c5-bf46-802db8f843ff")) > 0);
Assert.True(_testGuid.CompareTo(new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff")) == 0);
Assert.True(_testGuid.CompareTo(new Guid("e8a110d5-fc49-43c5-bf46-802db8f843ff")) < 0);
// Int32 Guid.System.IComparable.CompareTo(Object)
IComparable icomp = _testGuid;
Assert.True(icomp.CompareTo(new Guid("98a110d5-fc49-43c5-bf46-802db8f843ff")) > 0);
Assert.True(icomp.CompareTo(new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff")) == 0);
Assert.True(icomp.CompareTo(new Guid("e8a110d5-fc49-43c5-bf46-802db8f843ff")) < 0);
Assert.True(icomp.CompareTo(null) > 0);
Assert.Throws<ArgumentException>(() => icomp.CompareTo("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
}
[Fact]
public static void TestToByteArray()
{
// Byte[] Guid.ToByteArray()
var bytes1 = new byte[] { 0xd5, 0x10, 0xa1, 0xa8, 0x49, 0xfc, 0xc5, 0x43, 0xbf, 0x46, 0x80, 0x2d, 0xb8, 0xf8, 0x43, 0xff };
var bytes2 = _testGuid.ToByteArray();
Assert.Equal(bytes1.Length, bytes2.Length);
for (int i = 0; i < bytes1.Length; i++)
Assert.Equal(bytes1[i], bytes2[i]);
}
[Fact]
public static void TestEmpty()
{
// Guid Guid.Empty
Assert.Equal(Guid.Empty, new Guid(0, 0, 0, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }));
}
[Fact]
public static void TestNewGuid()
{
// Guid Guid.NewGuid()
var g = Guid.NewGuid();
Assert.NotEqual(Guid.Empty, g);
var g2 = Guid.NewGuid();
Assert.NotEqual(g, g2);
}
[Fact]
public static void TestParse()
{
// Guid Guid.Parse(String)
// Guid Guid.ParseExact(String, String)
Assert.Equal(_testGuid, Guid.Parse("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
Assert.Equal(_testGuid, Guid.Parse("a8a110d5fc4943c5bf46802db8f843ff"));
Assert.Equal(_testGuid, Guid.Parse("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
Assert.Equal(_testGuid, Guid.Parse("{a8a110d5-fc49-43c5-bf46-802db8f843ff}"));
Assert.Equal(_testGuid, Guid.Parse("(a8a110d5-fc49-43c5-bf46-802db8f843ff)"));
Assert.Equal(_testGuid, Guid.Parse("{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}"));
Assert.Equal(_testGuid, Guid.ParseExact("a8a110d5fc4943c5bf46802db8f843ff", "N"));
Assert.Equal(_testGuid, Guid.ParseExact("a8a110d5-fc49-43c5-bf46-802db8f843ff", "D"));
Assert.Equal(_testGuid, Guid.ParseExact("{a8a110d5-fc49-43c5-bf46-802db8f843ff}", "B"));
Assert.Equal(_testGuid, Guid.ParseExact("(a8a110d5-fc49-43c5-bf46-802db8f843ff)", "P"));
Assert.Equal(_testGuid, Guid.ParseExact("{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}", "X"));
}
[Fact]
public static void TestTryParse()
{
// Boolean Guid.TryParse(String, Guid)
// Boolean Guid.TryParseExact(String, String, Guid)
Guid g;
Assert.True(Guid.TryParse("a8a110d5-fc49-43c5-bf46-802db8f843ff", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("a8a110d5fc4943c5bf46802db8f843ff", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("a8a110d5-fc49-43c5-bf46-802db8f843ff", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("{a8a110d5-fc49-43c5-bf46-802db8f843ff}", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("(a8a110d5-fc49-43c5-bf46-802db8f843ff)", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("a8a110d5fc4943c5bf46802db8f843ff", "N", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("a8a110d5-fc49-43c5-bf46-802db8f843ff", "D", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("{a8a110d5-fc49-43c5-bf46-802db8f843ff}", "B", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("(a8a110d5-fc49-43c5-bf46-802db8f843ff)", "P", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}", "X", out g));
Assert.Equal(_testGuid, g);
Assert.False(Guid.TryParse("a8a110d5fc4943c5bf46802db8f843f", out g)); // One two few digits
Assert.False(Guid.TryParseExact("a8a110d5-fc49-43c5-bf46-802db8f843ff", "N", out g)); // Contains '-' when "N" doesn't support those
}
[Fact]
public static void TestGetHashCode()
{
// Int32 Guid.GetHashCode()
Assert.NotEqual(_testGuid.GetHashCode(), Guid.Empty.GetHashCode());
}
[Fact]
public static void TestToString()
{
// String Guid.ToString()
// String Guid.ToString(String)
// String Guid.System.IFormattable.ToString(String, IFormatProvider) // The IFormatProvider is ignored so don't need to test
Assert.Equal(_testGuid.ToString(), "a8a110d5-fc49-43c5-bf46-802db8f843ff");
Assert.Equal(_testGuid.ToString("N"), "a8a110d5fc4943c5bf46802db8f843ff");
Assert.Equal(_testGuid.ToString("D"), "a8a110d5-fc49-43c5-bf46-802db8f843ff");
Assert.Equal(_testGuid.ToString("B"), "{a8a110d5-fc49-43c5-bf46-802db8f843ff}");
Assert.Equal(_testGuid.ToString("P"), "(a8a110d5-fc49-43c5-bf46-802db8f843ff)");
Assert.Equal(_testGuid.ToString("X"), "{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}");
}
[Fact]
public static void TestRandomness()
{
const int Iterations = 100;
const int GuidSize = 16;
byte[] random = new byte[GuidSize * Iterations];
for (int i = 0; i < Iterations; i++)
{
// Get a new Guid
Guid g = Guid.NewGuid();
byte[] bytes = g.ToByteArray();
// Make sure it's different from all of the previously created ones
for (int j = 0; j < i; j++)
{
Assert.False(bytes.SequenceEqual(new ArraySegment<byte>(random, j * GuidSize, GuidSize)));
}
// Copy it to our randomness array
Array.Copy(bytes, 0, random, i * GuidSize, GuidSize);
}
// Verify the randomness of the data in the array. Guid has some small bias in it
// due to several bits fixed based on the format, but that bias is small enough and
// the variability allowed by VerifyRandomDistribution large enough that we don't do
// anything special for it.
RandomDataGenerator.VerifyRandomDistribution(random);
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Principal;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Counters;
namespace Orleans.Counter.Control
{
using System.Collections.Generic;
using Orleans.Serialization;
/// <summary>
/// Control Orleans Counters - Register or Unregister the Orleans counter set
/// </summary>
internal class CounterControl
{
public bool Unregister { get; private set; }
public bool BruteForce { get; private set; }
public bool NeedRunAsAdministrator { get; private set; }
public bool IsRunningAsAdministrator { get; private set; }
public bool PauseAtEnd { get; private set; }
public CounterControl()
{
// Check user is Administrator and has granted UAC elevation permission to run this app
var userIdent = WindowsIdentity.GetCurrent();
var userPrincipal = new WindowsPrincipal(userIdent);
IsRunningAsAdministrator = userPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}
public void PrintUsage()
{
using (var usageStr = new StringWriter())
{
usageStr.WriteLine(typeof(CounterControl).GetTypeInfo().Assembly.GetName().Name + ".exe {command}");
usageStr.WriteLine("Where commands are:");
usageStr.WriteLine(" /? or /help = Display usage info");
usageStr.WriteLine(" /r or /register = Register Windows performance counters for Orleans [default]");
usageStr.WriteLine(" /u or /unregister = Unregister Windows performance counters for Orleans");
usageStr.WriteLine(" /f or /force = Use brute force, if necessary");
usageStr.WriteLine(" /pause = Pause for user key press after operation");
ConsoleText.WriteUsage(usageStr.ToString());
}
}
public bool ParseArguments(string[] args)
{
bool ok = true;
NeedRunAsAdministrator = true;
Unregister = false;
foreach (var arg in args)
{
if (arg.StartsWith("/") || arg.StartsWith("-"))
{
var a = arg.ToLowerInvariant().Substring(1);
switch (a)
{
case "r":
case "register":
Unregister = false;
break;
case "u":
case "unregister":
Unregister = true;
break;
case "f":
case "force":
BruteForce = true;
break;
case "pause":
PauseAtEnd = true;
break;
case "?":
case "help":
NeedRunAsAdministrator = false;
ok = false;
break;
default:
NeedRunAsAdministrator = false;
ok = false;
break;
}
}
else
{
ConsoleText.WriteError("Unrecognised command line option: " + arg);
ok = false;
}
}
return ok;
}
public int Run()
{
if (NeedRunAsAdministrator && !IsRunningAsAdministrator)
{
ConsoleText.WriteError("Need to be running in Administrator role to perform the requested operations.");
return 1;
}
SerializationManager.InitializeForTesting();
InitConsoleLogging();
try
{
if (Unregister)
{
ConsoleText.WriteStatus("Unregistering Orleans performance counters with Windows");
UnregisterWindowsPerfCounters(this.BruteForce);
}
else
{
ConsoleText.WriteStatus("Registering Orleans performance counters with Windows");
RegisterWindowsPerfCounters(true); // Always reinitialize counter registrations, even if already existed
}
ConsoleText.WriteStatus("Operation completed successfully.");
return 0;
}
catch (Exception exc)
{
ConsoleText.WriteError("Error running " + typeof(CounterControl).GetTypeInfo().Assembly.GetName().Name + ".exe", exc);
if (!BruteForce) return 2;
ConsoleText.WriteStatus("Ignoring error due to brute-force mode");
return 0;
}
}
/// <summary>
/// Initialize log infrastrtucture for Orleans runtime sub-components
/// </summary>
private static void InitConsoleLogging()
{
Trace.Listeners.Clear();
var cfg = new NodeConfiguration { TraceFilePattern = null, TraceToConsole = false };
LogManager.Initialize(cfg);
//TODO: Move it to use the APM APIs
//var logWriter = new LogWriterToConsole(true, true); // Use compact console output & no timestamps / log message metadata
//LogManager.LogConsumers.Add(logWriter);
}
/// <summary>
/// Create the set of Orleans counters, if they do not already exist
/// </summary>
/// <param name="useBruteForce">Use brute force, if necessary</param>
/// <remarks>Note: Program needs to be running as Administrator to be able to register Windows perf counters.</remarks>
private static void RegisterWindowsPerfCounters(bool useBruteForce)
{
try
{
if (OrleansPerfCounterManager.AreWindowsPerfCountersAvailable())
{
if (!useBruteForce)
{
ConsoleText.WriteStatus("Orleans counters are already registered -- Use brute-force mode to re-initialize");
return;
}
// Delete any old perf counters
UnregisterWindowsPerfCounters(true);
}
if (GrainTypeManager.Instance == null)
{
var loader = new SiloAssemblyLoader(new Dictionary<string, SearchOption>());
var typeManager = new GrainTypeManager(false, null, loader); // We shouldn't need GrainFactory in this case
GrainTypeManager.Instance.Start(false);
}
// Register perf counters
OrleansPerfCounterManager.InstallCounters();
if (OrleansPerfCounterManager.AreWindowsPerfCountersAvailable())
ConsoleText.WriteStatus("Orleans counters registered successfully");
else
ConsoleText.WriteError("Orleans counters are NOT registered");
}
catch (Exception exc)
{
ConsoleText.WriteError("Error registering Orleans counters - {0}" + exc);
throw;
}
}
/// <summary>
/// Remove the set of Orleans counters, if they already exist
/// </summary>
/// <param name="useBruteForce">Use brute force, if necessary</param>
/// <remarks>Note: Program needs to be running as Administrator to be able to unregister Windows perf counters.</remarks>
private static void UnregisterWindowsPerfCounters(bool useBruteForce)
{
if (!OrleansPerfCounterManager.AreWindowsPerfCountersAvailable())
{
ConsoleText.WriteStatus("Orleans counters are already unregistered");
return;
}
// Delete any old perf counters
try
{
OrleansPerfCounterManager.DeleteCounters();
}
catch (Exception exc)
{
ConsoleText.WriteError("Error deleting old Orleans counters - {0}" + exc);
if (useBruteForce)
ConsoleText.WriteStatus("Ignoring error deleting Orleans counters due to brute-force mode");
else
throw;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using RA.Enums;
using RA.Exceptions;
using RA.Extensions;
using System.Xml.Linq;
namespace RA
{
public class ResponseContext
{
private readonly HttpStatusCode _statusCode;
private readonly string _content;
private dynamic _parsedContent;
private readonly Dictionary<string, IEnumerable<string>> _headers = new Dictionary<string, IEnumerable<string>>();
private TimeSpan _elapsedExecutionTime;
private readonly Dictionary<string, double> _loadValues = new Dictionary<string, double>();
private readonly Dictionary<string, bool> _assertions = new Dictionary<string, bool>();
private readonly List<LoadResponse> _loadResponses;
private bool _isSchemaValid = true;
private List<string> _schemaErrors = new List<string>();
public ResponseContext(HttpStatusCode statusCode, string content, Dictionary<string, IEnumerable<string>> headers, TimeSpan elaspedExecutionTime, List<LoadResponse> loadResponses)
{
_statusCode = statusCode;
_content = content;
_headers = headers;
_elapsedExecutionTime = elaspedExecutionTime;
_loadResponses = loadResponses ?? new List<LoadResponse>();
Initialize();
}
/// <summary>
/// Retrieve an object from the response document.
/// </summary>
/// <param name="func"></param>
/// <returns></returns>
public object Retrieve(Func<dynamic, object> func)
{
try
{
return func.Invoke(_parsedContent).Value;
}
catch { }
try
{
return func.Invoke(_parsedContent);
}
catch { }
return null;
}
/// <summary>
/// Setup a test against the body of response document.
/// </summary>
/// <param name="ruleName"></param>
/// <param name="func"></param>
/// <returns></returns>
public ResponseContext TestBody(string ruleName, Func<dynamic, bool> func)
{
return TestWrapper(ruleName, () => func.Invoke(_parsedContent));
}
/// <summary>
/// Setup a test against the response headers.
/// </summary>
/// <param name="ruleName"></param>
/// <param name="key"></param>
/// <param name="func"></param>
/// <returns></returns>
public ResponseContext TestHeader(string ruleName, string key, Func<string, bool> func)
{
return TestWrapper(ruleName, () => func.Invoke(HeaderValue(key.Trim())));
}
/// <summary>
/// Setup a test against the response time (total milliseconds)
/// </summary>
/// <param name="ruleName"></param>
/// <param name="func"></param>
/// <returns></returns>
public ResponseContext TestElaspedTime(string ruleName, Func<double, bool> func)
{
return TestWrapper(ruleName, () => func.Invoke(_elapsedExecutionTime.TotalMilliseconds));
}
/// <summary>
/// Setup a test against the calculated load test values. The entire set of
/// load test values are only available if a load test was configured with the
/// When().Load() call.
/// </summary>
/// <param name="ruleName"></param>
/// <param name="key"></param>
/// <param name="func"></param>
/// <returns></returns>
public ResponseContext TestLoad(string ruleName, string key, Func<double, bool> func)
{
return TestWrapper(ruleName, () => func.Invoke(LoadValue(key.Trim())));
}
/// <summary>
/// Setup a test against the response status
/// eg: OK 200 or Error 400
/// </summary>
/// <param name="ruleName"></param>
/// <param name="func"></param>
/// <returns></returns>
public ResponseContext TestStatus(string ruleName, Func<int, bool> func)
{
return TestWrapper(ruleName, () => func.Invoke((int)_statusCode));
}
private ResponseContext TestWrapper(string ruleName, Func<bool> func)
{
if (_assertions.ContainsKey(ruleName))
throw new ArgumentException(string.Format("Rule for ({0}) already exist", ruleName));
var result = false;
try
{
result = func.Invoke();
}
catch
{ }
_assertions.Add(ruleName, result);
return this;
}
/// <summary>
/// Setup a schema to validate the response body structure with.
/// For JSON, v3 and v4 of the JSON schema draft specificiation are respected.
/// </summary>
/// <param name="schema"></param>
/// <returns></returns>
public ResponseContext Schema(string schema)
{
JSchema jSchema = null;
try
{
jSchema = JSchema.Parse(schema);
}
catch (Exception ex)
{
throw new ArgumentException("Schema is not valid", "schema", ex);
}
IList<string> messages;
var trimmedContent = _content.TrimStart();
_isSchemaValid =
trimmedContent.StartsWith("{")
? JObject.Parse(_content).IsValid(jSchema, out messages)
: JArray.Parse(_content).IsValid(jSchema, out messages);
if (!_isSchemaValid)
{
foreach (var message in messages)
{
_schemaErrors.Add(message);
}
}
return this;
}
public ResponseContext Assert(string ruleName)
{
if (!_assertions.ContainsKey(ruleName)) return this;
if (!_assertions[ruleName])
throw new AssertException($"({ruleName}) Test Failed");
// in order to allow multiple asserts
return this;
}
/// <summary>
/// Assert schema for validity. Failures will produce an AssertException.
/// </summary>
public void AssertSchema()
{
if (!_isSchemaValid)
{
throw new AssertException(string.Format("Schema Check Failed"));
}
}
/// <summary>
/// Assert all test and schema for validity. You can optionally skip schema validation. Failures will produce an AssertException.
/// </summary>
/// /// <param name="assertSchema"></param>
public void AssertAll(bool assertSchema = true)
{
Console.WriteLine(_assertions.Count);
foreach (var assertion in _assertions)
{
Console.WriteLine(assertion.Value);
if (!assertion.Value)
throw new AssertException(string.Format("({0}) Test Failed", assertion.Key));
}
if (assertSchema)
AssertSchema();
}
private void Initialize()
{
Parse();
ParseLoad();
}
private void Parse()
{
var contentType = ContentType();
if (contentType.Contains("json"))
{
if (!string.IsNullOrEmpty(_content))
{
try
{
_parsedContent = JObject.Parse(_content);
return;
}
catch
{
}
try
{
_parsedContent = JArray.Parse(_content);
return;
}
catch
{
}
}
else
{
return;
}
}
else if (contentType.Contains("xml"))
{
if (!string.IsNullOrEmpty(_content))
{
try
{
_parsedContent = XDocument.Parse(_content);
return;
}
catch
{
}
}
}
if (!string.IsNullOrEmpty(_content))
throw new Exception(string.Format("({0}) not supported", contentType));
}
private void ParseLoad()
{
if (_loadResponses.Any())
{
_loadValues.Add(LoadValueTypes.TotalCall.Value, _loadResponses.Count);
_loadValues.Add(LoadValueTypes.TotalSucceeded.Value, _loadResponses.Count(x => x.StatusCode == (int)HttpStatusCode.OK));
_loadValues.Add(LoadValueTypes.TotalLost.Value, _loadResponses.Count(x => x.StatusCode == -1));
_loadValues.Add(LoadValueTypes.AverageTTLMs.Value, new TimeSpan((long)_loadResponses.Where(x => x.StatusCode == (int)HttpStatusCode.OK).Average(x => x.Ticks)).TotalMilliseconds);
_loadValues.Add(LoadValueTypes.MaximumTTLMs.Value, new TimeSpan(_loadResponses.Where(x => x.StatusCode == (int)HttpStatusCode.OK).Max(x => x.Ticks)).TotalMilliseconds);
_loadValues.Add(LoadValueTypes.MinimumTTLMs.Value, new TimeSpan(_loadResponses.Where(x => x.StatusCode == (int)HttpStatusCode.OK).Min(x => x.Ticks)).TotalMilliseconds);
}
}
private string ContentType()
{
return HeaderValue(HeaderType.ContentType.Value);
}
private string HeaderValue(string key)
{
return _headers.Where(x => x.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase))
.Select(x => string.Join(", ", x.Value))
.DefaultIfEmpty(string.Empty)
.FirstOrDefault();
}
private double LoadValue(string key)
{
return _loadValues.Where(x => x.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase))
.Select(x => x.Value)
.DefaultIfEmpty(0)
.FirstOrDefault();
}
/// <summary>
/// Output all debug values from the setup context.
/// </summary>
/// <returns></returns>
public ResponseContext Debug()
{
"status code".WriteHeader();
((int)_statusCode).ToString().WriteLine();
"response headers".WriteHeader();
foreach (var header in _headers)
{
"{0} : {1}".WriteLine(header.Key, string.Join(", ", header.Value));
}
"content".WriteHeader();
"{0}\n".Write(_content);
"assertions".WriteHeader();
foreach (var assertion in _assertions)
{
"{0} : {1}".WriteLine(assertion.Key, assertion.Value);
}
"schema errors".WriteHeader();
foreach (var schemaError in _schemaErrors)
{
schemaError.WriteLine();
}
if (_loadResponses.Any())
{
"load test result".WriteHeader();
LoadValueTypes.GetAll().ForEach(x => "{0} {1}".WriteLine(_loadValues[x.Value], x.DisplayName.ToLower()));
}
return this;
}
/// <summary>
/// Write the response of all asserted test via Console.IO
/// </summary>
/// <returns></returns>
public ResponseContext WriteAssertions()
{
"assertions".WriteHeader();
foreach (var assertion in _assertions)
{
assertion.WriteTest();
}
"schema validation".WriteHeader();
if (_isSchemaValid) ConsoleExtensions.WritePassedTest();
else ConsoleExtensions.WriteFailedTest();
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Text;
namespace TinkerWorX.GPUDust
{
public class GPUDustGame : Game
{
private const Single NONE = 0.00f;
private const Single DUST = 0.02f;
private const Single WALL = 0.04f;
private const Single FLUID = 0.06f;
private const Single SAND = 0.02f;
private const Single DIRT = 0.04f;
private const Single CONCRETE = 0.06f;
private const Single FIRE = 0.08f;
private const Single WATER = 0.10f;
private const Single PLANT = 0.12f;
private const Single MOVE_NONE = 0.00f;
private const Single MOVE_RIGHT = 0.02f;
private const Single MOVE_DOWN = 0.04f;
private const Single MOVE_LEFT = 0.06f;
private const Single MOVE_UP = 0.08f;
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
private RenderTarget2D newBuffer;
private RenderTarget2D oldBuffer;
private Texture2D pixelTexture;
private Effect startPhase;
private Effect dustPhase;
private Effect fluidPhase;
private Effect movePhase;
private Effect reactivePhase;
private Effect colorPhase;
private FPSCounterComponent fpsCounter;
private Vector2[,] spray = new Vector2[25, 25];
public GPUDustGame()
{
this.graphics = new GraphicsDeviceManager(this);
this.graphics.PreferredBackBufferWidth = 1280;
this.graphics.PreferredBackBufferHeight = 720;
this.graphics.SynchronizeWithVerticalRetrace = false;
this.IsMouseVisible = true;
this.IsFixedTimeStep = false;
this.TargetElapsedTime = TimeSpan.FromMilliseconds(5);
}
private void Swap<T>(ref T a, ref T b)
{
var t = a;
a = b;
b = t;
}
private void SwapBuffers()
{
this.Swap(ref this.newBuffer, ref this.oldBuffer);
}
protected override void Initialize()
{
this.Content.RootDirectory = "Content";
this.spriteBatch = new SpriteBatch(this.GraphicsDevice);
this.newBuffer = new RenderTarget2D(this.GraphicsDevice, this.GraphicsDevice.Viewport.Width, this.GraphicsDevice.Viewport.Height);
this.oldBuffer = new RenderTarget2D(this.GraphicsDevice, this.GraphicsDevice.Viewport.Width, this.GraphicsDevice.Viewport.Height);
for (int x = 0; x < spray.GetLength(0); x++)
{
for (int y = 0; y < spray.GetLength(1); y++)
{
spray[x, y] = new Vector2(x - spray.GetLength(0) / 2.00f, y - spray.GetLength(1) / 2.00f);
}
}
this.fpsCounter = new FPSCounterComponent(this);
this.Components.Add(this.fpsCounter);
this.Window.AllowUserResizing = true;
this.Window.ClientSizeChanged += Window_ClientSizeChanged;
base.Initialize();
}
private void SetupPhaseParameters()
{
var defaultTransformation = Matrix.CreateTranslation(-0.50f, -0.50f, 0.00f) * Matrix.CreateOrthographicOffCenter(0.00f, this.GraphicsDevice.Viewport.Width, this.GraphicsDevice.Viewport.Height, 0.00f, 0.00f, 1.00f);
this.startPhase.Parameters["MatrixTransform"].SetValue(defaultTransformation);
this.startPhase.Parameters["XUnit"].SetValue(new Vector2(1.00f / this.GraphicsDevice.Viewport.Width, 0.00f));
this.startPhase.Parameters["YUnit"].SetValue(new Vector2(0.00f, 1.00f / this.GraphicsDevice.Viewport.Height));
this.dustPhase.Parameters["MatrixTransform"].SetValue(defaultTransformation);
this.dustPhase.Parameters["XUnit"].SetValue(new Vector2(1.00f / this.GraphicsDevice.Viewport.Width, 0.00f));
this.dustPhase.Parameters["YUnit"].SetValue(new Vector2(0.00f, 1.00f / this.GraphicsDevice.Viewport.Height));
this.fluidPhase.Parameters["MatrixTransform"].SetValue(defaultTransformation);
this.fluidPhase.Parameters["XUnit"].SetValue(new Vector2(1.00f / this.GraphicsDevice.Viewport.Width, 0.00f));
this.fluidPhase.Parameters["YUnit"].SetValue(new Vector2(0.00f, 1.00f / this.GraphicsDevice.Viewport.Height));
this.movePhase.Parameters["MatrixTransform"].SetValue(defaultTransformation);
this.movePhase.Parameters["XUnit"].SetValue(new Vector2(1.00f / this.GraphicsDevice.Viewport.Width, 0.00f));
this.movePhase.Parameters["YUnit"].SetValue(new Vector2(0.00f, 1.00f / this.GraphicsDevice.Viewport.Height));
this.reactivePhase.Parameters["MatrixTransform"].SetValue(defaultTransformation);
this.reactivePhase.Parameters["XUnit"].SetValue(new Vector2(1.00f / this.GraphicsDevice.Viewport.Width, 0.00f));
this.reactivePhase.Parameters["YUnit"].SetValue(new Vector2(0.00f, 1.00f / this.GraphicsDevice.Viewport.Height));
this.colorPhase.Parameters["MatrixTransform"].SetValue(defaultTransformation);
this.colorPhase.Parameters["XUnit"].SetValue(new Vector2(1.00f / this.GraphicsDevice.Viewport.Width, 0.00f));
this.colorPhase.Parameters["YUnit"].SetValue(new Vector2(0.00f, 1.00f / this.GraphicsDevice.Viewport.Height));
this.newBuffer = new RenderTarget2D(this.GraphicsDevice, this.GraphicsDevice.Viewport.Width, this.GraphicsDevice.Viewport.Height);
this.oldBuffer = new RenderTarget2D(this.GraphicsDevice, this.GraphicsDevice.Viewport.Width, this.GraphicsDevice.Viewport.Height);
this.GraphicsDevice.SetRenderTarget(this.newBuffer);
this.GraphicsDevice.Clear(new Color(NONE, NONE, NONE, MOVE_NONE));
this.GraphicsDevice.SetRenderTarget(this.oldBuffer);
this.GraphicsDevice.Clear(new Color(NONE, NONE, NONE, MOVE_NONE));
}
private void Window_ClientSizeChanged(Object sender, EventArgs e)
{
this.SetupPhaseParameters();
}
protected override void LoadContent()
{
this.pixelTexture = new Texture2D(this.GraphicsDevice, 1, 1);
this.pixelTexture.SetData(new[] { Color.White });
this.startPhase = this.Content.Load<Effect>(@"StartPhase");
this.dustPhase = this.Content.Load<Effect>(@"DustPhase");
this.fluidPhase = this.Content.Load<Effect>(@"FluidPhase");
this.movePhase = this.Content.Load<Effect>(@"MovePhase");
this.reactivePhase = this.Content.Load<Effect>(@"ReactivePhase");
this.colorPhase = this.Content.Load<Effect>(@"ColorPhase");
this.SetupPhaseParameters();
}
protected override void Update(GameTime gameTime)
{
this.Window.Title = this.GraphicsDevice.Viewport.Bounds + " @ " + this.fpsCounter.FPS + " fps";
base.Update(gameTime);
}
private Single[] directions = new[] { MOVE_DOWN, MOVE_RIGHT, MOVE_LEFT };
protected override void Draw(GameTime gameTime)
{
// START
this.SwapBuffers();
this.GraphicsDevice.SetRenderTarget(this.newBuffer);
this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque, SamplerState.PointClamp, null, null, this.startPhase);
this.spriteBatch.Draw(this.oldBuffer, Vector2.Zero, Color.White);
this.spriteBatch.End();
for (var i = 0; i < 1; i++)
{
this.Swap(ref directions[1], ref directions[2]);
for (var n = 0; n < this.directions.Length; n++)
{
var direction = this.directions[n];
// DUST
this.SwapBuffers();
this.GraphicsDevice.SetRenderTarget(this.newBuffer);
this.dustPhase.Parameters["Direction"].SetValue(direction);
this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque, SamplerState.PointClamp, null, null, this.dustPhase);
this.spriteBatch.Draw(this.oldBuffer, Vector2.Zero, Color.White);
this.spriteBatch.End();
// FLUID
this.SwapBuffers();
this.GraphicsDevice.SetRenderTarget(this.newBuffer);
this.fluidPhase.Parameters["Direction"].SetValue(direction);
this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque, SamplerState.PointClamp, null, null, this.fluidPhase);
this.spriteBatch.Draw(this.oldBuffer, Vector2.Zero, Color.White);
this.spriteBatch.End();
// MOVEMENT
this.SwapBuffers();
this.GraphicsDevice.SetRenderTarget(this.newBuffer);
this.movePhase.Parameters["Direction"].SetValue(direction);
this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque, SamplerState.PointClamp, null, null, this.movePhase);
this.spriteBatch.Draw(this.oldBuffer, Vector2.Zero, Color.White);
this.spriteBatch.End();
}
}
// REACTIONS
this.SwapBuffers();
this.GraphicsDevice.SetRenderTarget(this.newBuffer);
this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque, SamplerState.PointClamp, null, null, this.reactivePhase);
this.spriteBatch.Draw(this.oldBuffer, Vector2.Zero, Color.White);
this.spriteBatch.End();
this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque, SamplerState.PointClamp, null, null);
if (this.IsActive)
{
if (Mouse.GetState().LeftButton == ButtonState.Pressed)
{
if (Keyboard.GetState().IsKeyDown(Keys.LeftShift))
{
var list = this.spray.Cast<Vector2>().ToList();
list.Shuffle();
foreach (var offset in list.Take(16))
{
this.spriteBatch.Draw(this.pixelTexture, new Rectangle(Mouse.GetState().X + (Int32)offset.X, Mouse.GetState().Y + (Int32)offset.Y, 1, 1), new Color(FLUID, WATER, NONE, NONE));
}
}
else if (Keyboard.GetState().IsKeyDown(Keys.LeftControl))
{
this.spriteBatch.Draw(this.pixelTexture, new Rectangle(Mouse.GetState().X - 2, Mouse.GetState().Y - 2, 5, 5), new Color(WALL, CONCRETE, NONE, NONE));
}
else
{
var list = this.spray.Cast<Vector2>().ToList();
list.Shuffle();
foreach (var offset in list.Take(16))
{
this.spriteBatch.Draw(this.pixelTexture, new Rectangle(Mouse.GetState().X + (Int32)offset.X, Mouse.GetState().Y + (Int32)offset.Y, 1, 1), new Color(DUST, DIRT, NONE, NONE));
}
}
}
if (Mouse.GetState().RightButton == ButtonState.Pressed)
{
if (Keyboard.GetState().IsKeyDown(Keys.LeftShift))
{
this.spriteBatch.Draw(this.pixelTexture, new Rectangle(Mouse.GetState().X - 12, Mouse.GetState().Y - 12, 25, 25), new Color(NONE, NONE, NONE, NONE));
}
else if (Keyboard.GetState().IsKeyDown(Keys.LeftControl))
{
this.spriteBatch.Draw(this.pixelTexture, new Rectangle(Mouse.GetState().X - 2, Mouse.GetState().Y - 2, 5, 5), new Color(WALL, PLANT, NONE, NONE));
}
else
{
var list = this.spray.Cast<Vector2>().ToList();
list.Shuffle();
foreach (var offset in list.Take(16))
{
this.spriteBatch.Draw(this.pixelTexture, new Rectangle(Mouse.GetState().X + (Int32)offset.X, Mouse.GetState().Y + (Int32)offset.Y, 1, 1), new Color(NONE, FIRE, NONE, NONE));
}
}
}
}
this.spriteBatch.End();
this.GraphicsDevice.SetRenderTarget(null);
this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque, SamplerState.PointClamp, null, null, this.colorPhase);
this.spriteBatch.Draw(this.newBuffer, Vector2.Zero, Color.White);
this.spriteBatch.End();
base.Draw(gameTime);
}
}
}
| |
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace Pidgin
{
/// <summary>
/// A version of <see cref="List{T}"/> which uses an array pool.
///
/// For efficiency, <see cref="PooledList{T}"/> is implemented as a mutable struct.
/// It's intended to be passed by reference.
/// </summary>
/// <typeparam name="T">The type of elements of the list</typeparam>
public struct PooledList<T> : IDisposable, IList<T>
{
private static readonly bool _needsClear = RuntimeHelpers.IsReferenceOrContainsReferences<T>();
private const int InitialCapacity = 16;
private ArrayPool<T> _arrayPool;
private T[]? _items;
private int _count;
/// <summary>The number of elements in the list</summary>
/// <returns>The number of elements in the list</returns>
public int Count
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return _count;
}
}
/// <summary>Returns false</summary>
/// <returns>False</returns>
public bool IsReadOnly => false;
/// <summary>Creates a <see cref="PooledList{T}"/> which uses the supplied <see cref="ArrayPool{T}"/>.</summary>
public PooledList(ArrayPool<T> arrayPool)
{
_arrayPool = arrayPool;
_items = null;
_count = 0;
}
/// <summary>Gets or sets the element at index <paramref name="index"/>.</summary>
/// <param name="index">The index</param>
/// <returns>The element at index <paramref name="index"/>.</returns>
public T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (index >= _count)
{
ThrowArgumentOutOfRangeException(nameof(index));
}
return _items![index];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
if (index >= _count)
{
ThrowArgumentOutOfRangeException(nameof(index));
}
_items![index] = value;
}
}
/// <summary>Adds an item to the end of the list.</summary>
/// <param name="item">The item to add</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(T item)
{
GrowIfNecessary(1);
_items![_count] = item;
_count++;
}
/// <summary>Adds a collection of items to the end of the list.</summary>
/// <param name="items">The items to add</param>
public void AddRange(ImmutableArray<T> items)
{
GrowIfNecessary(items.Length);
items.CopyTo(_items!, _count);
_count += items.Length;
}
/// <summary>Adds a collection of items to the end of the list.</summary>
/// <param name="items">The items to add</param>
public void AddRange(ReadOnlySpan<T> items)
{
GrowIfNecessary(items.Length);
items.CopyTo(_items.AsSpan().Slice(_count));
_count += items.Length;
}
/// <summary>Adds a collection of items to the end of the list.</summary>
/// <param name="items">The items to add</param>
public void AddRange(ICollection<T> items)
{
GrowIfNecessary(items.Count);
items.CopyTo(_items, _count);
_count += items.Count;
}
/// <summary>Adds a collection of items to the end of the list.</summary>
/// <param name="items">The items to add</param>
public void AddRange(IEnumerable<T> items)
{
switch (items)
{
case T[] a:
AddRange(a.AsSpan());
return;
case ImmutableArray<T> i:
AddRange(i);
return;
case ICollection<T> c:
AddRange(c);
return;
default:
foreach (var item in items)
{
Add(item);
}
return;
}
}
/// <summary>Removes and returns an item from the end of the list.</summary>
/// <exception cref="InvalidOperationException">The list is empty.</exception>
/// <returns>The last item in the list.</returns>
public T Pop()
{
if (_count == 0)
{
ThrowInvalidOperationException();
}
_count--;
return _items![_count];
}
/// <summary>Returns a <see cref="Span{T}"/> view of the list.</summary>
/// <returns>A <see cref="Span{T}"/> view of the list.</returns>
public Span<T> AsSpan() => _items.AsSpan().Slice(0, _count);
/// <summary>
/// Searches for <paramref name="item"/> in the list and returns its index.
/// Returns <c>-1</c> if the <paramref name="item"/> is missing.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>The index of <paramref name="item"/>, or <c>-1</c> if it is missing.</returns>
public int IndexOf(T item)
{
if (_count == 0)
{
return -1;
}
return Array.IndexOf(_items!, item, 0, _count);
}
/// <summary>
/// Inserts <paramref name="item"/> into the list at <paramref name="index"/>.
/// </summary>
/// <param name="index">The index at which to insert the item.</param>
/// <param name="item">The item to insert.</param>
/// <exception cref="ArgumentOutOfRangeException">The index is outside the bounds of the list.</exception>
public void Insert(int index, T item)
{
if (index < 0 || index > _count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
GrowIfNecessary(1);
Array.Copy(_items, index, _items, index + 1, _count - index);
_items![index] = item;
_count++;
}
/// <summary>
/// Removes the item at <paramref name="index"/>.
/// </summary>
/// <param name="index">The index from which to remove the item.</param>
/// <exception cref="ArgumentOutOfRangeException">The index is outside the bounds of the list.</exception>
public void RemoveAt(int index)
{
if (index < 0 || index >= _count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
_count--;
Array.Copy(_items!, index + 1, _items!, index, _count - index);
}
/// <summary>
/// Searches for <paramref name="item"/> in the list.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>True if the item is in the list, false if it is not.</returns>
public bool Contains(T item)
=> Array.IndexOf(_items!, item, 0, _count) >= 0;
/// <summary>
/// Copies the list into an array.
/// </summary>
/// <param name="array">The destination array to copy the list into.</param>
/// <param name="arrayIndex">The starting index in the destination array.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> was null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="arrayIndex"/> was less than 0.</exception>
/// <exception cref="ArgumentException">There was not enough space in the <paramref name="array"/>.</exception>
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
}
if (_count > array.Length - arrayIndex)
{
throw new ArgumentException();
}
Array.Copy(_items!, 0, array, arrayIndex, _count);
}
/// <summary>
/// Searches for <paramref name="item"/> in the list and removes it.
/// Returns <c>false</c> if the <paramref name="item"/> is missing.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>True if the item was removed, false if it was missing.</returns>
public bool Remove(T item)
{
var ix = IndexOf(item);
if (ix < 0)
{
return false;
}
RemoveAt(ix);
return true;
}
/// <summary>
/// Empties the list.
/// </summary>
public void Clear()
{
_count = 0;
}
/// <summary>
/// Returns any allocated memory to the pool.
/// </summary>
public void Dispose()
{
if (_items != null)
{
_arrayPool.Return(_items, _needsClear);
}
_items = null;
_count = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MemberNotNull(nameof(_arrayPool), nameof(_items))]
private void GrowIfNecessary(int additionalSpace)
{
if (_arrayPool == null)
{
_arrayPool = ArrayPool<T>.Shared;
}
if (_items == null)
{
Init(additionalSpace);
}
else if (_count + additionalSpace >= _items.Length)
{
Grow(additionalSpace);
}
}
[MemberNotNull(nameof(_items))]
private void Init(int space)
{
_items = _arrayPool.Rent(Math.Max(InitialCapacity, space));
}
private void Grow(int additionalSpace)
{
var newBuffer = _arrayPool.Rent(Math.Max(_items!.Length * 2, _count + additionalSpace));
Array.Copy(_items, newBuffer, _count);
_arrayPool.Return(_items, _needsClear);
_items = newBuffer;
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
for (var i = 0; i < _count; i++)
{
yield return _items![i];
}
}
IEnumerator IEnumerable.GetEnumerator()
=> ((IEnumerable<T>)this).GetEnumerator();
[DoesNotReturn]
private static void ThrowArgumentOutOfRangeException(string paramName)
{
throw CreateArgumentOutOfRangeException(paramName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static Exception CreateArgumentOutOfRangeException(string paramName)
=> new ArgumentOutOfRangeException(paramName);
[DoesNotReturn]
private static void ThrowInvalidOperationException()
{
throw CreateInvalidOperationException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static Exception CreateInvalidOperationException()
=> new InvalidOperationException();
}
}
| |
/*
* Copyright (c) 2015 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using TeamUtility.IO.SaveUtility;
namespace TeamUtility.IO
{
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class MiniJson
{
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json)
{
return string.IsNullOrEmpty(json) ? null : Parser.Parse(json);
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj, bool prettyPrint)
{
return Serializer.Serialize(obj, prettyPrint);
}
private sealed class Parser : IDisposable
{
private enum TOKEN
{
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
private const string WORD_BREAK = "{}[],:\"";
private StringReader json;
#region [Properties]
private char PeekChar
{
get
{
return System.Convert.ToChar(json.Peek());
}
}
private char NextChar
{
get
{
return System.Convert.ToChar(json.Read());
}
}
private string NextWord
{
get
{
StringBuilder word = new StringBuilder();
while(!IsWordBreak(PeekChar))
{
word.Append(NextChar);
if(json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
private TOKEN NextToken
{
get
{
EatWhitespace();
if(json.Peek() == -1) {
return TOKEN.NONE;
}
switch(PeekChar)
{
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
switch(NextWord)
{
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
#endregion
#region [Init]
public Parser(string jsonString)
{
json = new StringReader(jsonString);
}
public static object Parse(string jsonString)
{
using(var instance = new Parser(jsonString))
{
return instance.ParseValue();
}
}
#endregion
public void Dispose()
{
json.Dispose();
json = null;
}
private Dictionary<string, object> ParseObject()
{
Dictionary<string, object> table = new Dictionary<string, object>();
json.Read(); // ditch opening bracket
while(true)
{
switch(NextToken)
{
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
string name = ParseString();
if(name == null) {
return null;
}
if(NextToken != TOKEN.COLON) {
return null;
}
json.Read(); // ditch the colon
table[name] = ParseValue();
break;
}
}
}
private List<object> ParseArray()
{
List<object> array = new List<object>();
json.Read(); // ditch opening bracket
bool parsing = true;
while(parsing)
{
TOKEN nextToken = NextToken;
switch(nextToken)
{
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
private object ParseValue()
{
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
private object ParseByToken(TOKEN token)
{
switch(token)
{
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
private string ParseString()
{
StringBuilder builder = new StringBuilder();
char c;
bool parsing = true;
json.Read (); // ditch opening quote
while (parsing)
{
if(json.Peek() == -1)
{
parsing = false;
break;
}
c = NextChar;
switch(c)
{
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1)
{
parsing = false;
break;
}
c = NextChar;
switch(c)
{
case '"':
case '\\':
case '/':
builder.Append(c);
break;
case 'b':
builder.Append('\b');
break;
case 'f':
builder.Append('\f');
break;
case 'n':
builder.Append('\n');
break;
case 'r':
builder.Append('\r');
break;
case 't':
builder.Append('\t');
break;
case 'u':
var hex = new char[4];
for (int i=0; i< 4; i++) {
hex [i] = NextChar;
}
builder.Append((char)System.Convert.ToInt32(new string(hex), 16));
break;
}
break;
default:
builder.Append(c);
break;
}
}
return builder.ToString();
}
private object ParseNumber()
{
string number = NextWord;
if (number.IndexOf('.') == -1)
{
long parsedInt;
Int64.TryParse(number, out parsedInt);
return parsedInt;
}
else
{
double parsedDouble;
Double.TryParse(number, out parsedDouble);
return parsedDouble;
}
}
private void EatWhitespace()
{
while(Char.IsWhiteSpace(PeekChar))
{
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
private bool IsWordBreak(char c)
{
return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1;
}
}
private sealed class Serializer
{
private StringBuilder builder;
private int depth;
private bool prettyPrint;
public string Json
{
get
{
return builder.ToString();
}
}
#region [Init]
public Serializer(bool prettyPrint)
{
depth = 0;
builder = new StringBuilder();
this.prettyPrint = prettyPrint;
}
public static string Serialize(object obj, bool prettyPrint)
{
Serializer serializer = new Serializer(prettyPrint);
serializer.SerializeValue(obj);
return serializer.Json;
}
#endregion
private void SerializeValue(object value)
{
if(value == null)
{
builder.Append("null");
}
else if(value is char)
{
SerializeString(new string((char)value, 1));
}
else if(value is string)
{
SerializeString((string)value);
}
else if(value is bool)
{
builder.Append((bool)value ? "true" : "false");
}
else if(value is IList<object>)
{
SerializeArray((IList<object>)value);
}
else if(value is IDictionary<string, object>)
{
SerializeObject((IDictionary<string, object>)value);
}
else
{
SerializeOther(value);
}
}
private void SerializeObject(IDictionary<string, object> obj)
{
bool first = true;
if(prettyPrint)
{
if(depth > 0)
{
WriteIndentation();
}
depth++;
}
builder.Append('{');
if(prettyPrint)
{
WriteIndentation();
}
foreach(KeyValuePair<string, object> pair in obj)
{
if(!first)
{
builder.Append(", ");
if(prettyPrint)
{
WriteIndentation();
}
}
SerializeString(pair.Key);
builder.Append(": ");
SerializeValue(pair.Value);
first = false;
}
if(prettyPrint)
{
depth--;
WriteIndentation();
}
builder.Append ('}');
}
private void SerializeArray(IList<object> anArray)
{
bool first = true;
if(prettyPrint)
{
depth++;
}
builder.Append ('[');
if(prettyPrint)
{
WriteIndentation();
}
foreach (object obj in anArray)
{
if (!first)
{
builder.Append (", ");
if(prettyPrint)
{
WriteIndentation();
}
}
SerializeValue(obj);
first = false;
}
if(prettyPrint)
{
depth--;
WriteIndentation();
}
builder.Append (']');
}
private void SerializeString(string str)
{
builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach(var c in charArray)
{
switch(c)
{
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = System.Convert.ToInt32(c);
if((codepoint >= 32) && (codepoint <= 126))
{
builder.Append(c);
}
else
{
builder.Append("\\u");
builder.Append(codepoint.ToString("x4"));
}
break;
}
}
builder.Append('\"');
}
private void SerializeOther(object value)
{
// NOTE: decimals lose precision during serialization.
// They always have, I'm just letting you know.
// Previously floats and doubles lost precision too.
if(value is float)
{
builder.Append(((float)value).ToString ("R"));
}
else if(value is int || value is uint || value is long || value is sbyte ||
value is byte || value is short || value is ushort || value is ulong)
{
builder.Append(value);
}
else if(value is double || value is decimal)
{
builder.Append(System.Convert.ToDouble(value).ToString("R"));
}
else
{
SerializeString(value.ToString());
}
}
private void WriteIndentation()
{
builder.Append('\n');
for(int i=0; i< depth; i++)
{
builder.Append('\t');
}
}
}
}
}
| |
namespace Mapbox.Unity.MeshGeneration.Modifiers
{
using System.Collections.Generic;
using UnityEngine;
using Mapbox.Unity.MeshGeneration.Data;
[CreateAssetMenu(menuName = "Mapbox/Modifiers/Smooth Height for Buildings Modifier")]
public class ChamferHeightModifier : MeshModifier
{
[SerializeField]
[Tooltip("Flatten top polygons to prevent unwanted slanted roofs because of the bumpy terrain")]
private bool _flatTops;
[SerializeField]
[Tooltip("Fixed height value for ForceHeight option")]
private float _height;
[SerializeField]
[Tooltip("Fix all features to certain height, suggested to be used for pushing roads above terrain level to prevent z-fighting.")]
private bool _forceHeight;
[SerializeField]
[Range(0.1f,2)]
[Tooltip("Chamfer width value")]
private float _offset = 0.2f;
public override ModifierType Type { get { return ModifierType.Preprocess; } }
public override void Run(VectorFeatureUnity feature, MeshData md, UnityTile tile = null)
{
if (md.Vertices.Count == 0 || feature == null || feature.Points.Count < 1)
return;
var minHeight = 0f;
float hf = _height;
if (!_forceHeight)
{
GetHeightData(feature, ref minHeight, ref hf);
}
var max = md.Vertices[0].y;
var min = md.Vertices[0].y;
if (_flatTops)
{
FlattenTops(md, minHeight, ref hf, ref max, ref min);
}
else
{
for (int i = 0; i < md.Vertices.Count; i++)
{
md.Vertices[i] = new Vector3(md.Vertices[i].x, md.Vertices[i].y + minHeight + hf, md.Vertices[i].z);
}
}
var originalVertexCount = md.Vertices.Count;
Chamfer(feature, md, tile);
Sides(feature, md, hf, originalVertexCount);
}
private void Sides(VectorFeatureUnity feature, MeshData meshData, float hf, int originalVertexCount)
{
float d = 0f;
Vector3 v1;
Vector3 v2 = Vector3.zero;
int ind = 0;
var wallTri = new List<int>();
var wallUv = new List<Vector2>();
meshData.Vertices.Add(new Vector3(meshData.Vertices[originalVertexCount - 1].x, meshData.Vertices[originalVertexCount - 1].y - hf, meshData.Vertices[originalVertexCount - 1].z));
wallUv.Add(new Vector2(0, -hf));
meshData.Normals.Add(meshData.Normals[originalVertexCount - 1]);
for (int i = 0; i < meshData.Edges.Count; i += 2)
{
v1 = meshData.Vertices[meshData.Edges[i]];
v2 = meshData.Vertices[meshData.Edges[i + 1]];
ind = meshData.Vertices.Count;
meshData.Vertices.Add(v1);
meshData.Vertices.Add(v2);
meshData.Vertices.Add(new Vector3(v1.x, v1.y - hf, v1.z));
meshData.Vertices.Add(new Vector3(v2.x, v2.y - hf, v2.z));
meshData.Normals.Add(meshData.Normals[meshData.Edges[i]]);
meshData.Normals.Add(meshData.Normals[meshData.Edges[i + 1]]);
meshData.Normals.Add(meshData.Normals[meshData.Edges[i]]);
meshData.Normals.Add(meshData.Normals[meshData.Edges[i + 1]]);
d = (v2 - v1).magnitude;
wallUv.Add(new Vector2(0, 0));
wallUv.Add(new Vector2(d, 0));
wallUv.Add(new Vector2(0, -hf));
wallUv.Add(new Vector2(d, -hf));
wallTri.Add(ind);
wallTri.Add(ind + 1);
wallTri.Add(ind + 2);
wallTri.Add(ind + 1);
wallTri.Add(ind + 3);
wallTri.Add(ind + 2);
}
meshData.Triangles.Add(wallTri);
meshData.UV[0].AddRange(wallUv);
}
private static void FlattenTops(MeshData meshData, float minHeight, ref float hf, ref float max, ref float min)
{
for (int i = 0; i < meshData.Vertices.Count; i++)
{
if (meshData.Vertices[i].y > max)
max = meshData.Vertices[i].y;
else if (meshData.Vertices[i].y < min)
min = meshData.Vertices[i].y;
}
for (int i = 0; i < meshData.Vertices.Count; i++)
{
meshData.Vertices[i] = new Vector3(meshData.Vertices[i].x, max + minHeight + hf, meshData.Vertices[i].z);
}
hf += max - min;
}
private static void GetHeightData(VectorFeatureUnity feature, ref float minHeight, ref float hf)
{
if (feature.Properties.ContainsKey("height"))
{
if (float.TryParse(feature.Properties["height"].ToString(), out hf))
{
if (feature.Properties.ContainsKey("min_height"))
{
minHeight = float.Parse(feature.Properties["min_height"].ToString());
hf -= minHeight;
}
}
}
if (feature.Properties.ContainsKey("ele"))
{
if (float.TryParse(feature.Properties["ele"].ToString(), out hf))
{
}
}
}
public void Chamfer(VectorFeatureUnity feature, MeshData md, UnityTile tile = null)
{
if (md.Vertices.Count == 0 || feature.Points.Count < 1)
return;
List<Vector3> newVertices = new List<Vector3>();
List<Vector2> newUV = new List<Vector2>();
md.Normals.Clear();
md.Edges.Clear();
for (int t = 0; t < md.Triangles[0].Count; t++)
{
md.Triangles[0][t] *= 3;
}
var next = 0; var current = 0; var prev = 0;
Vector3 v1, v2, n1, n2, pij1, pij2, pjk1, pjk2;
Vector3 poi, close1, close2;
var start = 0;
for (int i = 0; i < feature.Points.Count; i++)
{
var count = feature.Points[i].Count;
var cst = newVertices.Count;
for (int j = 0; j < count; j++)
{
if (j == count - 1)
{
newVertices.Add(newVertices[cst]);
newVertices.Add(newVertices[cst + 1]);
newVertices.Add(newVertices[cst + 2]);
newUV.Add(newUV[cst]);
newUV.Add(newUV[cst + 1]);
newUV.Add(newUV[cst + 2]);
md.Normals.Add(md.Normals[cst]);
md.Normals.Add(md.Normals[cst + 1]);
md.Normals.Add(md.Normals[cst + 2]);
continue;
}
current = start + j;
if (j > 0)
next = start + j - 1;
else
next = start + j - 1 + count - 1; //another -1 as last item equals first
prev = start + j + 1;
v1 = new Vector3(
md.Vertices[current].x - md.Vertices[next].x, 0,
md.Vertices[current].z - md.Vertices[next].z);
v1.Normalize();
v1 *= -_offset;
n1 = new Vector3(-v1.z, 0, v1.x);
pij1 = new Vector3(
(float)(md.Vertices[next].x + n1.x), 0,
(float)(md.Vertices[next].z + n1.z));
pij2 = new Vector3(
(float)(md.Vertices[current].x + n1.x), 0,
(float)(md.Vertices[current].z + n1.z));
v2 = new Vector3(
md.Vertices[prev].x - md.Vertices[current].x, 0,
md.Vertices[prev].z - md.Vertices[current].z);
v2.Normalize();
v2 *= -_offset;
n2 = new Vector3(-v2.z, 0, v2.x);
pjk1 = new Vector3(
(float)(md.Vertices[current].x + n2.x), 0,
(float)(md.Vertices[current].z + n2.z));
pjk2 = new Vector3(
(float)(md.Vertices[prev].x + n2.x), 0,
(float)(md.Vertices[prev].z + n2.z));
// See where the shifted lines ij and jk intersect.
bool lines_intersect, segments_intersect;
FindIntersection(pij1, pij2, pjk1, pjk2,
out lines_intersect, out segments_intersect,
out poi, out close1, out close2);
var d = Vector3.Distance(poi, pij2);
if (d > 10 * _offset)
{
poi = new Vector3((md.Vertices[current].x + (poi - (-v1 - v2)).normalized.x), 0,
(md.Vertices[current].z + (poi - (-v1 - v2)).normalized.z));
}
newVertices.Add(new Vector3(poi.x, poi.y + _offset + md.Vertices[current].y, poi.z));
newVertices.Add(md.Vertices[current] + v1);
newVertices.Add(md.Vertices[current] - v2);
md.Normals.Add(Constants.Math.Vector3Up);
md.Normals.Add(-n1);
md.Normals.Add(-n2);
newUV.Add(md.UV[0][current]);
newUV.Add(md.UV[0][current]);
newUV.Add(md.UV[0][current]);
md.Triangles[0].Add(3 * current);
md.Triangles[0].Add(3 * current + 1);
md.Triangles[0].Add(3 * current + 2);
md.Edges.Add(3 * current + 2);
md.Edges.Add(3 * current + 1);
md.Triangles[0].Add(3 * prev);
md.Triangles[0].Add(3 * current + 2);
md.Triangles[0].Add(3 * prev + 1);
md.Triangles[0].Add(3 * current);
md.Triangles[0].Add(3 * current + 2);
md.Triangles[0].Add(3 * prev);
//Debug.Log(i + " - " + j + " - " + k);
md.Edges.Add(3 * prev + 1);
md.Edges.Add(3 * current + 2);
}
start += count;
}
md.Vertices = newVertices;
md.UV[0] = newUV;
}
private List<Vector3> GetEnlargedPolygon(List<Vector3> old_points, float offset)
{
List<Vector3> enlarged_points = new List<Vector3>();
int num_points = old_points.Count;
for (int j = 0; j < num_points; j++)
{
// Find the new location for point j.
// Find the points before and after j.
int i = (j - 1);
if (i < 0) i += num_points;
int k = (j + 1) % num_points;
// Move the points by the offset.
Vector3 v1 = new Vector3(
old_points[j].x - old_points[i].x, 0,
old_points[j].z - old_points[i].z);
v1.Normalize();
v1 *= offset;
Vector3 n1 = new Vector3(-v1.z, 0, v1.x);
Vector3 pij1 = new Vector3(
(float)(old_points[i].x + n1.x), 0,
(float)(old_points[i].z + n1.z));
Vector3 pij2 = new Vector3(
(float)(old_points[j].x + n1.x), 0,
(float)(old_points[j].z + n1.z));
Vector3 v2 = new Vector3(
old_points[k].x - old_points[j].x, 0,
old_points[k].z - old_points[j].z);
v2.Normalize();
v2 *= offset;
Vector3 n2 = new Vector3(-v2.z, 0, v2.x);
Vector3 pjk1 = new Vector3(
(float)(old_points[j].x + n2.x), 0,
(float)(old_points[j].z + n2.z));
Vector3 pjk2 = new Vector3(
(float)(old_points[k].x + n2.x), 0,
(float)(old_points[k].z + n2.z));
// See where the shifted lines ij and jk intersect.
bool lines_intersect, segments_intersect;
Vector3 poi, close1, close2;
FindIntersection(pij1, pij2, pjk1, pjk2,
out lines_intersect, out segments_intersect,
out poi, out close1, out close2);
Debug.Assert(lines_intersect,
"Edges " + i + "-->" + j + " and " +
j + "-->" + k + " are parallel");
enlarged_points.Add(poi);
}
return enlarged_points;
}
// Find the point of intersection between
// the lines p1 --> p2 and p3 --> p4.
private void FindIntersection(
Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4,
out bool lines_intersect, out bool segments_intersect,
out Vector3 intersection,
out Vector3 close_p1, out Vector3 close_p2)
{
// Get the segments' parameters.
float dx12 = p2.x - p1.x;
float dy12 = p2.z - p1.z;
float dx34 = p4.x - p3.x;
float dy34 = p4.z - p3.z;
// Solve for t1 and t2
float denominator = (dy12 * dx34 - dx12 * dy34);
float t1 =
((p1.x - p3.x) * dy34 + (p3.z - p1.z) * dx34)
/ denominator;
if (float.IsInfinity(t1))
{
// The lines are parallel (or close enough to it).
lines_intersect = false;
segments_intersect = false;
intersection = new Vector3(float.NaN, 0, float.NaN);
close_p1 = new Vector3(float.NaN, 0, float.NaN);
close_p2 = new Vector3(float.NaN, 0, float.NaN);
return;
}
lines_intersect = true;
float t2 =
((p3.x - p1.x) * dy12 + (p1.z - p3.z) * dx12)
/ -denominator;
// Find the point of intersection.
intersection = new Vector3(p1.x + dx12 * t1, 0, p1.z + dy12 * t1);
// The segments intersect if t1 and t2 are between 0 and 1.
segments_intersect =
((t1 >= 0) && (t1 <= 1) &&
(t2 >= 0) && (t2 <= 1));
// Find the closest points on the segments.
if (t1 < 0)
{
t1 = 0;
}
else if (t1 > 1)
{
t1 = 1;
}
if (t2 < 0)
{
t2 = 0;
}
else if (t2 > 1)
{
t2 = 1;
}
close_p1 = new Vector3(p1.x + dx12 * t1, 0, p1.z + dy12 * t1);
close_p2 = new Vector3(p3.x + dx34 * t2, 0, p3.z + dy34 * t2);
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Security.Cryptography
{
public abstract partial class Aes : System.Security.Cryptography.SymmetricAlgorithm
{
protected Aes() { }
public static new System.Security.Cryptography.Aes Create() { throw null; }
public static new System.Security.Cryptography.Aes Create(string algorithmName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class AesManaged : System.Security.Cryptography.Aes
{
public AesManaged() { }
public override int FeedbackSize { get { throw null; } set { } }
public override int BlockSize { get { throw null; } set { } }
public override byte[] IV { get { throw null; } set { } }
public override byte[] Key { get { throw null; } set { } }
public override int KeySize { get { throw null; } set { } }
public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } }
public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
public override void GenerateIV() { }
public override void GenerateKey() { }
}
public abstract partial class AsymmetricKeyExchangeDeformatter
{
protected AsymmetricKeyExchangeDeformatter() { }
public abstract string Parameters { get; set; }
public abstract byte[] DecryptKeyExchange(byte[] rgb);
public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key);
}
public abstract partial class AsymmetricKeyExchangeFormatter
{
protected AsymmetricKeyExchangeFormatter() { }
public abstract string Parameters { get; }
public abstract byte[] CreateKeyExchange(byte[] data);
public abstract byte[] CreateKeyExchange(byte[] data, System.Type symAlgType);
public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key);
}
public abstract partial class AsymmetricSignatureDeformatter
{
protected AsymmetricSignatureDeformatter() { }
public abstract void SetHashAlgorithm(string strName);
public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key);
public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature);
public virtual bool VerifySignature(System.Security.Cryptography.HashAlgorithm hash, byte[] rgbSignature) { throw null; }
}
public abstract partial class AsymmetricSignatureFormatter
{
protected AsymmetricSignatureFormatter() { }
public abstract byte[] CreateSignature(byte[] rgbHash);
public virtual byte[] CreateSignature(System.Security.Cryptography.HashAlgorithm hash) { throw null; }
public abstract void SetHashAlgorithm(string strName);
public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key);
}
public abstract partial class DeriveBytes : System.IDisposable
{
protected DeriveBytes() { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract byte[] GetBytes(int cb);
public abstract void Reset();
}
public partial class CryptoConfig
{
public CryptoConfig() { }
public static bool AllowOnlyFipsAlgorithms { get { throw null; } }
public static void AddAlgorithm(System.Type algorithm, params string[] names) { }
public static void AddOID(string oid, params string[] names) { }
public static object CreateFromName(string name) { throw null; }
public static object CreateFromName(string name, params object[] args) { throw null; }
public static byte[] EncodeOID(string str) { throw null; }
public static string MapNameToOID(string name) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public abstract partial class DES : System.Security.Cryptography.SymmetricAlgorithm
{
protected DES() { }
public override byte[] Key { get { throw null; } set { } }
public static new System.Security.Cryptography.DES Create() { throw null; }
public static new System.Security.Cryptography.DES Create(string algName) { throw null; }
public static bool IsSemiWeakKey(byte[] rgbKey) { throw null; }
public static bool IsWeakKey(byte[] rgbKey) { throw null; }
}
public abstract partial class DSA : System.Security.Cryptography.AsymmetricAlgorithm
{
protected DSA() { }
public static new System.Security.Cryptography.DSA Create() { throw null; }
public static System.Security.Cryptography.DSA Create(int keySizeInBits) { throw null; }
public static new System.Security.Cryptography.DSA Create(string algName) { throw null; }
public static System.Security.Cryptography.DSA Create(System.Security.Cryptography.DSAParameters parameters) { throw null; }
public abstract byte[] CreateSignature(byte[] rgbHash);
public abstract System.Security.Cryptography.DSAParameters ExportParameters(bool includePrivateParameters);
public override void FromXmlString(string xmlString) { }
protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public abstract void ImportParameters(System.Security.Cryptography.DSAParameters parameters);
public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public override string ToXmlString(bool includePrivateParameters) { throw null; }
public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature);
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct DSAParameters
{
public int Counter;
public byte[] G;
public byte[] J;
public byte[] P;
public byte[] Q;
public byte[] Seed;
public byte[] X;
public byte[] Y;
}
public partial class DSASignatureDeformatter : System.Security.Cryptography.AsymmetricSignatureDeformatter
{
public DSASignatureDeformatter() { }
public DSASignatureDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override void SetHashAlgorithm(string strName) { }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; }
}
public partial class DSASignatureFormatter : System.Security.Cryptography.AsymmetricSignatureFormatter
{
public DSASignatureFormatter() { }
public DSASignatureFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override byte[] CreateSignature(byte[] rgbHash) { throw null; }
public override void SetHashAlgorithm(string strName) { }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ECCurve
{
public byte[] A;
public byte[] B;
public byte[] Cofactor;
public System.Security.Cryptography.ECCurve.ECCurveType CurveType;
public System.Security.Cryptography.ECPoint G;
public System.Nullable<System.Security.Cryptography.HashAlgorithmName> Hash;
public byte[] Order;
public byte[] Polynomial;
public byte[] Prime;
public byte[] Seed;
public bool IsCharacteristic2 { get { throw null; } }
public bool IsExplicit { get { throw null; } }
public bool IsNamed { get { throw null; } }
public bool IsPrime { get { throw null; } }
public System.Security.Cryptography.Oid Oid { get { throw null; } }
public static System.Security.Cryptography.ECCurve CreateFromFriendlyName(string oidFriendlyName) { throw null; }
public static System.Security.Cryptography.ECCurve CreateFromOid(System.Security.Cryptography.Oid curveOid) { throw null; }
public static System.Security.Cryptography.ECCurve CreateFromValue(string oidValue) { throw null; }
public void Validate() { }
public enum ECCurveType
{
Characteristic2 = 4,
Implicit = 0,
Named = 5,
PrimeMontgomery = 3,
PrimeShortWeierstrass = 1,
PrimeTwistedEdwards = 2,
}
public static partial class NamedCurves
{
public static System.Security.Cryptography.ECCurve brainpoolP160r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP160t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP192r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP192t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP224r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP224t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP256r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP256t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP320r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP320t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP384r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP384t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP512r1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve brainpoolP512t1 { get { throw null; } }
public static System.Security.Cryptography.ECCurve nistP256 { get { throw null; } }
public static System.Security.Cryptography.ECCurve nistP384 { get { throw null; } }
public static System.Security.Cryptography.ECCurve nistP521 { get { throw null; } }
}
}
public abstract partial class ECDiffieHellmanPublicKey : System.IDisposable
{
protected ECDiffieHellmanPublicKey(byte[] keyBlob) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public virtual byte[] ToByteArray() { throw null; }
public virtual string ToXmlString() { throw null; }
}
public abstract partial class ECDsa : System.Security.Cryptography.AsymmetricAlgorithm
{
protected ECDsa() { }
public override string KeyExchangeAlgorithm { get { throw null; } }
public override string SignatureAlgorithm { get { throw null; } }
public static new System.Security.Cryptography.ECDsa Create() { throw null; }
public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECCurve curve) { throw null; }
public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECParameters parameters) { throw null; }
public static new System.Security.Cryptography.ECDsa Create(string algorithm) { throw null; }
public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; }
public virtual System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; }
public override void FromXmlString(string xmlString) { }
public virtual void GenerateKey(System.Security.Cryptography.ECCurve curve) { }
protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual void ImportParameters(System.Security.Cryptography.ECParameters parameters) { }
public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public abstract byte[] SignHash(byte[] hash);
public override string ToXmlString(bool includePrivateParameters) { throw null; }
public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public abstract bool VerifyHash(byte[] hash, byte[] signature);
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ECParameters
{
public System.Security.Cryptography.ECCurve Curve;
public byte[] D;
public System.Security.Cryptography.ECPoint Q;
public void Validate() { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct ECPoint
{
public byte[] X;
public byte[] Y;
}
public partial class HMACMD5 : System.Security.Cryptography.HMAC
{
public HMACMD5() { }
public HMACMD5(byte[] key) { }
public override byte[] Key { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
}
public partial class HMACSHA1 : System.Security.Cryptography.HMAC
{
public HMACSHA1() { }
public HMACSHA1(byte[] key) { }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public HMACSHA1(byte[] key, bool useManagedSha1) { }
public override byte[] Key { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
}
public partial class HMACSHA256 : System.Security.Cryptography.HMAC
{
public HMACSHA256() { }
public HMACSHA256(byte[] key) { }
public override byte[] Key { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
}
public partial class HMACSHA384 : System.Security.Cryptography.HMAC
{
public HMACSHA384() { }
public HMACSHA384(byte[] key) { }
public bool ProduceLegacyHmacValues { get; set; }
public override byte[] Key { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
}
public partial class HMACSHA512 : System.Security.Cryptography.HMAC
{
public HMACSHA512() { }
public HMACSHA512(byte[] key) { }
public bool ProduceLegacyHmacValues { get; set; }
public override byte[] Key { get { throw null; } set { } }
protected override void Dispose(bool disposing) { }
protected override void HashCore(byte[] rgb, int ib, int cb) { }
protected override byte[] HashFinal() { throw null; }
public override void Initialize() { }
}
public sealed partial class IncrementalHash : System.IDisposable
{
internal IncrementalHash() { }
public System.Security.Cryptography.HashAlgorithmName AlgorithmName { get { throw null; } }
public void AppendData(byte[] data) { }
public void AppendData(byte[] data, int offset, int count) { }
public static System.Security.Cryptography.IncrementalHash CreateHash(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public static System.Security.Cryptography.IncrementalHash CreateHMAC(System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] key) { throw null; }
public void Dispose() { }
public byte[] GetHashAndReset() { throw null; }
}
public abstract partial class MD5 : System.Security.Cryptography.HashAlgorithm
{
protected MD5() { }
public static new System.Security.Cryptography.MD5 Create() { throw null; }
public static new System.Security.Cryptography.MD5 Create(string algName) { throw null; }
}
public abstract class MaskGenerationMethod
{
public abstract byte[] GenerateMask(byte[] rgbSeed, int cbReturn);
}
public class PKCS1MaskGenerationMethod : MaskGenerationMethod
{
public PKCS1MaskGenerationMethod() { }
public string HashName { get { throw null; } set { } }
public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn) { throw null; }
}
public abstract partial class RandomNumberGenerator : System.IDisposable
{
protected RandomNumberGenerator() { }
public static System.Security.Cryptography.RandomNumberGenerator Create() { throw null; }
public static System.Security.Cryptography.RandomNumberGenerator Create(string rngName) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract void GetBytes(byte[] data);
public virtual void GetBytes(byte[] data, int offset, int count) { }
public virtual void GetNonZeroBytes(byte[] data) { }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public abstract partial class RC2 : System.Security.Cryptography.SymmetricAlgorithm
{
protected int EffectiveKeySizeValue;
protected RC2() { }
public virtual int EffectiveKeySize { get { throw null; } set { } }
public override int KeySize { get { throw null; } set { } }
public static new System.Security.Cryptography.RC2 Create() { throw null; }
public static new System.Security.Cryptography.RC2 Create(string AlgName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public abstract partial class Rijndael : System.Security.Cryptography.SymmetricAlgorithm
{
protected Rijndael() { }
public static new System.Security.Cryptography.Rijndael Create() { throw null; }
public static new System.Security.Cryptography.Rijndael Create(string algName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class RijndaelManaged : System.Security.Cryptography.Rijndael
{
public RijndaelManaged() { }
public override int BlockSize { get { throw null; } set { } }
public override byte[] IV { get { throw null; } set { } }
public override byte[] Key { get { throw null; } set { } }
public override int KeySize { get { throw null; } set { } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } }
public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
public override void GenerateIV() { }
public override void GenerateKey() { }
}
public partial class Rfc2898DeriveBytes : System.Security.Cryptography.DeriveBytes
{
public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) { }
public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm) { }
public Rfc2898DeriveBytes(string password, byte[] salt) { }
public Rfc2898DeriveBytes(string password, byte[] salt, int iterations) { }
public Rfc2898DeriveBytes(string password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm) { }
public Rfc2898DeriveBytes(string password, int saltSize) { }
public Rfc2898DeriveBytes(string password, int saltSize, int iterations) { }
public Rfc2898DeriveBytes(string password, int saltSize, int iterations, HashAlgorithmName hashAlgorithm) { }
public HashAlgorithmName HashAlgorithm { get { throw null; } }
public int IterationCount { get { throw null; } set { } }
public byte[] Salt { get { throw null; } set { } }
public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
public override byte[] GetBytes(int cb) { throw null; }
public override void Reset() { }
}
public abstract partial class RSA : System.Security.Cryptography.AsymmetricAlgorithm
{
protected RSA() { }
public override string KeyExchangeAlgorithm { get { throw null; } }
public override string SignatureAlgorithm { get { throw null; } }
public static new System.Security.Cryptography.RSA Create() { throw null; }
public static System.Security.Cryptography.RSA Create(int keySizeInBits) { throw null; }
public static new System.Security.Cryptography.RSA Create(string algName) { throw null; }
public static System.Security.Cryptography.RSA Create(System.Security.Cryptography.RSAParameters parameters) { throw null; }
public virtual byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; }
public virtual byte[] DecryptValue(byte[] rgb) { throw null; }
public virtual byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; }
public virtual byte[] EncryptValue(byte[] rgb) { throw null; }
public abstract System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters);
protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public override void FromXmlString(string xmlString) { }
public abstract void ImportParameters(System.Security.Cryptography.RSAParameters parameters);
public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public virtual byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public override string ToXmlString(bool includePrivateParameters) { throw null; }
public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public virtual bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
}
public sealed partial class RSAEncryptionPadding : System.IEquatable<System.Security.Cryptography.RSAEncryptionPadding>
{
internal RSAEncryptionPadding() { }
public System.Security.Cryptography.RSAEncryptionPaddingMode Mode { get { throw null; } }
public System.Security.Cryptography.HashAlgorithmName OaepHashAlgorithm { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA1 { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA256 { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA384 { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA512 { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding Pkcs1 { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding CreateOaep(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Security.Cryptography.RSAEncryptionPadding other) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { throw null; }
public static bool operator !=(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { throw null; }
public override string ToString() { throw null; }
}
public enum RSAEncryptionPaddingMode
{
Oaep = 1,
Pkcs1 = 0,
}
public partial class RSAOAEPKeyExchangeDeformatter : System.Security.Cryptography.AsymmetricKeyExchangeDeformatter
{
public RSAOAEPKeyExchangeDeformatter() { }
public RSAOAEPKeyExchangeDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override string Parameters { get { throw null; } set { } }
public override byte[] DecryptKeyExchange(byte[] rgbData) { throw null; }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
public partial class RSAOAEPKeyExchangeFormatter : System.Security.Cryptography.AsymmetricKeyExchangeFormatter
{
public RSAOAEPKeyExchangeFormatter() { }
public RSAOAEPKeyExchangeFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public byte[] Parameter { get { throw null; } set { } }
public override string Parameters { get { throw null; } }
public RandomNumberGenerator Rng { get { throw null; } set { } }
public override byte[] CreateKeyExchange(byte[] rgbData) { throw null; }
public override byte[] CreateKeyExchange(byte[] rgbData, System.Type symAlgType) { throw null; }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct RSAParameters
{
public byte[] D;
public byte[] DP;
public byte[] DQ;
public byte[] Exponent;
public byte[] InverseQ;
public byte[] Modulus;
public byte[] P;
public byte[] Q;
}
public partial class RSAPKCS1KeyExchangeDeformatter : System.Security.Cryptography.AsymmetricKeyExchangeDeformatter
{
public RSAPKCS1KeyExchangeDeformatter() { }
public RSAPKCS1KeyExchangeDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public RandomNumberGenerator RNG { get { throw null; } set { } }
public override string Parameters { get { throw null; } set { } }
public override byte[] DecryptKeyExchange(byte[] rgbIn) { throw null; }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
public partial class RSAPKCS1KeyExchangeFormatter : System.Security.Cryptography.AsymmetricKeyExchangeFormatter
{
public RSAPKCS1KeyExchangeFormatter() { }
public RSAPKCS1KeyExchangeFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override string Parameters { get { throw null; } }
public RandomNumberGenerator Rng { get { throw null; } set { } }
public override byte[] CreateKeyExchange(byte[] rgbData) { throw null; }
public override byte[] CreateKeyExchange(byte[] rgbData, System.Type symAlgType) { throw null; }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
public partial class RSAPKCS1SignatureDeformatter : System.Security.Cryptography.AsymmetricSignatureDeformatter
{
public RSAPKCS1SignatureDeformatter() { }
public RSAPKCS1SignatureDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override void SetHashAlgorithm(string strName) { }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; }
}
public partial class RSAPKCS1SignatureFormatter : System.Security.Cryptography.AsymmetricSignatureFormatter
{
public RSAPKCS1SignatureFormatter() { }
public RSAPKCS1SignatureFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override byte[] CreateSignature(byte[] rgbHash) { throw null; }
public override void SetHashAlgorithm(string strName) { }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
public sealed partial class RSASignaturePadding : System.IEquatable<System.Security.Cryptography.RSASignaturePadding>
{
internal RSASignaturePadding() { }
public System.Security.Cryptography.RSASignaturePaddingMode Mode { get { throw null; } }
public static System.Security.Cryptography.RSASignaturePadding Pkcs1 { get { throw null; } }
public static System.Security.Cryptography.RSASignaturePadding Pss { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Security.Cryptography.RSASignaturePadding other) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { throw null; }
public static bool operator !=(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { throw null; }
public override string ToString() { throw null; }
}
public enum RSASignaturePaddingMode
{
Pkcs1 = 0,
Pss = 1,
}
public abstract partial class SHA1 : System.Security.Cryptography.HashAlgorithm
{
protected SHA1() { }
public static new System.Security.Cryptography.SHA1 Create() { throw null; }
public static new System.Security.Cryptography.SHA1 Create(string hashName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class SHA1Managed : System.Security.Cryptography.SHA1
{
public SHA1Managed() { }
protected sealed override void Dispose(bool disposing) { }
protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected sealed override byte[] HashFinal() { throw null; }
public sealed override void Initialize() { }
}
public abstract partial class SHA256 : System.Security.Cryptography.HashAlgorithm
{
protected SHA256() { }
public static new System.Security.Cryptography.SHA256 Create() { throw null; }
public static new System.Security.Cryptography.SHA256 Create(string hashName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class SHA256Managed : System.Security.Cryptography.SHA256
{
public SHA256Managed() { }
protected sealed override void Dispose(bool disposing) { }
protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected sealed override byte[] HashFinal() { throw null; }
public sealed override void Initialize() { }
}
public abstract partial class SHA384 : System.Security.Cryptography.HashAlgorithm
{
protected SHA384() { }
public static new System.Security.Cryptography.SHA384 Create() { throw null; }
public static new System.Security.Cryptography.SHA384 Create(string hashName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class SHA384Managed : System.Security.Cryptography.SHA384
{
public SHA384Managed() { }
protected sealed override void Dispose(bool disposing) { }
protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected sealed override byte[] HashFinal() { throw null; }
public sealed override void Initialize() { }
}
public abstract partial class SHA512 : System.Security.Cryptography.HashAlgorithm
{
protected SHA512() { }
public static new System.Security.Cryptography.SHA512 Create() { throw null; }
public static new System.Security.Cryptography.SHA512 Create(string hashName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public sealed partial class SHA512Managed : System.Security.Cryptography.SHA512
{
public SHA512Managed() { }
protected sealed override void Dispose(bool disposing) { }
protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { }
protected sealed override byte[] HashFinal() { throw null; }
public sealed override void Initialize() { }
}
public partial class SignatureDescription {
public SignatureDescription() { }
public SignatureDescription(System.Security.SecurityElement el) { }
public string DeformatterAlgorithm { get { throw null; } set { } }
public string DigestAlgorithm { get { throw null;} set { } }
public string FormatterAlgorithm { get { throw null;} set { } }
public string KeyAlgorithm { get { throw null;} set { } }
public virtual System.Security.Cryptography.AsymmetricSignatureDeformatter CreateDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; }
public virtual System.Security.Cryptography.HashAlgorithm CreateDigest() { throw null; }
public virtual System.Security.Cryptography.AsymmetricSignatureFormatter CreateFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; }
}
public abstract partial class TripleDES : System.Security.Cryptography.SymmetricAlgorithm
{
protected TripleDES() { }
public override byte[] Key { get { throw null; } set { } }
public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public static new System.Security.Cryptography.TripleDES Create() { throw null; }
public static new System.Security.Cryptography.TripleDES Create(string str) { throw null; }
public static bool IsWeakKey(byte[] rgbKey) { throw null; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Demo.OAuth2.WebApi2.Areas.HelpPage.Models;
namespace Demo.OAuth2.WebApi2.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright 2008-2011. This work is licensed under the BSD license, available at
// http://www.movesinstitute.org/licenses
//
// Orignal authors: DMcG, Jason Nelson
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace OpenDis.Enumerations.Environment.ObjectState
{
/// <summary>
/// Enumeration values for Minefield (env.obj.appear.areal.minefield, Minefield,
/// section 12.1.2.4.1)
/// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
/// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Serializable]
public struct Minefield
{
/// <summary>
/// Describes the breached appearance of the object
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Describes the breached appearance of the object")]
public enum BreachValue : uint
{
/// <summary>
/// No breaching
/// </summary>
NoBreaching = 0,
/// <summary>
/// Breached
/// </summary>
Breached = 1,
/// <summary>
/// Cleared
/// </summary>
Cleared = 2,
/// <summary>
/// null
/// </summary>
Unknown = 3
}
private Minefield.BreachValue breach;
private int mineCount;
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(Minefield left, Minefield right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(Minefield left, Minefield right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
// If parameters are null return false (cast to object to prevent recursive loop!)
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
/// <summary>
/// Performs an explicit conversion from <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> to <see cref="System.UInt32"/>.
/// </summary>
/// <param name="obj">The <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> scheme instance.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator uint(Minefield obj)
{
return obj.ToUInt32();
}
/// <summary>
/// Performs an explicit conversion from <see cref="System.UInt32"/> to <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/>.
/// </summary>
/// <param name="value">The uint value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator Minefield(uint value)
{
return Minefield.FromUInt32(value);
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> instance from the byte array.
/// </summary>
/// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/>.</param>
/// <param name="index">The starting position within value.</param>
/// <returns>The <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> instance, represented by a byte array.</returns>
/// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception>
/// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception>
public static Minefield FromByteArray(byte[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (index < 0 ||
index > array.Length - 1 ||
index + 4 > array.Length - 1)
{
throw new IndexOutOfRangeException();
}
return FromUInt32(BitConverter.ToUInt32(array, index));
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> instance from the uint value.
/// </summary>
/// <param name="value">The uint value which represents the <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> instance.</param>
/// <returns>The <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> instance, represented by the uint value.</returns>
public static Minefield FromUInt32(uint value)
{
Minefield ps = new Minefield();
uint mask0 = 0x30000;
byte shift0 = 16;
uint newValue0 = value & mask0 >> shift0;
ps.Breach = (Minefield.BreachValue)newValue0;
uint mask2 = 0x80000000;
byte shift2 = 31;
uint newValue2 = value & mask2 >> shift2;
ps.MineCount = (int)newValue2;
return ps;
}
/// <summary>
/// Gets or sets the breach.
/// </summary>
/// <value>The breach.</value>
public Minefield.BreachValue Breach
{
get { return this.breach; }
set { this.breach = value; }
}
/// <summary>
/// Gets or sets the minecount.
/// </summary>
/// <value>The minecount.</value>
public int MineCount
{
get { return this.mineCount; }
set { this.mineCount = value; }
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (!(obj is Minefield))
{
return false;
}
return this.Equals((Minefield)obj);
}
/// <summary>
/// Determines whether the specified <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> instance is equal to this instance.
/// </summary>
/// <param name="other">The <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> instance to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Minefield other)
{
// If parameter is null return false (cast to object to prevent recursive loop!)
if ((object)other == null)
{
return false;
}
return
this.Breach == other.Breach &&
this.MineCount == other.MineCount;
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> to the byte array.
/// </summary>
/// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> instance.</returns>
public byte[] ToByteArray()
{
return BitConverter.GetBytes(this.ToUInt32());
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> to the uint value.
/// </summary>
/// <returns>The uint value representing the current <see cref="OpenDis.Enumerations.Environment.ObjectState.Minefield"/> instance.</returns>
public uint ToUInt32()
{
uint val = 0;
val |= (uint)((uint)this.Breach << 16);
val |= (uint)((uint)this.MineCount << 31);
return val;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
int hash = 17;
// Overflow is fine, just wrap
unchecked
{
hash = (hash * 29) + this.Breach.GetHashCode();
hash = (hash * 29) + this.MineCount.GetHashCode();
}
return hash;
}
}
}
| |
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.ClassBased;
using FluentNHibernate.MappingModel.Collections;
using FluentNHibernate.MappingModel.Output;
using FluentNHibernate.Testing.Testing;
using NUnit.Framework;
namespace FluentNHibernate.Testing.MappingModel.Output
{
[TestFixture]
public class XmlReferenceComponentWriterTester
{
private IXmlWriter<ReferenceComponentMapping> writer;
[SetUp]
public void GetWriterFromContainer()
{
var container = new XmlWriterContainer();
writer = container.Resolve<IXmlWriter<ReferenceComponentMapping>>();
}
[Test]
public void ShouldWriteNameAttribute()
{
var testHelper = CreateTestHelper();
testHelper.Check(x => x.Name, "name").MapsToAttribute("name");
testHelper.VerifyAll(writer);
}
private XmlWriterTestHelper<ReferenceComponentMapping> CreateTestHelper()
{
var testHelper = new XmlWriterTestHelper<ReferenceComponentMapping>();
testHelper.CreateInstance(CreateInstance);
return testHelper;
}
private ReferenceComponentMapping CreateInstance()
{
var property = new DummyPropertyInfo("ComponentProperty", typeof(ComponentTarget)).ToMember();
var instance = new ReferenceComponentMapping(ComponentType.Component, property, typeof(ComponentTarget), typeof(Target), null);
instance.AssociateExternalMapping(new ExternalComponentMapping(ComponentType.Component));
return instance;
}
[Test]
public void ShouldWriteAccessAttribute()
{
var testHelper = CreateTestHelper();
testHelper.Check(x => x.Access, "acc").MapsToAttribute("access");
testHelper.VerifyAll(writer);
}
[Test]
public void ShouldWriteClassAttribute()
{
var testHelper = CreateTestHelper();
testHelper.Check(x => x.Class, new TypeReference("class")).MapsToAttribute("class");
testHelper.VerifyAll(writer);
}
[Test]
public void ShouldWriteUpdateAttribute()
{
var testHelper = CreateTestHelper();
testHelper.Check(x => x.Update, true).MapsToAttribute("update");
testHelper.VerifyAll(writer);
}
[Test]
public void ShouldWriteInsertAttribute()
{
var testHelper = CreateTestHelper();
testHelper.Check(x => x.Insert, true).MapsToAttribute("insert");
testHelper.VerifyAll(writer);
}
[Test]
public void ShouldWriteLazyAttribute()
{
var testHelper = CreateTestHelper();
testHelper.Check(x => x.Lazy, true).MapsToAttribute("lazy");
testHelper.VerifyAll(writer);
}
[Test]
public void ShouldWriteOptimisticLockAttribute()
{
var testHelper = CreateTestHelper();
testHelper.Check(x => x.OptimisticLock, true).MapsToAttribute("optimistic-lock");
testHelper.VerifyAll(writer);
}
[Test]
public void ShouldWriteComponents()
{
var mapping = CreateInstance();
mapping.AddComponent(new ComponentMapping(ComponentType.Component));
writer.VerifyXml(mapping)
.Element("component").Exists();
}
[Test]
public void ShouldWriteDynamicComponents()
{
var mapping = CreateInstance();
mapping.AddComponent(new ComponentMapping(ComponentType.DynamicComponent));
writer.VerifyXml(mapping)
.Element("dynamic-component").Exists();
}
[Test]
public void ShouldWriteProperties()
{
var mapping = CreateInstance();
mapping.AddProperty(new PropertyMapping());
writer.VerifyXml(mapping)
.Element("property").Exists();
}
[Test]
public void ShouldWriteManyToOnes()
{
var mapping = CreateInstance();
mapping.AddReference(new ManyToOneMapping());
writer.VerifyXml(mapping)
.Element("many-to-one").Exists();
}
[Test]
public void ShouldWriteOneToOnes()
{
var mapping = CreateInstance();
mapping.AddOneToOne(new OneToOneMapping());
writer.VerifyXml(mapping)
.Element("one-to-one").Exists();
}
[Test]
public void ShouldWriteAnys()
{
var mapping = CreateInstance();
mapping.AddAny(new AnyMapping());
writer.VerifyXml(mapping)
.Element("any").Exists();
}
[Test]
public void ShouldWriteMaps()
{
var mapping = CreateInstance();
mapping.AddCollection(CollectionMapping.Map());
writer.VerifyXml(mapping)
.Element("map").Exists();
}
[Test]
public void ShouldWriteSets()
{
var mapping = CreateInstance();
mapping.AddCollection(CollectionMapping.Set());
writer.VerifyXml(mapping)
.Element("set").Exists();
}
[Test]
public void ShouldWriteBags()
{
var mapping = CreateInstance();
mapping.AddCollection(CollectionMapping.Bag());
writer.VerifyXml(mapping)
.Element("bag").Exists();
}
[Test]
public void ShouldWriteLists()
{
var mapping = CreateInstance();
mapping.AddCollection(CollectionMapping.List());
writer.VerifyXml(mapping)
.Element("list").Exists();
}
[Test, Ignore]
public void ShouldWriteArrays()
{
Assert.Fail();
}
[Test, Ignore]
public void ShouldWritePrimitiveArrays()
{
Assert.Fail();
}
private class Target {}
private class ComponentTarget {}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using System.Reflection;
using Ctrip.Log4.Appender;
using Ctrip.Log4.Layout;
using Ctrip.Log4.Util;
using Ctrip.Log4.Repository;
using Ctrip.Log4.Repository.Hierarchy;
namespace Ctrip.Log4.Config
{
/// <summary>
/// Use this class to quickly configure a <see cref="Hierarchy"/>.
/// </summary>
/// <remarks>
/// <para>
/// Allows very simple programmatic configuration of Ctrip.
/// </para>
/// <para>
/// Only one appender can be configured using this configurator.
/// The appender is set at the root of the hierarchy and all logging
/// events will be delivered to that appender.
/// </para>
/// <para>
/// Appenders can also implement the <see cref="Ctrip.Log4.Core.IOptionHandler"/> interface. Therefore
/// they would require that the <see cref="M:Ctrip.Log4.Core.IOptionHandler.ActivateOptions()"/> method
/// be called after the appenders properties have been configured.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class BasicConfigurator
{
#region Private Static Fields
/// <summary>
/// The fully qualified type of the BasicConfigurator class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(BasicConfigurator);
#endregion Private Static Fields
#region Private Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="BasicConfigurator" /> class.
/// </summary>
/// <remarks>
/// <para>
/// Uses a private access modifier to prevent instantiation of this class.
/// </para>
/// </remarks>
private BasicConfigurator()
{
}
#endregion Private Instance Constructors
#region Public Static Methods
/// <summary>
/// Initializes the Ctrip system with a default configuration.
/// </summary>
/// <remarks>
/// <para>
/// Initializes the Ctrip logging system using a <see cref="ConsoleAppender"/>
/// that will write to <c>Console.Out</c>. The log messages are
/// formatted using the <see cref="PatternLayout"/> layout object
/// with the <see cref="PatternLayout.DetailConversionPattern"/>
/// layout style.
/// </para>
/// </remarks>
static public ICollection Configure()
{
return BasicConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()));
}
/// <summary>
/// Initializes the Ctrip system using the specified appender.
/// </summary>
/// <param name="appender">The appender to use to log all logging events.</param>
/// <remarks>
/// <para>
/// Initializes the Ctrip system using the specified appender.
/// </para>
/// </remarks>
static public ICollection Configure(IAppender appender)
{
return Configure(new IAppender[] { appender });
}
/// <summary>
/// Initializes the Ctrip system using the specified appenders.
/// </summary>
/// <param name="appenders">The appenders to use to log all logging events.</param>
/// <remarks>
/// <para>
/// Initializes the Ctrip system using the specified appenders.
/// </para>
/// </remarks>
static public ICollection Configure(params IAppender[] appenders)
{
ArrayList configurationMessages = new ArrayList();
ILoggerRepository repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, appenders);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
/// <summary>
/// Initializes the <see cref="ILoggerRepository"/> with a default configuration.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <remarks>
/// <para>
/// Initializes the specified repository using a <see cref="ConsoleAppender"/>
/// that will write to <c>Console.Out</c>. The log messages are
/// formatted using the <see cref="PatternLayout"/> layout object
/// with the <see cref="PatternLayout.DetailConversionPattern"/>
/// layout style.
/// </para>
/// </remarks>
static public ICollection Configure(ILoggerRepository repository)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
// Create the layout
PatternLayout layout = new PatternLayout();
layout.ConversionPattern = PatternLayout.DetailConversionPattern;
layout.ActivateOptions();
// Create the appender
ConsoleAppender appender = new ConsoleAppender();
appender.Layout = layout;
appender.ActivateOptions();
InternalConfigure(repository, appender);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
/// <summary>
/// Initializes the <see cref="ILoggerRepository"/> using the specified appender.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="appender">The appender to use to log all logging events.</param>
/// <remarks>
/// <para>
/// Initializes the <see cref="ILoggerRepository"/> using the specified appender.
/// </para>
/// </remarks>
static public ICollection Configure(ILoggerRepository repository, IAppender appender)
{
return Configure(repository, new IAppender[] { appender });
}
/// <summary>
/// Initializes the <see cref="ILoggerRepository"/> using the specified appenders.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="appenders">The appenders to use to log all logging events.</param>
/// <remarks>
/// <para>
/// Initializes the <see cref="ILoggerRepository"/> using the specified appender.
/// </para>
/// </remarks>
static public ICollection Configure(ILoggerRepository repository, params IAppender[] appenders)
{
ArrayList configurationMessages = new ArrayList();
using (new LogLog.LogReceivedAdapter(configurationMessages))
{
InternalConfigure(repository, appenders);
}
repository.ConfigurationMessages = configurationMessages;
return configurationMessages;
}
static private void InternalConfigure(ILoggerRepository repository, params IAppender[] appenders)
{
IBasicRepositoryConfigurator configurableRepository = repository as IBasicRepositoryConfigurator;
if (configurableRepository != null)
{
configurableRepository.Configure(appenders);
}
else
{
LogLog.Warn(declaringType, "BasicConfigurator: Repository [" + repository + "] does not support the BasicConfigurator");
}
}
#endregion Public Static Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Engine.Operations;
using Signum.Entities.Authorization;
using Signum.Entities;
using Signum.Engine.Maps;
using Signum.Utilities.Reflection;
using Signum.Engine.DynamicQuery;
using System.Reflection;
using Signum.Utilities;
using Signum.Entities.Basics;
using Signum.Entities.Alerts;
using System.Linq.Expressions;
using Signum.Engine.Extensions.Basics;
using Signum.Engine.Basics;
using Signum.Engine.Authorization;
using Signum.Engine.Mailing;
using Signum.Entities.Mailing;
using Signum.Engine.Templating;
using Signum.Engine.Scheduler;
using Signum.Entities.UserAssets;
using Microsoft.AspNetCore.Html;
using Signum.Engine;
using Signum.Entities.Scheduler;
using System.Text.RegularExpressions;
namespace Signum.Engine.Alerts
{
public static class AlertLogic
{
[AutoExpressionField]
public static IQueryable<AlertEntity> Alerts(this Entity e) =>
As.Expression(() => Database.Query<AlertEntity>().Where(a => a.Target.Is(e)));
[AutoExpressionField]
public static IQueryable<AlertEntity> MyActiveAlerts(this Entity e) =>
As.Expression(() => e.Alerts().Where(a => a.Recipient == UserHolder.Current.ToLite() && a.CurrentState == AlertCurrentState.Alerted));
public static Func<IUserEntity?> DefaultRecipient = () => null;
public static Dictionary<AlertTypeSymbol, AlertTypeOptions> SystemAlertTypes = new Dictionary<AlertTypeSymbol, AlertTypeOptions>();
public static string? GetText(this AlertTypeSymbol? alertType)
{
if (alertType == null)
return null;
var options = SystemAlertTypes.GetOrThrow(alertType);
return options.GetText?.Invoke();
}
public static bool Started = false;
public static void AssertStarted(SchemaBuilder sb)
{
sb.AssertDefined(ReflectionTools.GetMethodInfo(() => Start(null!, null!)));
}
public static void Start(SchemaBuilder sb, params Type[] registerExpressionsFor)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
sb.Include<AlertEntity>()
.WithQuery(() => a => new
{
Entity = a,
a.Id,
a.AlertDate,
a.AlertType,
a.State,
a.Title,
Text = a.Text!.Etc(100),
a.Target,
a.Recipient,
a.CreationDate,
a.CreatedBy,
a.AttendedDate,
a.AttendedBy,
});
AlertGraph.Register();
As.ReplaceExpression((AlertEntity a) => a.Text, a => a.TextField.HasText() ? a.TextField : a.AlertType.GetText());
Schema.Current.EntityEvents<AlertEntity>().Retrieved += (a, ctx) =>
{
a.TextFromAlertType = a.AlertType?.GetText();
};
sb.Include<AlertTypeSymbol>()
.WithSave(AlertTypeOperation.Save)
.WithDelete(AlertTypeOperation.Delete)
.WithQuery(() => t => new
{
Entity = t,
t.Id,
t.Name,
t.Key,
});
SemiSymbolLogic<AlertTypeSymbol>.Start(sb, () => SystemAlertTypes.Keys);
if (registerExpressionsFor != null)
{
var alerts = Signum.Utilities.ExpressionTrees.Linq.Expr((Entity ident) => ident.Alerts());
var myActiveAlerts = Signum.Utilities.ExpressionTrees.Linq.Expr((Entity ident) => ident.MyActiveAlerts());
foreach (var type in registerExpressionsFor)
{
QueryLogic.Expressions.Register(new ExtensionInfo(type, alerts, alerts.Body.Type, "Alerts", () => typeof(AlertEntity).NicePluralName()));
QueryLogic.Expressions.Register(new ExtensionInfo(type, myActiveAlerts, myActiveAlerts.Body.Type, "MyActiveAlerts", () => AlertMessage.MyActiveAlerts.NiceToString()));
}
}
Started = true;
}
}
public static void RegisterAlertNotificationMail(SchemaBuilder sb)
{
EmailModelLogic.RegisterEmailModel<AlertNotificationMail>(() => new EmailTemplateEntity
{
Messages = CultureInfoLogic.ForEachCulture(culture => new EmailTemplateMessageEmbedded(culture)
{
Text = @"
<p>Hi @[m:Entity],</p>
<p>You have some pending alerts:</p>
<ul>
@foreach[m:Alerts] as $a
<li>
<strong>@[$a.AlertType]:</strong><br/>
@[m:TextFormatted]<br/>
<small>@[$a.AlertDate] @[$a.CreatedBy]</small>
</li>
@endforeach
</ul>
<p>Please visit <a href=""@[g:UrlLeft]"">@[g:UrlLeft]</a></p>",
Subject = AlertMessage.NewUnreadNotifications.NiceToString(),
}).ToMList()
});
sb.Include<SendNotificationEmailTaskEntity>()
.WithSave(SendNotificationEmailTaskOperation.Save)
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.SendNotificationsOlderThan,
e.SendBehavior,
});
SchedulerLogic.ExecuteTask.Register((SendNotificationEmailTaskEntity task, ScheduledTaskContext ctx) =>
{
var limit = DateTime.Now.AddMinutes(-task.SendNotificationsOlderThan);
var query = Database.Query<AlertEntity>()
.Where(a => a.State == AlertState.Saved && a.EmailNotificationsSent == false && a.Recipient != null && a.CreationDate < limit)
.Where(a => task.SendBehavior == SendAlertTypeBehavior.All ||
task.SendBehavior == SendAlertTypeBehavior.Include && task.AlertTypes.Contains(a.AlertType!) ||
task.SendBehavior == SendAlertTypeBehavior.Exclude && !task.AlertTypes.Contains(a.AlertType!));
if (!query.Any())
return null;
var alerts = query
.Select(a => new { Alert = a, Recipient = a.Recipient!.Entity })
.ToList();
EmailPackageEntity emailPackage = new EmailPackageEntity().Save();
var emails = alerts.GroupBy(a => a.Recipient, a => a.Alert).SelectMany(gr => new AlertNotificationMail((UserEntity)gr.Key, gr.ToList()).CreateEmailMessage()).ToList();
emails.ForEach(a =>
{
a.State = EmailMessageState.ReadyToSend;
a.Package = emailPackage.ToLite();
});
emails.BulkInsertQueryIds(a => a.Target!);
query.UnsafeUpdate().Set(a => a.EmailNotificationsSent, a => true).Execute();
return emailPackage.ToLite();
});
}
public class AlertNotificationMail : EmailModel<UserEntity>
{
public List<AlertEntity> Alerts { get; set; }
public AlertNotificationMail(UserEntity recipient, List<AlertEntity> alerts) : base(recipient)
{
this.Alerts = alerts;
}
static Regex LinkPlaceholder = new Regex(@"\[(?<prop>(\w|\d|\.)+)(\:(?<text>.+))?\](\((?<url>.+)\))?");
public HtmlString? TextFormatted(TemplateParameters tp)
{
if (!tp.RuntimeVariables.TryGetValue("$a", out object? alertObject))
return null;
var alert = (AlertEntity)alertObject;
var text = alert.Text ?? "";
var newText = LinkPlaceholder.Replace(text, m =>
{
var propEx = m.Groups["prop"].Value;
var prop = GetPropertyValue(alert, propEx);
var lite = prop is Entity e ? e.ToLite() :
prop is Lite<Entity> l ? l : null;
var url = ReplacePlaceHolders(m.Groups["url"].Value.DefaultToNull(), alert)?.Replace("~", EmailLogic.Configuration.UrlLeft) ?? (lite != null ? EntityUrl(lite) : "#");
var text = ReplacePlaceHolders(m.Groups["text"].Value.DefaultToNull(), alert) ?? (lite != null ? lite.ToString() : null);
return @$"<a href=""{url}"">{text}</a>";
});
if (text != newText)
return new HtmlString(newText);
if (alert.Target != null)
return new HtmlString(@$"{text}<br/><a href=""{EntityUrl(alert.Target)}"">{alert.Target.ToString()}</a>");
return new HtmlString(text);
}
private static string EntityUrl(Lite<Entity> lite)
{
return $"{EmailLogic.Configuration.UrlLeft}/view/{TypeLogic.GetCleanName(lite.EntityType)}/{lite.Id}";
}
static Regex TextPlaceHolder = new Regex(@"({(?<prop>(\w|\d|\.)+)})");
private string? ReplacePlaceHolders(string? value, AlertEntity alert)
{
if (value == null)
return null;
return TextPlaceHolder.Replace(value, g =>
{
return GetPropertyValue(alert, g.Groups["prop"].Value)?.ToString()!;
});
}
private static object? GetPropertyValue(AlertEntity alert, string expresion)
{
var parts = expresion.SplitNoEmpty('.');
var result = SimpleMemberEvaluator.EvaluateExpression(alert, parts);
if (result is Result<object?>.Error e)
throw new InvalidOperationException(e.ErrorText);
if (result is Result<object?>.Success s)
return s.Value;
throw new UnexpectedValueException(result);
}
public override List<EmailOwnerRecipientData> GetRecipients()
{
return new List<EmailOwnerRecipientData>
{
new EmailOwnerRecipientData(this.Entity.EmailOwnerData)
{
Kind = EmailRecipientKind.To,
}
};
}
}
public static void RegisterAlertType(AlertTypeSymbol alertType, Enum localizableTextMessage) => RegisterAlertType(alertType, new AlertTypeOptions { GetText = () => localizableTextMessage.NiceToString() });
public static void RegisterAlertType(AlertTypeSymbol alertType, AlertTypeOptions? options = null)
{
if (!alertType.Key.HasText())
throw new InvalidOperationException("alertType must have a key, use MakeSymbol method after the constructor when declaring it");
SystemAlertTypes.Add(alertType, options ?? new AlertTypeOptions());
}
public static AlertEntity? CreateAlert(this IEntity entity, AlertTypeSymbol alertType, string? text = null, DateTime? alertDate = null, Lite<IUserEntity>? createdBy = null, string? title = null, Lite<IUserEntity>? recipient = null)
{
return CreateAlert(entity.ToLiteFat(), alertType, text, alertDate, createdBy, title, recipient);
}
public static AlertEntity? CreateAlert<T>(this Lite<T> entity, AlertTypeSymbol alertType, string? text = null, DateTime? alertDate = null, Lite<IUserEntity>? createdBy = null, string? title = null, Lite<IUserEntity>? recipient = null) where T : class, IEntity
{
if (Started == false)
return null;
var result = new AlertEntity
{
AlertDate = alertDate ?? TimeZoneManager.Now,
CreatedBy = createdBy ?? UserHolder.Current?.ToLite(),
TitleField = title,
TextField = text,
Target = (Lite<Entity>)entity,
AlertType = alertType,
Recipient = recipient
};
return result.Execute(AlertOperation.Save);
}
public static AlertEntity? CreateAlertForceNew(this IEntity entity, AlertTypeSymbol alertType, string? text = null, DateTime? alertDate = null, Lite<IUserEntity>? createdBy = null, string? title = null, Lite<IUserEntity>? recipient = null)
{
return CreateAlertForceNew(entity.ToLite(), alertType, text, alertDate, createdBy, title, recipient);
}
public static AlertEntity? CreateAlertForceNew<T>(this Lite<T> entity, AlertTypeSymbol alertType, string? text = null, DateTime? alertDate = null, Lite<IUserEntity>? createdBy = null, string? title = null, Lite<IUserEntity>? recipient = null) where T : class, IEntity
{
if (Started == false)
return null;
using (Transaction tr = Transaction.ForceNew())
{
var alert = entity.CreateAlert(alertType, text, alertDate, createdBy);
return tr.Commit(alert);
}
}
public static void RegisterCreatorTypeCondition(SchemaBuilder sb, TypeConditionSymbol typeCondition)
{
sb.Schema.Settings.AssertImplementedBy((AlertEntity a) => a.CreatedBy, typeof(UserEntity));
TypeConditionLogic.RegisterCompile<AlertEntity>(typeCondition,
a => a.CreatedBy.Is(UserEntity.Current));
}
public static void RegisterRecipientTypeCondition(SchemaBuilder sb, TypeConditionSymbol typeCondition)
{
sb.Schema.Settings.AssertImplementedBy((AlertEntity a) => a.Recipient, typeof(UserEntity));
TypeConditionLogic.RegisterCompile<AlertEntity>(typeCondition,
a => a.Recipient.Is(UserEntity.Current));
}
public static void AttendAllAlerts(Lite<Entity> target, AlertTypeSymbol alertType)
{
using (AuthLogic.Disable())
{
Database.Query<AlertEntity>()
.Where(a => a.Target.Is(target) && a.AlertType == alertType && a.State == AlertState.Saved)
.ToList()
.ForEach(a => a.Execute(AlertOperation.Attend));
}
}
public static void DeleteAllAlerts(Lite<Entity> target)
{
using (AuthLogic.Disable())
{
Database.Query<AlertEntity>()
.Where(a => a.Target.Is(target))
.UnsafeDelete();
}
}
}
public class AlertTypeOptions
{
public Func<string>? GetText;
}
public class AlertGraph : Graph<AlertEntity, AlertState>
{
public static void Register()
{
GetState = a => a.State;
new ConstructFrom<Entity>(AlertOperation.CreateAlertFromEntity)
{
ToStates = { AlertState.New },
Construct = (a, _) => new AlertEntity
{
AlertDate = TimeZoneManager.Now,
CreatedBy = UserHolder.Current.ToLite(),
Recipient = AlertLogic.DefaultRecipient()?.ToLite(),
TitleField = null,
TextField = null,
Target = a.ToLite(),
AlertType = null
}
}.Register();
new Construct(AlertOperation.Create)
{
ToStates = { AlertState.New },
Construct = (_) => new AlertEntity
{
AlertDate = TimeZoneManager.Now,
CreatedBy = UserHolder.Current.ToLite(),
Recipient = AlertLogic.DefaultRecipient()?.ToLite(),
TitleField = null,
TextField = null,
Target = null!,
AlertType = null
}
}.Register();
new Execute(AlertOperation.Save)
{
FromStates = { AlertState.Saved, AlertState.New },
ToStates = { AlertState.Saved },
CanBeNew = true,
CanBeModified = true,
Execute = (a, _) => { a.State = AlertState.Saved; }
}.Register();
new Execute(AlertOperation.Attend)
{
FromStates = { AlertState.Saved },
ToStates = { AlertState.Attended },
Execute = (a, _) =>
{
a.State = AlertState.Attended;
a.AttendedDate = TimeZoneManager.Now;
a.AttendedBy = UserEntity.Current.ToLite();
}
}.Register();
new Execute(AlertOperation.Unattend)
{
FromStates = { AlertState.Attended },
ToStates = { AlertState.Saved },
Execute = (a, _) =>
{
a.State = AlertState.Saved;
a.AttendedDate = null;
a.AttendedBy = null;
}
}.Register();
new Execute(AlertOperation.Delay)
{
FromStates = { AlertState.Saved },
ToStates = { AlertState.Saved },
Execute = (a, args) =>
{
a.AlertDate = args.GetArg<DateTime>();
}
}.Register();
}
}
}
| |
//
// Palette.cs
//
// Author:
// Maia Kozheva <sikon@ubuntu.com>
//
// Copyright (c) 2010 Maia Kozheva <sikon@ubuntu.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Cairo;
namespace Pinta.Core
{
public sealed class Palette
{
public enum FileFormat { PDN, GIMP }
public event EventHandler PaletteChanged;
private List<Color> colors;
private Palette ()
{
colors = new List<Color> ();
}
private void OnPaletteChanged ()
{
if (PaletteChanged != null)
PaletteChanged (this, EventArgs.Empty);
}
public int Count
{
get {
return colors.Count;
}
}
public Color this[int index]
{
get {
return colors[index];
}
set {
colors[index] = value;
OnPaletteChanged ();
}
}
public void Resize (int newSize)
{
int difference = newSize - Count;
if (difference > 0) {
for (int i = 0; i < difference; i++)
colors.Add (new Color (1, 1, 1));
} else {
colors.RemoveRange (newSize, -difference);
}
colors.TrimExcess ();
OnPaletteChanged ();
}
public static Palette GetDefault ()
{
Palette p = new Palette ();
p.LoadDefault ();
return p;
}
public static Palette FromFile (string fileName)
{
Palette p = new Palette ();
p.Load (fileName);
return p;
}
public void LoadDefault ()
{
colors.Clear ();
colors.Add (new Color (255 / 255f, 255 / 255f, 255 / 255f));
colors.Add (new Color (128 / 255f, 128 / 255f, 128 / 255f));
colors.Add (new Color (127 / 255f, 0 / 255f, 0 / 255f));
colors.Add (new Color (127 / 255f, 51 / 255f, 0 / 255f));
colors.Add (new Color (127 / 255f, 106 / 255f, 0 / 255f));
colors.Add (new Color (91 / 255f, 127 / 255f, 0 / 255f));
colors.Add (new Color (38 / 255f, 127 / 255f, 0 / 255f));
colors.Add (new Color (0 / 255f, 127 / 255f, 14 / 255f));
colors.Add (new Color (0 / 255f, 127 / 255f, 70 / 255f));
colors.Add (new Color (0 / 255f, 127 / 255f, 127 / 255f));
colors.Add (new Color (0 / 255f, 74 / 255f, 127 / 255f));
colors.Add (new Color (0 / 255f, 19 / 255f, 127 / 255f));
colors.Add (new Color (33 / 255f, 0 / 255f, 127 / 255f));
colors.Add (new Color (87 / 255f, 0 / 255f, 127 / 255f));
colors.Add (new Color (127 / 255f, 0 / 255f, 110 / 255f));
colors.Add (new Color (127 / 255f, 0 / 255f, 55 / 255f));
colors.Add (new Color (0 / 255f, 0 / 255f, 0 / 255f));
colors.Add (new Color (64 / 255f, 64 / 255f, 64 / 255f));
colors.Add (new Color (255 / 255f, 0 / 255f, 0 / 255f));
colors.Add (new Color (255 / 255f, 106 / 255f, 0 / 255f));
colors.Add (new Color (255 / 255f, 216 / 255f, 0 / 255f));
colors.Add (new Color (182 / 255f, 255 / 255f, 0 / 255f));
colors.Add (new Color (76 / 255f, 255 / 255f, 0 / 255f));
colors.Add (new Color (0 / 255f, 255 / 255f, 33 / 255f));
colors.Add (new Color (0 / 255f, 255 / 255f, 144 / 255f));
colors.Add (new Color (0 / 255f, 255 / 255f, 255 / 255f));
colors.Add (new Color (0 / 255f, 148 / 255f, 255 / 255f));
colors.Add (new Color (0 / 255f, 38 / 255f, 255 / 255f));
colors.Add (new Color (72 / 255f, 0 / 255f, 255 / 255f));
colors.Add (new Color (178 / 255f, 0 / 255f, 255 / 255f));
colors.Add (new Color (255 / 255f, 0 / 255f, 220 / 255f));
colors.Add (new Color (255 / 255f, 0 / 255f, 110 / 255f));
colors.Add (new Color (160 / 255f, 160 / 255f, 160 / 255f));
colors.Add (new Color (48 / 255f, 48 / 255f, 48 / 255f));
colors.Add (new Color (255 / 255f, 127 / 255f, 127 / 255f));
colors.Add (new Color (255 / 255f, 178 / 255f, 127 / 255f));
colors.Add (new Color (255 / 255f, 233 / 255f, 127 / 255f));
colors.Add (new Color (218 / 255f, 255 / 255f, 127 / 255f));
colors.Add (new Color (165 / 255f, 255 / 255f, 127 / 255f));
colors.Add (new Color (127 / 255f, 255 / 255f, 142 / 255f));
colors.Add (new Color (127 / 255f, 255 / 255f, 197 / 255f));
colors.Add (new Color (127 / 255f, 255 / 255f, 255 / 255f));
colors.Add (new Color (127 / 255f, 201 / 255f, 255 / 255f));
colors.Add (new Color (127 / 255f, 146 / 255f, 255 / 255f));
colors.Add (new Color (161 / 255f, 127 / 255f, 255 / 255f));
colors.Add (new Color (214 / 255f, 127 / 255f, 255 / 255f));
colors.Add (new Color (255 / 255f, 127 / 255f, 237 / 255f));
colors.Add (new Color (255 / 255f, 127 / 255f, 182 / 255f));
colors.TrimExcess ();
OnPaletteChanged ();
}
public void Load (string fileName)
{
List<Color> tmpColors = new List<Color> ();
StreamReader reader = new StreamReader (fileName);
try {
string line = reader.ReadLine ();
if (line.IndexOf ("GIMP") != 0) {
// Assume PDN palette
do {
if (line.IndexOf (';') == 0)
continue;
uint color = uint.Parse (line.Substring (0, 8), NumberStyles.HexNumber);
double b = (color & 0xff) / 255f;
double g = ((color >> 8) & 0xff) / 255f;
double r = ((color >> 16) & 0xff) / 255f;
double a = (color >> 24) / 255f;
tmpColors.Add (new Color (r, g, b, a));
} while ((line = reader.ReadLine ()) != null);
} else {
// GIMP palette: skip everything until the first color
while (!char.IsDigit(line[0]))
line = reader.ReadLine ();
// then read the palette
do {
if (line.IndexOf ('#') == 0)
continue;
string[] split = line.Split ((char[]) null, StringSplitOptions.RemoveEmptyEntries);
double r = int.Parse (split[0]) / 255f;
double g = int.Parse (split[1]) / 255f;
double b = int.Parse (split[2]) / 255f;
tmpColors.Add (new Color (r, g, b));
} while ((line = reader.ReadLine ()) != null);
}
colors = tmpColors;
colors.TrimExcess ();
OnPaletteChanged ();
} finally {
reader.Close ();
}
}
public void Save (string fileName, FileFormat format)
{
StreamWriter writer = new StreamWriter (fileName);
if (format == FileFormat.PDN) {
writer.WriteLine ("; Hexadecimal format: aarrggbb");
foreach (Color color in colors) {
byte a = (byte) (color.A * 255);
byte r = (byte) (color.R * 255);
byte g = (byte) (color.G * 255);
byte b = (byte) (color.B * 255);
writer.WriteLine ("{0:X}", (a << 24) | (r << 16) | (g << 8) | b);
}
} else {
// GIMP
writer.WriteLine ("GIMP Palette");
writer.WriteLine ("Name: Pinta Created {0}", DateTime.Now.ToString (DateTimeFormatInfo.InvariantInfo.RFC1123Pattern));
writer.WriteLine ("#");
foreach (Color color in colors) {
writer.WriteLine ("{0,3} {1,3} {2,3} Untitled", (int) (color.R * 255), (int) (color.G * 255), (int) (color.B * 255));
}
}
writer.Close ();
}
}
}
| |
using System;
using System.Collections.Generic;
namespace ICSimulator
{
/* a Priority Packet Pool is an abstract packet container that
* implements a priority/reordering/scheduling. Intended for use
* with injection queues, and possibly in-network buffers, that are
* nominally FIFO but could potentially reorder.
*/
public interface IPrioPktPool
{
void addPacket(Packet pkt);
void setNodeId(int id);
Packet next();
int Count { get; }
int FlitCount { get; }
}
/* simple single-FIFO packet pool. */
public class FIFOPrioPktPool : IPrioPktPool
{
Queue<Packet> queue;
int flitCount = 0;
public FIFOPrioPktPool()
{
queue = new Queue<Packet>();
}
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
queue.Enqueue(pkt);
}
public Packet next()
{
if (queue.Count > 0)
{
Packet p = queue.Dequeue();
flitCount -= p.nrOfFlits;
return p;
}
else
return null;
}
public void setNodeId(int id)
{
}
public int Count { get { return queue.Count; } }
public int FlitCount { get { return flitCount; } }
}
/* multi-queue priority packet pool, based on Packet's notion of
* queues (Packet.numQueues and Packet.getQueue() ): currently
* Packet implements these based on the cache-coherence protocol,
* so that control, data, and writeback packets have separate queues.
*/
public class MultiQPrioPktPool : IPrioPktPool
{
Queue<Packet>[] queues;
int nqueues;
int queue_next;
int flitCount = 0;
public MultiQPrioPktPool()
{
nqueues = Packet.numQueues;
queues = new Queue<Packet>[nqueues];
for (int i = 0; i < nqueues; i++)
queues[i] = new Queue<Packet>();
queue_next = nqueues - 1;
}
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
queues[pkt.getQueue()].Enqueue(pkt);
}
void advanceRR()
{
int tries = nqueues;
do
queue_next = (queue_next + 1) % nqueues;
while (tries-- > 0 && queues[queue_next].Count == 0);
}
public Packet next()
{
advanceRR();
if (queues[queue_next].Count > 0)
{
Packet p = queues[queue_next].Dequeue();
flitCount -= p.nrOfFlits;
return p;
}
else
return null;
}
public void setNodeId(int id)
{
}
public int Count
{
get
{
int sum = 0;
for (int i = 0; i < nqueues; i++)
sum += queues[i].Count;
return sum;
}
}
public int FlitCount { get { return flitCount; } }
}
/**
* @brief Same as the multiqpriopktpool with throttling on request packet
* enabled.
**/
public class MultiQThrottlePktPool : IPrioPktPool
{
Queue<Packet>[] queues;
int nqueues;
int queue_next;
int node_id=-1;
int flitCount = 0;
public static IPrioPktPool construct()
{
if (Config.cluster_prios_injq)
return new ReallyNiftyPrioritizingPacketPool();
else
return new MultiQThrottlePktPool();
}
private MultiQThrottlePktPool()
{
nqueues = Packet.numQueues;
queues = new Queue<Packet>[nqueues];
for (int i = 0; i < nqueues; i++)
queues[i] = new Queue<Packet>();
queue_next = nqueues - 1;
}
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
queues[pkt.getQueue()].Enqueue(pkt);
}
void advanceRR()
{
int tries = nqueues;
do
queue_next = (queue_next + 1) % nqueues;
while (tries-- > 0 && queues[queue_next].Count == 0);
}
public Packet next()
{
if(node_id==-1)
throw new Exception("Haven't configured the packet pool");
advanceRR();
//only queues for non-control packets go proceed without any
//throttling constraint
if (queues[queue_next].Count > 0 &&
(queue_next!=0 || Simulator.controller.tryInject(node_id)) )
{
Packet p = queues[queue_next].Dequeue();
flitCount -= p.nrOfFlits;
return p;
}
else
return null;
}
public void setNodeId(int id)
{
node_id=id;
}
public int Count
{
get
{
int sum = 0;
for (int i = 0; i < nqueues; i++)
sum += queues[i].Count;
return sum;
}
}
public int FlitCount { get { return flitCount; } }
}
/** @brief the Really Nifty Prioritizing Packet Pool respects full
* priorities (i.e., by using a min-heap) and also optionally respects
* throttling.
*/
public class ReallyNiftyPrioritizingPacketPool : IPrioPktPool
{
class HeapNode : IComparable
{
public Packet pkt;
public HeapNode(Packet p) { pkt = p; }
public int CompareTo(object o)
{
if (o is HeapNode)
return Simulator.controller.rankFlits(pkt.flits[0], (o as HeapNode).pkt.flits[0]);
else
throw new ArgumentException("bad comparison");
}
}
MinHeap<HeapNode>[] heaps;
int nheaps;
int heap_next;
int flitCount = 0;
int node_id = -1;
public ReallyNiftyPrioritizingPacketPool()
{
nheaps = Packet.numQueues;
heaps = new MinHeap<HeapNode>[nheaps];
for (int i = 0; i < nheaps; i++)
heaps[i] = new MinHeap<HeapNode>();
heap_next = nheaps - 1;
}
public void addPacket(Packet pkt)
{
flitCount += pkt.nrOfFlits;
HeapNode h = new HeapNode(pkt);
heaps[pkt.getQueue()].Enqueue(h);
}
void advanceRR()
{
int tries = nheaps;
do
heap_next = (heap_next + 1) % nheaps;
// keep incrementing while we're at an empty queue or at req-queue and throttling
while (tries-- > 0 &&
((heaps[heap_next].Count == 0) ||
(heap_next == 0 && !Simulator.controller.tryInject(node_id))));
}
public Packet next()
{
advanceRR();
//only queues for non-control packets go proceed without any
//throttling constraint
if (heaps[heap_next].Count > 0 &&
(heap_next!=0 || Simulator.controller.tryInject(node_id)) )
{
HeapNode h = heaps[heap_next].Dequeue();
Packet p = h.pkt;
flitCount -= p.nrOfFlits;
return p;
}
else
return null;
}
public void setNodeId(int id)
{
node_id = id;
}
public int Count
{
get
{
int sum = 0;
for (int i = 0; i < nheaps; i++)
sum += heaps[i].Count;
return sum;
}
}
public int FlitCount { get { return flitCount; } }
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Hydra.Panes.HydraPublic
File: AllSecuritiesPane.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Hydra.Panes
{
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Configuration;
using Ecng.Serialization;
using Ecng.Xaml;
using MoreLinq;
using StockSharp.Algo;
using StockSharp.Algo.History;
using StockSharp.Algo.Storages;
using StockSharp.BusinessEntities;
using StockSharp.Hydra.Windows;
using StockSharp.Hydra.Core;
using StockSharp.Logging;
using StockSharp.Localization;
using StockSharp.Messages;
public partial class AllSecuritiesPane : IPane
{
private bool _isDisposed;
public AllSecuritiesPane()
{
InitializeComponent();
Progress.Init(ExportBtn, MainGrid);
SecurityPicker.SecurityProvider = ConfigManager.GetService<ISecurityProvider>();
SecurityPicker.ExcludeAllSecurity();
ExportBtn.SetTypeEnabled(ExportTypes.StockSharpBin, false);
ExportBtn.SetTypeEnabled(ExportTypes.StockSharpCsv, false);
MarketData.DataLoading += () => MarketDataBusyIndicator.IsBusy = true;
MarketData.DataLoaded += () => MarketDataBusyIndicator.IsBusy = false;
}
private void DriveCtrl_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
UpdateMarketDataGrid();
}
private void SecurityPicker_OnSecuritySelected(Security security)
{
UpdateMarketDataGrid();
EditSecurities.IsEnabled = SecurityPicker.SelectedSecurities.Any();
}
private void DrivePanel_OnFormatChanged()
{
UpdateMarketDataGrid();
}
private void UpdateMarketDataGrid()
{
MarketData.BeginMakeEntries(ConfigManager.GetService<IStorageRegistry>(),
SecurityPicker.SelectedSecurity, DrivePanel.StorageFormat, DrivePanel.SelectedDrive);
}
private void LookupPanel_OnLookup(Security filter)
{
//SecurityPicker.Securities.Clear();
SecurityPicker.SecurityFilter = filter.Code;
var downloaders = MainWindow.Instance.Tasks.Where(t => t.Settings.IsEnabled).OfType<ISecurityDownloader>().ToArray();
if (downloaders.IsEmpty())
return;
BusyIndicator.BusyContent = LocalizedStrings.Str2834;
BusyIndicator.IsBusy = true;
ThreadingHelper
.Thread(() =>
{
try
{
var securities = ConfigManager.TryGetService<IEntityRegistry>().Securities;
SecurityPicker.Securities.AddRange(securities
.Lookup(filter)
.Where(s => !s.IsAllSecurity()));
downloaders.ForEach(d =>
d.Refresh(securities, filter, SecurityPicker.Securities.Add, () => _isDisposed));
}
catch (Exception ex)
{
ex.LogError();
}
try
{
this.GuiAsync(() => BusyIndicator.IsBusy = false);
}
catch (Exception ex)
{
ex.LogError();
}
})
.Launch();
}
private void CreateSecurity_OnClick(object sender, RoutedEventArgs e)
{
new SecurityEditWindow { Security = new Security() }.ShowModal(this);
//var wnd = new SecurityEditWindow { Security = new Security() };
//if (!wnd.ShowModal(this))
// return;
//SecurityPicker.Securities.Add(wnd.Security);
}
private void SecurityPicker_OnSecurityDoubleClick(Security security)
{
new SecurityEditWindow { Security = security }.ShowModal(this);
}
private void EditSecurities_OnClick(object sender, RoutedEventArgs e)
{
var securities = SecurityPicker.SelectedSecurities.ToArray();
if (securities.IsEmpty())
return;
new SecurityEditWindow { Securities = securities }.ShowModal(this);
}
string IPane.Title => LocalizedStrings.Str2835;
Uri IPane.Icon => null;
bool IPane.IsValid => true;
void IPersistable.Load(SettingsStorage storage)
{
if (storage.ContainsKey("Drive"))
DrivePanel.SelectedDrive = DriveCache.Instance.GetDrive(storage.GetValue<string>("Drive"));
DrivePanel.StorageFormat = storage.GetValue<StorageFormats>("StorageFormat");
MarketData.Load(storage.GetValue<SettingsStorage>(nameof(MarketData)));
SecurityPicker.Load(storage.GetValue<SettingsStorage>(nameof(SecurityPicker)));
LookupPanel.Load(storage.GetValue<SettingsStorage>(nameof(LookupPanel)));
}
void IPersistable.Save(SettingsStorage storage)
{
if (DrivePanel.SelectedDrive != null)
storage.SetValue("Drive", DrivePanel.SelectedDrive.Path);
storage.SetValue("StorageFormat", DrivePanel.StorageFormat.To<string>());
storage.SetValue(nameof(MarketData), MarketData.Save());
storage.SetValue(nameof(SecurityPicker), SecurityPicker.Save());
storage.SetValue(nameof(LookupPanel), LookupPanel.Save());
}
void IDisposable.Dispose()
{
Progress.Stop();
_isDisposed = true;
MarketData.CancelMakeEntires();
}
private void ExportBtn_OnExportStarted()
{
var securities = SecurityPicker.FilteredSecurities;
if (securities.Count == 0)
{
Progress.DoesntExist();
return;
}
var path = ExportBtn.GetPath(null, typeof(SecurityMessage), null, null, null, null);
if (path == null)
return;
Progress.Start(null, typeof(SecurityMessage), null, securities.Select(s => s.ToMessage()), securities.Count, path);
}
}
}
| |
// Copyright (c) 2012-2014 Sharpex2D - Kevin Scholz (ThuCommix)
//
// 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 Sharpex2D.Common.Extensions;
using Sharpex2D.Input;
using Sharpex2D.Math;
using Sharpex2D.Rendering;
namespace Sharpex2D.UI
{
[Developer("ThuCommix", "developer@sharpex2d.de")]
[TestState(TestState.Tested)]
public abstract class UIControl
{
#region IGameHandler Implementation
/// <summary>
/// Updates the object.
/// </summary>
/// <param name="gameTime">The GameTime.</param>
public void Update(GameTime gameTime)
{
_mouseState = _inputManager.Mouse.GetState();
_keyState = _inputManager.Keyboard.GetState();
_mouseRectangle.X = _mouseState.Position.X;
_mouseRectangle.Y = _mouseState.Position.Y;
IsMouseHoverState = _mouseRectangle.Intersects(Bounds.ToRectangle());
//check if the mouse clicked the control
if (IsMouseHoverState && IsMouseDown(MouseButtons.Left))
{
SetFocus();
}
OnUpdate(gameTime);
}
#endregion
#region UIControl
#region Properties
private KeyboardState _keyState;
private Vector2 _lastRelativeMousePostion;
private MouseState _mouseState;
/// <summary>
/// Gets the relative mouse position.
/// </summary>
public Vector2 RelativeMousePosition
{
get
{
if (!IsMouseHoverState)
{
return _lastRelativeMousePostion;
}
_lastRelativeMousePostion = _mouseState.Position - Position;
return _lastRelativeMousePostion;
}
}
/// <summary>
/// Gets the Bounds of the UIControl.
/// </summary>
public UIBounds Bounds { private set; get; }
/// <summary>
/// Sets or gets the Position of the UIControl.
/// </summary>
public Vector2 Position
{
get { return _position; }
set
{
_position = value;
UpdateBounds();
}
}
/// <summary>
/// A value indicating whether the UIControl is visible.
/// </summary>
public bool Visible { set; get; }
/// <summary>
/// A value indicating whether the UIConrol is enabled.
/// </summary>
public bool Enable { set; get; }
/// <summary>
/// A value indicating whether the UIControl is available to get the focus.
/// </summary>
public bool CanGetFocus { set; get; }
/// <summary>
/// Sets or gets the Size of the UIControl.
/// </summary>
public UISize Size
{
get { return _size; }
set
{
_size = value;
UpdateBounds();
}
}
/// <summary>
/// A value indicating whether the mouse is hovering the UIControl.
/// </summary>
public bool IsMouseHoverState { private set; get; }
/// <summary>
/// A value indicating whether the UIControl has focus.
/// </summary>
public bool HasFocus { internal set; get; }
/// <summary>
/// Gets the Guid-Identifer.
/// </summary>
public Guid Guid { private set; get; }
/// <summary>
/// Sets or gets the Parent UIControl.
/// </summary>
public UIControl Parent
{
set { SetParent(value); }
get { return _parent; }
}
/// <summary>
/// Gets the children of the UIControl.
/// </summary>
public List<UIControl> Children { internal set; get; }
/// <summary>
/// Sets or gets the UIManager.
/// </summary>
internal UIManager UIManager { set; get; }
#endregion
#region Methods
/// <summary>
/// Initializes a new UIControl class.
/// </summary>
/// <param name="assignedUIManager">The assigned UIManager.</param>
protected UIControl(UIManager assignedUIManager)
{
_position = new Vector2(0, 0);
_size = new UISize(0, 0);
UpdateBounds();
_mouseRectangle = new Rectangle {Width = 1, Height = 1};
Guid = Guid.NewGuid();
_inputManager = SGL.Components.Get<InputManager>();
CanGetFocus = true;
Enable = true;
Visible = true;
_parent = null;
_lastRelativeMousePostion = new Vector2(0, 0);
Children = new List<UIControl>();
UIManager = assignedUIManager;
UIManager.Add(this);
}
/// <summary>
/// Updates the Bounds of the UIControl.
/// </summary>
internal void UpdateBounds()
{
Bounds = new UIBounds((int) Position.X, (int) Position.Y, Size.Width, Size.Height);
}
/// <summary>
/// Sets the Parent.
/// </summary>
/// <param name="parent">The Parent.</param>
internal void SetParent(UIControl parent)
{
if (parent != null)
{
parent.Children.Add(this);
_parent = parent;
}
else
{
_parent.RemoveChild(this);
_parent = null;
}
}
/// <summary>
/// Sets the Focus for this UIControl.
/// </summary>
public void SetFocus()
{
//check if we can get the focus
if (!CanGetFocus || !Enable) return;
// unset the last focused element
foreach (UIControl ctrl in UIManager.GetAll())
{
ctrl.HasFocus = false;
}
HasFocus = true;
}
/// <summary>
/// Removes a UIControl from the Childs.
/// </summary>
/// <param name="control">The UIControl.</param>
public void RemoveChild(UIControl control)
{
if (Children.Contains(control))
{
Children.Remove(control);
}
}
/// <summary>
/// Removes the Focus of the UIControl.
/// </summary>
public void RemoveFocus()
{
HasFocus = false;
}
/// <summary>
/// Determines, if a MouseButton was pressed.
/// </summary>
/// <param name="mouseButton">The MouseButton.</param>
/// <returns>True if pressed</returns>
public bool IsMouseDown(MouseButtons mouseButton)
{
//while the cursor do not intersect our control, return false
return IsMouseHoverState && Enable && _mouseState.IsMouseButtonUp(mouseButton);
}
/// <summary>
/// Determines, if a Key was pressed down.
/// </summary>
/// <param name="key">The Key.</param>
/// <returns>True if pressed down</returns>
public bool IsKeyDown(Keys key)
{
return HasFocus && Enable && _keyState.IsKeyDown(key);
}
/// <summary>
/// Determines, if a Key was relased.
/// </summary>
/// <param name="key">The Key.</param>
/// <returns>True if pressed</returns>
public bool IsKeyUp(Keys key)
{
return HasFocus && Enable && _keyState.IsKeyUp(key);
}
#endregion
#region Private Fields
private readonly InputManager _inputManager;
private Rectangle _mouseRectangle;
private UIControl _parent;
private Vector2 _position;
private UISize _size;
#endregion
#region Abstract
/// <summary>
/// Processes a Render call.
/// </summary>
/// <param name="spriteBatch">The SpriteBatch.</param>
public abstract void OnDraw(SpriteBatch spriteBatch);
/// <summary>
/// Updates the object.
/// </summary>
/// <param name="gameTime">The GameTime.</param>
public virtual void OnUpdate(GameTime gameTime)
{
}
#endregion
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace System.Runtime
{
// AsyncResult starts acquired; Complete releases.
[Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.ManualResetEvent, SupportsAsync = true, ReleaseMethod = "Complete")]
internal abstract class AsyncResult : IAsyncResult
{
private static AsyncCallback s_asyncCompletionWrapperCallback;
private AsyncCallback _callback;
private bool _completedSynchronously;
private bool _endCalled;
private Exception _exception;
private bool _isCompleted;
private AsyncCompletion _nextAsyncCompletion;
private object _state;
private Action _beforePrepareAsyncCompletionAction;
private Func<IAsyncResult, bool> _checkSyncValidationFunc;
[Fx.Tag.SynchronizationObject]
private ManualResetEvent _manualResetEvent;
[Fx.Tag.SynchronizationObject(Blocking = false)]
private object _thisLock;
protected AsyncResult(AsyncCallback callback, object state)
{
_callback = callback;
_state = state;
_thisLock = new object();
}
public object AsyncState
{
get
{
return _state;
}
}
public WaitHandle AsyncWaitHandle
{
get
{
if (_manualResetEvent != null)
{
return _manualResetEvent;
}
lock (ThisLock)
{
if (_manualResetEvent == null)
{
_manualResetEvent = new ManualResetEvent(_isCompleted);
}
}
return _manualResetEvent;
}
}
public bool CompletedSynchronously
{
get
{
return _completedSynchronously;
}
}
public bool HasCallback
{
get
{
return _callback != null;
}
}
public bool IsCompleted
{
get
{
return _isCompleted;
}
}
// used in conjunction with PrepareAsyncCompletion to allow for finally blocks
protected Action<AsyncResult, Exception> OnCompleting { get; set; }
private object ThisLock
{
get
{
return _thisLock;
}
}
// subclasses like TraceAsyncResult can use this to wrap the callback functionality in a scope
protected Action<AsyncCallback, IAsyncResult> VirtualCallback
{
get;
set;
}
protected void Complete(bool completedSynchronously)
{
if (_isCompleted)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultCompletedTwice));
}
_completedSynchronously = completedSynchronously;
if (OnCompleting != null)
{
// Allow exception replacement, like a catch/throw pattern.
try
{
OnCompleting(this, _exception);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
_exception = exception;
}
}
if (completedSynchronously)
{
// If we completedSynchronously, then there's no chance that the manualResetEvent was created so
// we don't need to worry about a race condition.
Fx.Assert(_manualResetEvent == null, "No ManualResetEvent should be created for a synchronous AsyncResult.");
_isCompleted = true;
}
else
{
lock (ThisLock)
{
_isCompleted = true;
if (_manualResetEvent != null)
{
_manualResetEvent.Set();
}
}
}
if (_callback != null)
{
try
{
if (VirtualCallback != null)
{
VirtualCallback(_callback, this);
}
else
{
_callback(this);
}
}
#pragma warning disable 1634
#pragma warning suppress 56500 // transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw Fx.Exception.AsError(new CallbackException(InternalSR.AsyncCallbackThrewException, e));
}
#pragma warning restore 1634
}
}
protected void Complete(bool completedSynchronously, Exception exception)
{
_exception = exception;
Complete(completedSynchronously);
}
private static void AsyncCompletionWrapperCallback(IAsyncResult result)
{
if (result == null)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidNullAsyncResult));
}
if (result.CompletedSynchronously)
{
return;
}
AsyncResult thisPtr = (AsyncResult)result.AsyncState;
if (!thisPtr.OnContinueAsyncCompletion(result))
{
return;
}
AsyncCompletion callback = thisPtr.GetNextCompletion();
if (callback == null)
{
ThrowInvalidAsyncResult(result);
}
bool completeSelf = false;
Exception completionException = null;
try
{
completeSelf = callback(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeSelf = true;
completionException = e;
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
// Note: this should be only derived by the TransactedAsyncResult
protected virtual bool OnContinueAsyncCompletion(IAsyncResult result)
{
return true;
}
// Note: this should be used only by the TransactedAsyncResult
protected void SetBeforePrepareAsyncCompletionAction(Action beforePrepareAsyncCompletionAction)
{
_beforePrepareAsyncCompletionAction = beforePrepareAsyncCompletionAction;
}
// Note: this should be used only by the TransactedAsyncResult
protected void SetCheckSyncValidationFunc(Func<IAsyncResult, bool> checkSyncValidationFunc)
{
_checkSyncValidationFunc = checkSyncValidationFunc;
}
protected AsyncCallback PrepareAsyncCompletion(AsyncCompletion callback)
{
if (_beforePrepareAsyncCompletionAction != null)
{
_beforePrepareAsyncCompletionAction();
}
_nextAsyncCompletion = callback;
if (AsyncResult.s_asyncCompletionWrapperCallback == null)
{
AsyncResult.s_asyncCompletionWrapperCallback = Fx.ThunkCallback(new AsyncCallback(AsyncCompletionWrapperCallback));
}
return AsyncResult.s_asyncCompletionWrapperCallback;
}
protected bool CheckSyncContinue(IAsyncResult result)
{
AsyncCompletion dummy;
return TryContinueHelper(result, out dummy);
}
protected bool SyncContinue(IAsyncResult result)
{
AsyncCompletion callback;
if (TryContinueHelper(result, out callback))
{
return callback(result);
}
else
{
return false;
}
}
private bool TryContinueHelper(IAsyncResult result, out AsyncCompletion callback)
{
if (result == null)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidNullAsyncResult));
}
callback = null;
if (_checkSyncValidationFunc != null)
{
if (!_checkSyncValidationFunc(result))
{
return false;
}
}
else if (!result.CompletedSynchronously)
{
return false;
}
callback = GetNextCompletion();
if (callback == null)
{
ThrowInvalidAsyncResult("Only call Check/SyncContinue once per async operation (once per PrepareAsyncCompletion).");
}
return true;
}
private AsyncCompletion GetNextCompletion()
{
AsyncCompletion result = _nextAsyncCompletion;
_nextAsyncCompletion = null;
return result;
}
protected static void ThrowInvalidAsyncResult(IAsyncResult result)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidAsyncResultImplementation(result.GetType())));
}
protected static void ThrowInvalidAsyncResult(string debugText)
{
string message = InternalSR.InvalidAsyncResultImplementationGeneric;
if (debugText != null)
{
#if DEBUG
message += " " + debugText;
#endif
}
throw Fx.Exception.AsError(new InvalidOperationException(message));
}
[Fx.Tag.Blocking(Conditional = "!asyncResult.isCompleted")]
protected static TAsyncResult End<TAsyncResult>(IAsyncResult result)
where TAsyncResult : AsyncResult
{
if (result == null)
{
throw Fx.Exception.ArgumentNull("result");
}
TAsyncResult asyncResult = result as TAsyncResult;
if (asyncResult == null)
{
throw Fx.Exception.Argument("result", InternalSR.InvalidAsyncResult);
}
if (asyncResult._endCalled)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultAlreadyEnded));
}
asyncResult._endCalled = true;
if (!asyncResult._isCompleted)
{
asyncResult.AsyncWaitHandle.WaitOne();
}
if (asyncResult._manualResetEvent != null)
{
asyncResult._manualResetEvent.Dispose();
}
if (asyncResult._exception != null)
{
throw Fx.Exception.AsError(asyncResult._exception);
}
return asyncResult;
}
// can be utilized by subclasses to write core completion code for both the sync and async paths
// in one location, signalling chainable synchronous completion with the boolean result,
// and leveraging PrepareAsyncCompletion for conversion to an AsyncCallback.
// NOTE: requires that "this" is passed in as the state object to the asynchronous sub-call being used with a completion routine.
protected delegate bool AsyncCompletion(IAsyncResult result);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Text;
namespace System.IO
{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
public sealed partial class FileInfo : FileSystemInfo
{
private String _name;
[System.Security.SecurityCritical]
private FileInfo() { }
[System.Security.SecuritySafeCritical]
public FileInfo(String fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
Contract.EndContractBlock();
Init(fileName);
}
[System.Security.SecurityCritical]
private void Init(String fileName)
{
OriginalPath = fileName;
// Must fully qualify the path for the security check
String fullPath = Path.GetFullPath(fileName);
_name = Path.GetFileName(fileName);
FullPath = fullPath;
DisplayPath = GetDisplayPath(fileName);
}
private String GetDisplayPath(String originalPath)
{
return originalPath;
}
[System.Security.SecuritySafeCritical]
internal FileInfo(String fullPath, String originalPath)
{
Debug.Assert(Path.IsPathRooted(fullPath), "fullPath must be fully qualified!");
_name = originalPath ?? Path.GetFileName(fullPath);
OriginalPath = _name;
FullPath = fullPath;
DisplayPath = _name;
}
public override String Name
{
get { return _name; }
}
public long Length
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if ((FileSystemObject.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, DisplayPath), DisplayPath);
}
return FileSystemObject.Length;
}
}
/* Returns the name of the directory that the file is in */
public String DirectoryName
{
[System.Security.SecuritySafeCritical]
get
{
return Path.GetDirectoryName(FullPath);
}
}
/* Creates an instance of the parent directory */
public DirectoryInfo Directory
{
get
{
String dirName = DirectoryName;
if (dirName == null)
return null;
return new DirectoryInfo(dirName);
}
}
public bool IsReadOnly
{
get
{
return (Attributes & FileAttributes.ReadOnly) != 0;
}
set
{
if (value)
Attributes |= FileAttributes.ReadOnly;
else
Attributes &= ~FileAttributes.ReadOnly;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public StreamReader OpenText()
{
return new StreamReader(FullPath, Encoding.UTF8, detectEncodingFromByteOrderMarks: true);
}
public StreamWriter CreateText()
{
return new StreamWriter(FullPath, append: false);
}
public StreamWriter AppendText()
{
return new StreamWriter(FullPath, append: true);
}
// Copies an existing file to a new file. An exception is raised if the
// destination file already exists. Use the
// Copy(String, String, boolean) method to allow
// overwriting an existing file.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName
// and Write permissions to destFileName.
//
public FileInfo CopyTo(String destFileName)
{
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName);
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
Contract.EndContractBlock();
destFileName = File.InternalCopy(FullPath, destFileName, false);
return new FileInfo(destFileName, null);
}
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName and Create
// and Write permissions to destFileName.
//
public FileInfo CopyTo(String destFileName, bool overwrite)
{
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName);
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
Contract.EndContractBlock();
destFileName = File.InternalCopy(FullPath, destFileName, overwrite);
return new FileInfo(destFileName, null);
}
public FileStream Create()
{
return File.Create(FullPath);
}
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// On NT, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped. On Win95, the file will be
// deleted irregardless of whether the file is being used.
//
// Your application must have Delete permission to the target file.
//
[System.Security.SecuritySafeCritical]
public override void Delete()
{
FileSystem.Current.DeleteFile(FullPath);
}
// Tests if the given file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false.
//
// Your application must have Read permission for the target directory.
public override bool Exists
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
try
{
return FileSystemObject.Exists;
}
catch
{
return false;
}
}
}
// User must explicitly specify opening a new file or appending to one.
public FileStream Open(FileMode mode)
{
return Open(mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None);
}
public FileStream Open(FileMode mode, FileAccess access)
{
return Open(mode, access, FileShare.None);
}
public FileStream Open(FileMode mode, FileAccess access, FileShare share)
{
return new FileStream(FullPath, mode, access, share);
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileStream OpenRead()
{
return new FileStream(FullPath, FileMode.Open, FileAccess.Read,
FileShare.Read, 4096, false);
}
public FileStream OpenWrite()
{
return new FileStream(FullPath, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
// Moves a given file to a new location and potentially a new file name.
// This method does work across volumes.
//
// The caller must have certain FileIOPermissions. The caller must
// have Read and Write permission to
// sourceFileName and Write
// permissions to destFileName.
//
[System.Security.SecuritySafeCritical]
public void MoveTo(String destFileName)
{
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName));
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
Contract.EndContractBlock();
String fullDestFileName = Path.GetFullPath(destFileName);
// These checks are in place to ensure Unix error throwing happens the same way
// as it does on Windows.These checks can be removed if a solution to #2460 is
// found that doesn't require validity checks before making an API call.
if (!new DirectoryInfo(Path.GetDirectoryName(FullName)).Exists)
{
throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullName));
}
if (!Exists)
{
throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, FullName), FullName);
}
FileSystem.Current.MoveFile(FullPath, fullDestFileName);
FullPath = fullDestFileName;
OriginalPath = destFileName;
_name = Path.GetFileName(fullDestFileName);
DisplayPath = GetDisplayPath(destFileName);
// Flush any cached information about the file.
Invalidate();
}
public FileInfo Replace(String destinationFileName, String destinationBackupFileName)
{
return Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors: false);
}
public FileInfo Replace(String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
{
File.Replace(FullPath, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
return new FileInfo(destinationFileName);
}
// Returns the display path
public override String ToString()
{
return DisplayPath;
}
public void Decrypt()
{
File.Decrypt(FullPath);
}
public void Encrypt()
{
File.Encrypt(FullPath);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBAsyncTests : CSharpTestBase
{
[Fact(Skip = "1068894")]
[WorkItem(1137300, "DevDiv")]
[WorkItem(631350, "DevDiv")]
[WorkItem(643501, "DevDiv")]
[WorkItem(689616, "DevDiv")]
public void TestAsyncDebug()
{
var text = @"
using System;
using System.Threading;
using System.Threading.Tasks;
class DynamicMembers
{
public Func<Task<int>> Prop { get; set; }
}
class TestCase
{
public static int Count = 0;
public async void Run()
{
DynamicMembers dc2 = new DynamicMembers();
dc2.Prop = async () => { await Task.Delay(10000); return 3; };
var rez2 = await dc2.Prop();
if (rez2 == 3) Count++;
Driver.Result = TestCase.Count - 1;
//When test complete, set the flag.
Driver.CompletedSignal.Set();
}
}
class Driver
{
public static int Result = -1;
public static AutoResetEvent CompletedSignal = new AutoResetEvent(false);
static int Main()
{
var t = new TestCase();
t.Run();
CompletedSignal.WaitOne();
return Driver.Result;
}
}";
var compilation = CreateCompilationWithMscorlib45(text, options: TestOptions.DebugDll).VerifyDiagnostics();
var v = CompileAndVerify(compilation);
v.VerifyIL("TestCase.<Run>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 303 (0x12f)
.maxstack 3
.locals init (int V_0,
System.Runtime.CompilerServices.TaskAwaiter<int> V_1,
int V_2,
TestCase.<Run>d__1 V_3,
bool V_4,
System.Exception V_5)
~IL_0000: ldarg.0
IL_0001: ldfld ""int TestCase.<Run>d__1.<>1__state""
IL_0006: stloc.0
.try
{
~IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_008b
-IL_000e: nop
-IL_000f: ldarg.0
IL_0010: newobj ""DynamicMembers..ctor()""
IL_0015: stfld ""DynamicMembers TestCase.<Run>d__1.<dc2>5__1""
-IL_001a: ldarg.0
IL_001b: ldfld ""DynamicMembers TestCase.<Run>d__1.<dc2>5__1""
IL_0020: ldsfld ""System.Func<System.Threading.Tasks.Task<int>> TestCase.<>c.<>9__1_0""
IL_0025: dup
IL_0026: brtrue.s IL_003f
IL_0028: pop
IL_0029: ldsfld ""TestCase.<>c TestCase.<>c.<>9""
IL_002e: ldftn ""System.Threading.Tasks.Task<int> TestCase.<>c.<Run>b__1_0()""
IL_0034: newobj ""System.Func<System.Threading.Tasks.Task<int>>..ctor(object, System.IntPtr)""
IL_0039: dup
IL_003a: stsfld ""System.Func<System.Threading.Tasks.Task<int>> TestCase.<>c.<>9__1_0""
IL_003f: callvirt ""void DynamicMembers.Prop.set""
IL_0044: nop
-IL_0045: ldarg.0
IL_0046: ldfld ""DynamicMembers TestCase.<Run>d__1.<dc2>5__1""
IL_004b: callvirt ""System.Func<System.Threading.Tasks.Task<int>> DynamicMembers.Prop.get""
IL_0050: callvirt ""System.Threading.Tasks.Task<int> System.Func<System.Threading.Tasks.Task<int>>.Invoke()""
IL_0055: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_005a: stloc.1
~IL_005b: ldloca.s V_1
IL_005d: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_0062: brtrue.s IL_00a7
IL_0064: ldarg.0
IL_0065: ldc.i4.0
IL_0066: dup
IL_0067: stloc.0
IL_0068: stfld ""int TestCase.<Run>d__1.<>1__state""
<IL_006d: ldarg.0
IL_006e: ldloc.1
IL_006f: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> TestCase.<Run>d__1.<>u__1""
IL_0074: ldarg.0
IL_0075: stloc.3
IL_0076: ldarg.0
IL_0077: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder TestCase.<Run>d__1.<>t__builder""
IL_007c: ldloca.s V_1
IL_007e: ldloca.s V_3
IL_0080: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, TestCase.<Run>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref TestCase.<Run>d__1)""
IL_0085: nop
IL_0086: leave IL_012e
>IL_008b: ldarg.0
IL_008c: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> TestCase.<Run>d__1.<>u__1""
IL_0091: stloc.1
IL_0092: ldarg.0
IL_0093: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> TestCase.<Run>d__1.<>u__1""
IL_0098: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_009e: ldarg.0
IL_009f: ldc.i4.m1
IL_00a0: dup
IL_00a1: stloc.0
IL_00a2: stfld ""int TestCase.<Run>d__1.<>1__state""
IL_00a7: ldloca.s V_1
IL_00a9: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_00ae: stloc.2
IL_00af: ldloca.s V_1
IL_00b1: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_00b7: ldarg.0
IL_00b8: ldloc.2
IL_00b9: stfld ""int TestCase.<Run>d__1.<>s__3""
IL_00be: ldarg.0
IL_00bf: ldarg.0
IL_00c0: ldfld ""int TestCase.<Run>d__1.<>s__3""
IL_00c5: stfld ""int TestCase.<Run>d__1.<rez2>5__2""
-IL_00ca: ldarg.0
IL_00cb: ldfld ""int TestCase.<Run>d__1.<rez2>5__2""
IL_00d0: ldc.i4.3
IL_00d1: ceq
IL_00d3: stloc.s V_4
~IL_00d5: ldloc.s V_4
IL_00d7: brfalse.s IL_00e7
-IL_00d9: ldsfld ""int TestCase.Count""
IL_00de: stloc.2
IL_00df: ldloc.2
IL_00e0: ldc.i4.1
IL_00e1: add
IL_00e2: stsfld ""int TestCase.Count""
-IL_00e7: ldsfld ""int TestCase.Count""
IL_00ec: ldc.i4.1
IL_00ed: sub
IL_00ee: stsfld ""int Driver.Result""
-IL_00f3: ldsfld ""System.Threading.AutoResetEvent Driver.CompletedSignal""
IL_00f8: callvirt ""bool System.Threading.EventWaitHandle.Set()""
IL_00fd: pop
IL_00fe: leave.s IL_011a
}
catch System.Exception
{
~$IL_0100: stloc.s V_5
IL_0102: ldarg.0
IL_0103: ldc.i4.s -2
IL_0105: stfld ""int TestCase.<Run>d__1.<>1__state""
IL_010a: ldarg.0
IL_010b: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder TestCase.<Run>d__1.<>t__builder""
IL_0110: ldloc.s V_5
IL_0112: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0117: nop
IL_0118: leave.s IL_012e
}
-IL_011a: ldarg.0
IL_011b: ldc.i4.s -2
IL_011d: stfld ""int TestCase.<Run>d__1.<>1__state""
~IL_0122: ldarg.0
IL_0123: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder TestCase.<Run>d__1.<>t__builder""
IL_0128: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_012d: nop
IL_012e: ret
}",
sequencePoints: "TestCase+<Run>d__1.MoveNext");
v.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""DynamicMembers"" name=""get_Prop"">
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""35"" endLine=""8"" endColumn=""39"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""DynamicMembers"" name=""set_Prop"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""40"" endLine=""8"" endColumn=""44"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""TestCase"" name=""Run"">
<customDebugInfo>
<forwardIterator name=""<Run>d__1"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""26"" />
<slot kind=""0"" offset=""139"" />
<slot kind=""28"" offset=""146"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<lambda offset=""86"" />
</encLambdaMap>
</customDebugInfo>
</method>
<method containingType=""TestCase"" name="".cctor"">
<customDebugInfo>
<using>
<namespace usingCount=""3"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""33"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x7"">
<namespace name=""System"" />
<namespace name=""System.Threading"" />
<namespace name=""System.Threading.Tasks"" />
</scope>
</method>
<method containingType=""Driver"" name=""Main"">
<customDebugInfo>
<forward declaringType=""TestCase"" methodName="".cctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""30"" startColumn=""5"" endLine=""30"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""32"" document=""0"" />
<entry offset=""0x7"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""17"" document=""0"" />
<entry offset=""0xe"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""35"" document=""0"" />
<entry offset=""0x19"" startLine=""35"" startColumn=""9"" endLine=""35"" endColumn=""30"" document=""0"" />
<entry offset=""0x21"" startLine=""36"" startColumn=""5"" endLine=""36"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x23"">
<local name=""t"" il_index=""0"" il_start=""0x0"" il_end=""0x23"" attributes=""0"" />
</scope>
</method>
<method containingType=""Driver"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""TestCase"" methodName="".cctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""35"" document=""0"" />
<entry offset=""0x6"" startLine=""28"" startColumn=""5"" endLine=""28"" endColumn=""78"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""TestCase+<>c"" name=""<Run>b__1_0"">
<customDebugInfo>
<forwardIterator name=""<<Run>b__1_0>d"" />
</customDebugInfo>
<sequencePoints />
</method>
<method containingType=""TestCase+<Run>d__1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""TestCase"" methodName="".cctor"" />
<hoistedLocalScopes>
<slot startOffset=""0xe"" endOffset=""0xff"" />
<slot startOffset=""0xe"" endOffset=""0xff"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""146"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""1"" offset=""173"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0xe"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""0"" />
<entry offset=""0xf"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""51"" document=""0"" />
<entry offset=""0x1a"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""71"" document=""0"" />
<entry offset=""0x45"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""37"" document=""0"" />
<entry offset=""0x5b"" hidden=""true"" document=""0"" />
<entry offset=""0xca"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""23"" document=""0"" />
<entry offset=""0xd5"" hidden=""true"" document=""0"" />
<entry offset=""0xd9"" startLine=""18"" startColumn=""24"" endLine=""18"" endColumn=""32"" document=""0"" />
<entry offset=""0xe7"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""44"" document=""0"" />
<entry offset=""0xf3"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""38"" document=""0"" />
<entry offset=""0x100"" hidden=""true"" document=""0"" />
<entry offset=""0x11a"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""0"" />
<entry offset=""0x122"" hidden=""true"" document=""0"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0x100"" />
<kickoffMethod declaringType=""TestCase"" methodName=""Run"" />
<await yield=""0x6d"" resume=""0x8b"" declaringType=""TestCase+<Run>d__1"" methodName=""MoveNext"" />
</asyncInfo>
</method>
<method containingType=""TestCase+<>c+<<Run>b__1_0>d"" name=""MoveNext"">
<customDebugInfo>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""20"" offset=""0"" />
<slot kind=""33"" offset=""2"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0xe"" startLine=""16"" startColumn=""32"" endLine=""16"" endColumn=""33"" document=""0"" />
<entry offset=""0xf"" startLine=""16"" startColumn=""34"" endLine=""16"" endColumn=""58"" document=""0"" />
<entry offset=""0x1f"" hidden=""true"" document=""0"" />
<entry offset=""0x78"" startLine=""16"" startColumn=""59"" endLine=""16"" endColumn=""68"" document=""0"" />
<entry offset=""0x7c"" hidden=""true"" document=""0"" />
<entry offset=""0x96"" startLine=""16"" startColumn=""69"" endLine=""16"" endColumn=""70"" document=""0"" />
<entry offset=""0x9e"" hidden=""true"" document=""0"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""TestCase+<>c"" methodName=""<Run>b__1_0"" />
<await yield=""0x31"" resume=""0x4c"" declaringType=""TestCase+<>c+<<Run>b__1_0>d"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(734596, "DevDiv")]
public void TestAsyncDebug2()
{
var text = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
private static Random random = new Random();
static void Main(string[] args)
{
new Program().QBar();
}
async void QBar()
{
await ZBar();
}
async Task<List<int>> ZBar()
{
var addedInts = new List<int>();
foreach (var z in new[] {1, 2, 3})
{
var newInt = await GetNextInt(random);
addedInts.Add(newInt);
}
return addedInts;
}
private Task<int> GetNextInt(Random random)
{
return Task.FromResult(random.Next());
}
}
}";
var compilation = CreateCompilationWithMscorlib45(text, options: TestOptions.DebugDll).VerifyDiagnostics();
compilation.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""ConsoleApplication1.Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
<namespace usingCount=""3"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""0"" />
<entry offset=""0x1"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""34"" document=""0"" />
<entry offset=""0xc"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xd"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<namespace name=""System.Threading.Tasks"" />
</scope>
</method>
<method containingType=""ConsoleApplication1.Program"" name=""QBar"">
<customDebugInfo>
<forwardIterator name=""<QBar>d__2"" />
</customDebugInfo>
</method>
<method containingType=""ConsoleApplication1.Program"" name=""ZBar"">
<customDebugInfo>
<forwardIterator name=""<ZBar>d__3"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""6"" offset=""61"" />
<slot kind=""8"" offset=""61"" />
<slot kind=""0"" offset=""61"" />
<slot kind=""0"" offset=""132"" />
<slot kind=""28"" offset=""141"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""ConsoleApplication1.Program"" name=""GetNextInt"" parameterNames=""random"">
<customDebugInfo>
<forward declaringType=""ConsoleApplication1.Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""0"" />
<entry offset=""0x1"" startLine=""31"" startColumn=""13"" endLine=""31"" endColumn=""51"" document=""0"" />
<entry offset=""0xf"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""ConsoleApplication1.Program"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""ConsoleApplication1.Program"" methodName=""Main"" parameterNames=""args"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""53"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""ConsoleApplication1.Program+<QBar>d__2"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""ConsoleApplication1.Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""15"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0xe"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""0"" />
<entry offset=""0xf"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""26"" document=""0"" />
<entry offset=""0x20"" hidden=""true"" document=""0"" />
<entry offset=""0x7b"" hidden=""true"" document=""0"" />
<entry offset=""0x93"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" document=""0"" />
<entry offset=""0x9b"" hidden=""true"" document=""0"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0x7b"" />
<kickoffMethod declaringType=""ConsoleApplication1.Program"" methodName=""QBar"" />
<await yield=""0x32"" resume=""0x4d"" declaringType=""ConsoleApplication1.Program+<QBar>d__2"" methodName=""MoveNext"" />
</asyncInfo>
</method>
<method containingType=""ConsoleApplication1.Program+<ZBar>d__3"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""ConsoleApplication1.Program"" methodName=""Main"" parameterNames=""args"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x14e"" />
<slot startOffset=""0x0"" endOffset=""0x0"" />
<slot startOffset=""0x0"" endOffset=""0x0"" />
<slot startOffset=""0x41"" endOffset=""0xed"" />
<slot startOffset=""0x54"" endOffset=""0xed"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""20"" offset=""0"" />
<slot kind=""33"" offset=""141"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0x11"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" document=""0"" />
<entry offset=""0x12"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""45"" document=""0"" />
<entry offset=""0x1d"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""20"" document=""0"" />
<entry offset=""0x1e"" startLine=""22"" startColumn=""31"" endLine=""22"" endColumn=""46"" document=""0"" />
<entry offset=""0x3c"" hidden=""true"" document=""0"" />
<entry offset=""0x41"" startLine=""22"" startColumn=""22"" endLine=""22"" endColumn=""27"" document=""0"" />
<entry offset=""0x54"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""14"" document=""0"" />
<entry offset=""0x55"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""55"" document=""0"" />
<entry offset=""0x6b"" hidden=""true"" document=""0"" />
<entry offset=""0xdb"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""39"" document=""0"" />
<entry offset=""0xed"" startLine=""26"" startColumn=""13"" endLine=""26"" endColumn=""14"" document=""0"" />
<entry offset=""0xee"" hidden=""true"" document=""0"" />
<entry offset=""0xfc"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""30"" document=""0"" />
<entry offset=""0x116"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""30"" document=""0"" />
<entry offset=""0x11f"" hidden=""true"" document=""0"" />
<entry offset=""0x139"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""0"" />
<entry offset=""0x141"" hidden=""true"" document=""0"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""ConsoleApplication1.Program"" methodName=""ZBar"" />
<await yield=""0x7d"" resume=""0x9c"" declaringType=""ConsoleApplication1.Program+<ZBar>d__3"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "1068894")]
[WorkItem(1137300, "DevDiv")]
[WorkItem(690180, "DevDiv")]
public void TestAsyncDebug3()
{
var text = @"
class TestCase
{
static async void Await(dynamic d)
{
int rez = await d;
}
}";
var compilation = CreateCompilationWithMscorlib45(
text,
options: TestOptions.DebugDll,
references: new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef })
.VerifyDiagnostics();
compilation.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""TestCase"" name=""Await"" parameterNames=""d"">
<customDebugInfo>
<forwardIterator name=""<Await>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""28"" offset=""21"" />
<slot kind=""28"" offset=""21"" ordinal=""1"" />
<slot kind=""28"" offset=""21"" ordinal=""2"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints />
</method>
<method containingType=""TestCase+<Await>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x11"" endOffset=""0x232"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""21"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0x11"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" />
<entry offset=""0x12"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""27"" document=""0"" />
<entry offset=""0xae"" hidden=""true"" document=""0"" />
<entry offset=""0x233"" hidden=""true"" document=""0"" />
<entry offset=""0x24d"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x255"" hidden=""true"" document=""0"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0x233"" />
<kickoffMethod declaringType=""TestCase"" methodName=""Await"" parameterNames=""d"" />
<await yield=""0x148"" resume=""0x190"" declaringType=""TestCase+<Await>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestAsyncDebug4()
{
var text = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await Task.Delay(1);
return 1;
}
}";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(text, options: TestOptions.DebugDll));
v.VerifyIL("C.F", @"
{
// Code size 52 (0x34)
.maxstack 2
.locals init (C.<F>d__0 V_0,
System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> V_1)
IL_0000: newobj ""C.<F>d__0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Create()""
IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0011: ldloc.0
IL_0012: ldc.i4.m1
IL_0013: stfld ""int C.<F>d__0.<>1__state""
IL_0018: ldloc.0
IL_0019: ldfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_001e: stloc.1
IL_001f: ldloca.s V_1
IL_0021: ldloca.s V_0
IL_0023: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Start<C.<F>d__0>(ref C.<F>d__0)""
IL_0028: ldloc.0
IL_0029: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_002e: call ""System.Threading.Tasks.Task<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Task.get""
IL_0033: ret
}",
sequencePoints: "C.F");
v.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 168 (0xa8)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter V_2,
C.<F>d__0 V_3,
System.Exception V_4)
~IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
~IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0048
-IL_000e: nop
-IL_000f: ldc.i4.1
IL_0010: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)""
IL_0015: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()""
IL_001a: stloc.2
~IL_001b: ldloca.s V_2
IL_001d: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get""
IL_0022: brtrue.s IL_0064
IL_0024: ldarg.0
IL_0025: ldc.i4.0
IL_0026: dup
IL_0027: stloc.0
IL_0028: stfld ""int C.<F>d__0.<>1__state""
<IL_002d: ldarg.0
IL_002e: ldloc.2
IL_002f: stfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0034: ldarg.0
IL_0035: stloc.3
IL_0036: ldarg.0
IL_0037: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_003c: ldloca.s V_2
IL_003e: ldloca.s V_3
IL_0040: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.<F>d__0)""
IL_0045: nop
IL_0046: leave.s IL_00a7
>IL_0048: ldarg.0
IL_0049: ldfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_004e: stloc.2
IL_004f: ldarg.0
IL_0050: ldflda ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0055: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_005b: ldarg.0
IL_005c: ldc.i4.m1
IL_005d: dup
IL_005e: stloc.0
IL_005f: stfld ""int C.<F>d__0.<>1__state""
IL_0064: ldloca.s V_2
IL_0066: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_006b: nop
IL_006c: ldloca.s V_2
IL_006e: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
-IL_0074: ldc.i4.1
IL_0075: stloc.1
IL_0076: leave.s IL_0092
}
catch System.Exception
{
~IL_0078: stloc.s V_4
IL_007a: ldarg.0
IL_007b: ldc.i4.s -2
IL_007d: stfld ""int C.<F>d__0.<>1__state""
IL_0082: ldarg.0
IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0088: ldloc.s V_4
IL_008a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_008f: nop
IL_0090: leave.s IL_00a7
}
-IL_0092: ldarg.0
IL_0093: ldc.i4.s -2
IL_0095: stfld ""int C.<F>d__0.<>1__state""
~IL_009a: ldarg.0
IL_009b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00a0: ldloc.1
IL_00a1: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00a6: nop
IL_00a7: ret
}
", sequencePoints: "C+<F>d__0.MoveNext");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DisplayClass_InBetweenSuspensionPoints_Release()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M(int b)
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
await M(x1 + x2 + x3);
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
// TODO: Currently we don't have means necessary to pass information about the display
// class being pushed on evaluation stack, so that EE could find the locals.
// Thus the locals are not available in EE.
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0xa"" hidden=""true"" document=""0"" />
<entry offset=""0x10"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" />
<entry offset=""0x17"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" />
<entry offset=""0x1e"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" />
<entry offset=""0x25"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" />
<entry offset=""0x36"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""31"" document=""0"" />
<entry offset=""0x55"" hidden=""true"" document=""0"" />
<entry offset=""0xab"" hidden=""true"" document=""0"" />
<entry offset=""0xc2"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""0"" />
<entry offset=""0xca"" hidden=""true"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xd6"">
<scope startOffset=""0xa"" endOffset=""0xab"">
<local name=""CS$<>8__locals0"" il_index=""1"" il_start=""0xa"" il_end=""0xab"" attributes=""0"" />
</scope>
</scope>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" parameterNames=""b"" />
<await yield=""0x67"" resume=""0x7e"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""b"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""95"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DisplayClass_InBetweenSuspensionPoints_Debug()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M(int b)
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
await M(x1 + x2 + x3);
// possible EnC edit:
// Console.WriteLine(x1);
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"b",
"<>8__1", // display class
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x10d"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""129"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0x11"" hidden=""true"" document=""0"" />
<entry offset=""0x1c"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0x1d"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" />
<entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" />
<entry offset=""0x35"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" />
<entry offset=""0x41"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" />
<entry offset=""0x58"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""31"" document=""0"" />
<entry offset=""0x86"" hidden=""true"" document=""0"" />
<entry offset=""0xe1"" hidden=""true"" document=""0"" />
<entry offset=""0xf9"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""0"" />
<entry offset=""0x101"" hidden=""true"" document=""0"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" parameterNames=""b"" />
<await yield=""0x98"" resume=""0xb3"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""b"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""95"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DisplayClass_AcrossSuspensionPoints_Release()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M(int b)
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
await Task.Delay(0);
Console.WriteLine(x1);
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<>8__1", // display class
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0xeb"" />
</hoistedLocalScopes>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0xa"" hidden=""true"" document=""0"" />
<entry offset=""0x15"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" />
<entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" />
<entry offset=""0x2d"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" />
<entry offset=""0x39"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" />
<entry offset=""0x4f"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""29"" document=""0"" />
<entry offset=""0x5b"" hidden=""true"" document=""0"" />
<entry offset=""0xaf"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""31"" document=""0"" />
<entry offset=""0xc1"" hidden=""true"" document=""0"" />
<entry offset=""0xd8"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""0"" />
<entry offset=""0xe0"" hidden=""true"" document=""0"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" parameterNames=""b"" />
<await yield=""0x6d"" resume=""0x84"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""b"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""95"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DisplayClass_AcrossSuspensionPoints_Debug()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M(int b)
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
await Task.Delay(0);
Console.WriteLine(x1);
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"b",
"<>8__1", // display class
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0xfc"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""129"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0x11"" hidden=""true"" document=""0"" />
<entry offset=""0x1c"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0x1d"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" />
<entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" />
<entry offset=""0x35"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" />
<entry offset=""0x41"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" />
<entry offset=""0x58"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""29"" document=""0"" />
<entry offset=""0x64"" hidden=""true"" document=""0"" />
<entry offset=""0xbd"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""31"" document=""0"" />
<entry offset=""0xd0"" hidden=""true"" document=""0"" />
<entry offset=""0xe8"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""0"" />
<entry offset=""0xf0"" hidden=""true"" document=""0"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" parameterNames=""b"" />
<await yield=""0x76"" resume=""0x91"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""b"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""95"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DynamicLocal_AcrossSuspensionPoints_Debug()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task M()
{
dynamic d = 1;
await Task.Delay(0);
d.ToString();
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<d>5__1",
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
// CHANGE: Dev12 emits a <dynamiclocal> entry for "d", but gives it slot "-1", preventing it from matching
// any locals when consumed by the EE (i.e. it has no effect). See FUNCBRECEE::IsLocalDynamic.
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x109"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""35"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0xe"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0xf"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" document=""0"" />
<entry offset=""0x1b"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""29"" document=""0"" />
<entry offset=""0x27"" hidden=""true"" document=""0"" />
<entry offset=""0x83"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""22"" document=""0"" />
<entry offset=""0xdd"" hidden=""true"" document=""0"" />
<entry offset=""0xf5"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
<entry offset=""0xfd"" hidden=""true"" document=""0"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" />
<await yield=""0x39"" resume=""0x57"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>
");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[WorkItem(1070519, "DevDiv")]
[Fact]
public void DynamicLocal_InBetweenSuspensionPoints_Release()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task M()
{
dynamic d = 1;
d.ToString();
await Task.Delay(0);
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""d"" />
</dynamicLocals>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0xd"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" document=""0"" />
<entry offset=""0x14"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""22"" document=""0"" />
<entry offset=""0x64"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""0"" />
<entry offset=""0x70"" hidden=""true"" document=""0"" />
<entry offset=""0xc6"" hidden=""true"" document=""0"" />
<entry offset=""0xdd"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
<entry offset=""0xe5"" hidden=""true"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xf1"">
<scope startOffset=""0xd"" endOffset=""0xc6"">
<local name=""d"" il_index=""1"" il_start=""0xd"" il_end=""0xc6"" attributes=""0"" />
</scope>
</scope>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" />
<await yield=""0x82"" resume=""0x99"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
</customDebugInfo>
</method>
</methods>
</symbols>
");
}
[WorkItem(1070519, "DevDiv")]
[Fact]
public void DynamicLocal_InBetweenSuspensionPoints_Debug()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task M()
{
dynamic d = 1;
d.ToString();
await Task.Delay(0);
// Possible EnC edit:
// System.Console.WriteLine(d);
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<d>5__1",
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x109"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""33"" offset=""58"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0x11"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x12"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" document=""0"" />
<entry offset=""0x1e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""22"" document=""0"" />
<entry offset=""0x76"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""0"" />
<entry offset=""0x82"" hidden=""true"" document=""0"" />
<entry offset=""0xdd"" hidden=""true"" document=""0"" />
<entry offset=""0xf5"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""0"" />
<entry offset=""0xfd"" hidden=""true"" document=""0"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""M"" />
<await yield=""0x94"" resume=""0xaf"" declaringType=""C+<M>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>
");
}
[Fact]
public void VariableScopeNotContainingSuspensionPoint()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task M()
{
{
int x = 1;
Console.WriteLine(x);
}
{
await Task.Delay(0);
}
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
// We need to hoist x even though its scope doesn't contain await.
// The scopes may be merged by an EnC edit:
//
// {
// int x = 1;
// Console.WriteLine(x);
// await Task.Delay(0);
// Console.WriteLine(x);
// }
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<x>5__1",
"<>u__1", // awaiter
}, module.GetFieldNames("C.<M>d__0"));
});
}
[Fact]
public void AwaitInFinally()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task<int> G()
{
int x = 42;
try
{
}
finally
{
x = await G();
}
return x;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<x>5__1",
"<>s__2",
"<>s__3",
"<>s__4",
"<>u__1", // awaiter
}, module.GetFieldNames("C.<G>d__0"));
});
v.VerifyPdb("C.G", @"
<symbols>
<methods>
<method containingType=""C"" name=""G"">
<customDebugInfo>
<forwardIterator name=""<G>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""22"" offset=""34"" />
<slot kind=""23"" offset=""34"" />
<slot kind=""28"" offset=""105"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
v.VerifyIL("C.<G>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 286 (0x11e)
.maxstack 3
.locals init (int V_0,
int V_1,
object V_2,
System.Runtime.CompilerServices.TaskAwaiter<int> V_3,
int V_4,
C.<G>d__0 V_5,
System.Exception V_6)
~IL_0000: ldarg.0
IL_0001: ldfld ""int C.<G>d__0.<>1__state""
IL_0006: stloc.0
.try
{
~IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0070
-IL_000e: nop
-IL_000f: ldarg.0
IL_0010: ldc.i4.s 42
IL_0012: stfld ""int C.<G>d__0.<x>5__1""
~IL_0017: ldarg.0
IL_0018: ldnull
IL_0019: stfld ""object C.<G>d__0.<>s__2""
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: stfld ""int C.<G>d__0.<>s__3""
.try
{
-IL_0025: nop
-IL_0026: nop
~IL_0027: leave.s IL_0033
}
catch object
{
~IL_0029: stloc.2
IL_002a: ldarg.0
IL_002b: ldloc.2
IL_002c: stfld ""object C.<G>d__0.<>s__2""
IL_0031: leave.s IL_0033
}
-IL_0033: nop
-IL_0034: call ""System.Threading.Tasks.Task<int> C.G()""
IL_0039: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_003e: stloc.3
~IL_003f: ldloca.s V_3
IL_0041: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_0046: brtrue.s IL_008c
IL_0048: ldarg.0
IL_0049: ldc.i4.0
IL_004a: dup
IL_004b: stloc.0
IL_004c: stfld ""int C.<G>d__0.<>1__state""
<IL_0051: ldarg.0
IL_0052: ldloc.3
IL_0053: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<G>d__0.<>u__1""
IL_0058: ldarg.0
IL_0059: stloc.s V_5
IL_005b: ldarg.0
IL_005c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<G>d__0.<>t__builder""
IL_0061: ldloca.s V_3
IL_0063: ldloca.s V_5
IL_0065: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<G>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<G>d__0)""
IL_006a: nop
IL_006b: leave IL_011d
>IL_0070: ldarg.0
IL_0071: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<G>d__0.<>u__1""
IL_0076: stloc.3
IL_0077: ldarg.0
IL_0078: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<G>d__0.<>u__1""
IL_007d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0083: ldarg.0
IL_0084: ldc.i4.m1
IL_0085: dup
IL_0086: stloc.0
IL_0087: stfld ""int C.<G>d__0.<>1__state""
IL_008c: ldloca.s V_3
IL_008e: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0093: stloc.s V_4
IL_0095: ldloca.s V_3
IL_0097: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_009d: ldarg.0
IL_009e: ldloc.s V_4
IL_00a0: stfld ""int C.<G>d__0.<>s__4""
IL_00a5: ldarg.0
IL_00a6: ldarg.0
IL_00a7: ldfld ""int C.<G>d__0.<>s__4""
IL_00ac: stfld ""int C.<G>d__0.<x>5__1""
-IL_00b1: nop
~IL_00b2: ldarg.0
IL_00b3: ldfld ""object C.<G>d__0.<>s__2""
IL_00b8: stloc.2
IL_00b9: ldloc.2
IL_00ba: brfalse.s IL_00d7
IL_00bc: ldloc.2
IL_00bd: isinst ""System.Exception""
IL_00c2: stloc.s V_6
IL_00c4: ldloc.s V_6
IL_00c6: brtrue.s IL_00ca
IL_00c8: ldloc.2
IL_00c9: throw
IL_00ca: ldloc.s V_6
IL_00cc: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_00d1: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_00d6: nop
IL_00d7: ldarg.0
IL_00d8: ldfld ""int C.<G>d__0.<>s__3""
IL_00dd: pop
IL_00de: ldarg.0
IL_00df: ldnull
IL_00e0: stfld ""object C.<G>d__0.<>s__2""
-IL_00e5: ldarg.0
IL_00e6: ldfld ""int C.<G>d__0.<x>5__1""
IL_00eb: stloc.1
IL_00ec: leave.s IL_0108
}
catch System.Exception
{
~IL_00ee: stloc.s V_6
IL_00f0: ldarg.0
IL_00f1: ldc.i4.s -2
IL_00f3: stfld ""int C.<G>d__0.<>1__state""
IL_00f8: ldarg.0
IL_00f9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<G>d__0.<>t__builder""
IL_00fe: ldloc.s V_6
IL_0100: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_0105: nop
IL_0106: leave.s IL_011d
}
-IL_0108: ldarg.0
IL_0109: ldc.i4.s -2
IL_010b: stfld ""int C.<G>d__0.<>1__state""
~IL_0110: ldarg.0
IL_0111: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<G>d__0.<>t__builder""
IL_0116: ldloc.1
IL_0117: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_011c: nop
IL_011d: ret
}", sequencePoints: "C+<G>d__0.MoveNext");
v.VerifyPdb("C+<G>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<G>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x11d"" />
<slot startOffset=""0x29"" endOffset=""0x32"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""20"" offset=""0"" />
<slot kind=""temp"" />
<slot kind=""33"" offset=""105"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x7"" hidden=""true"" document=""0"" />
<entry offset=""0xe"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0xf"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""0"" />
<entry offset=""0x17"" hidden=""true"" document=""0"" />
<entry offset=""0x25"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""0"" />
<entry offset=""0x26"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""0"" />
<entry offset=""0x27"" hidden=""true"" document=""0"" />
<entry offset=""0x29"" hidden=""true"" document=""0"" />
<entry offset=""0x33"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""0"" />
<entry offset=""0x34"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""27"" document=""0"" />
<entry offset=""0x3f"" hidden=""true"" document=""0"" />
<entry offset=""0xb1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""0"" />
<entry offset=""0xb2"" hidden=""true"" document=""0"" />
<entry offset=""0xe5"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""18"" document=""0"" />
<entry offset=""0xee"" hidden=""true"" document=""0"" />
<entry offset=""0x108"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""0"" />
<entry offset=""0x110"" hidden=""true"" document=""0"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""G"" />
<await yield=""0x51"" resume=""0x70"" declaringType=""C+<G>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
public void HoistedSpilledVariables()
{
string source = @"
using System;
using System.Threading.Tasks;
class C
{
int[] a = new int[] { 1, 2 };
static async Task<int> G()
{
int z0 = H(ref new C().a[F(1)], F(2), ref new C().a[F(3)], await G());
int z1 = H(ref new C().a[F(1)], F(2), ref new C().a[F(3)], await G());
return z0 + z1;
}
static int H(ref int a, int b, ref int c, int d) => 1;
static int F(int a) => a;
}";
var v = CompileAndVerify(CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<z0>5__1",
"<z1>5__2",
"<>s__3",
"<>s__4",
"<>s__5",
"<>s__6",
"<>s__7",
"<>s__8",
"<>s__9",
"<>s__10",
"<>u__1", // awaiter
"<>s__11", // ref-spills
"<>s__12",
"<>s__13",
"<>s__14",
}, module.GetFieldNames("C.<G>d__1"));
});
v.VerifyPdb("C.G", @"
<symbols>
<methods>
<method containingType=""C"" name=""G"">
<customDebugInfo>
<forwardIterator name=""<G>d__1"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""95"" />
<slot kind=""28"" offset=""70"" />
<slot kind=""28"" offset=""70"" ordinal=""1"" />
<slot kind=""28"" offset=""150"" />
<slot kind=""28"" offset=""150"" ordinal=""1"" />
<slot kind=""29"" offset=""70"" />
<slot kind=""29"" offset=""70"" ordinal=""1"" />
<slot kind=""29"" offset=""70"" ordinal=""2"" />
<slot kind=""29"" offset=""70"" ordinal=""3"" />
<slot kind=""29"" offset=""150"" />
<slot kind=""29"" offset=""150"" ordinal=""1"" />
<slot kind=""29"" offset=""150"" ordinal=""2"" />
<slot kind=""29"" offset=""150"" ordinal=""3"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// List View Chart Instance
///<para>SObject Name: ListViewChartInstance</para>
///<para>Custom Object: False</para>
///</summary>
public class SfListViewChartInstance : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "ListViewChartInstance"; }
}
///<summary>
/// List View Chart Instance ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// ListView Chart Instance ID
/// <para>Name: ExternalId</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "externalId")]
[Updateable(false), Createable(false)]
public string ExternalId { get; set; }
///<summary>
/// List View Chart ID
/// <para>Name: ListViewChartId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "listViewChartId")]
[Updateable(false), Createable(false)]
public string ListViewChartId { get; set; }
///<summary>
/// ReferenceTo: ListViewChart
/// <para>RelationshipName: ListViewChart</para>
///</summary>
[JsonProperty(PropertyName = "listViewChart")]
[Updateable(false), Createable(false)]
public SfListViewChart ListViewChart { get; set; }
///<summary>
/// Label
/// <para>Name: Label</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "label")]
[Updateable(false), Createable(false)]
public string Label { get; set; }
///<summary>
/// API Name
/// <para>Name: DeveloperName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "developerName")]
[Updateable(false), Createable(false)]
public string DeveloperName { get; set; }
///<summary>
/// Entity
/// <para>Name: SourceEntity</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "sourceEntity")]
[Updateable(false), Createable(false)]
public string SourceEntity { get; set; }
///<summary>
/// List View ID
/// <para>Name: ListViewContextId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "listViewContextId")]
[Updateable(false), Createable(false)]
public string ListViewContextId { get; set; }
///<summary>
/// ReferenceTo: ListView
/// <para>RelationshipName: ListViewContext</para>
///</summary>
[JsonProperty(PropertyName = "listViewContext")]
[Updateable(false), Createable(false)]
public SfListView ListViewContext { get; set; }
///<summary>
/// TODO, use alias
/// <para>Name: ChartType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "chartType")]
[Updateable(false), Createable(false)]
public string ChartType { get; set; }
///<summary>
/// Last Viewed
/// <para>Name: IsLastViewed</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isLastViewed")]
[Updateable(false), Createable(false)]
public bool? IsLastViewed { get; set; }
///<summary>
/// SOQL Query for Chart Data
/// <para>Name: DataQuery</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "dataQuery")]
[Updateable(false), Createable(false)]
public string DataQuery { get; set; }
///<summary>
/// SOQL Query for Desktop Chart Data without S1 User Filters
/// <para>Name: DataQueryWithoutUserFilters</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "dataQueryWithoutUserFilters")]
[Updateable(false), Createable(false)]
public string DataQueryWithoutUserFilters { get; set; }
///<summary>
/// Editable
/// <para>Name: IsEditable</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isEditable")]
[Updateable(false), Createable(false)]
public bool? IsEditable { get; set; }
///<summary>
/// Deletable
/// <para>Name: IsDeletable</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeletable")]
[Updateable(false), Createable(false)]
public bool? IsDeletable { get; set; }
///<summary>
/// Grouping Field
/// <para>Name: GroupingField</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "groupingField")]
[Updateable(false), Createable(false)]
public string GroupingField { get; set; }
///<summary>
/// Aggregate Field
/// <para>Name: AggregateField</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "aggregateField")]
[Updateable(false), Createable(false)]
public string AggregateField { get; set; }
///<summary>
/// Aggregate Type
/// <para>Name: AggregateType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "aggregateType")]
[Updateable(false), Createable(false)]
public string AggregateType { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Diagnostics;
using System.Security;
using System.ServiceModel;
namespace System.Runtime
{
public static class Fx
{
private const string defaultEventSource = "System.Runtime";
#if DEBUG
private const string AssertsFailFastName = "AssertsFailFast";
private const string BreakOnExceptionTypesName = "BreakOnExceptionTypes";
private const string FastDebugName = "FastDebug";
private const string StealthDebuggerName = "StealthDebugger";
private static bool s_breakOnExceptionTypesRetrieved;
private static Type[] s_breakOnExceptionTypesCache;
#endif
private static ExceptionTrace s_exceptionTrace;
private static EtwDiagnosticTrace s_diagnosticTrace;
[Fx.Tag.SecurityNote(Critical = "This delegate is called from within a ConstrainedExecutionRegion, must not be settable from PT code")]
[SecurityCritical]
private static ExceptionHandler s_asynchronousThreadExceptionHandler;
internal static ExceptionTrace Exception
{
get
{
if (s_exceptionTrace == null)
{
// don't need a lock here since a true singleton is not required
s_exceptionTrace = new ExceptionTrace(defaultEventSource, Trace);
}
return s_exceptionTrace;
}
}
internal static EtwDiagnosticTrace Trace
{
get
{
if (s_diagnosticTrace == null)
{
s_diagnosticTrace = InitializeTracing();
}
return s_diagnosticTrace;
}
}
[Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical field EtwProvider",
Safe = "Doesn't leak info\\resources")]
[SecuritySafeCritical]
[SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule,
Justification = "This is a method that creates ETW provider passing Guid Provider ID.")]
private static EtwDiagnosticTrace InitializeTracing()
{
EtwDiagnosticTrace trace = new EtwDiagnosticTrace(defaultEventSource, EtwDiagnosticTrace.DefaultEtwProviderId);
return trace;
}
public static ExceptionHandler AsynchronousThreadExceptionHandler
{
[Fx.Tag.SecurityNote(Critical = "access critical field", Safe = "ok for get-only access")]
[SecuritySafeCritical]
get
{
return Fx.s_asynchronousThreadExceptionHandler;
}
[Fx.Tag.SecurityNote(Critical = "sets a critical field")]
[SecurityCritical]
set
{
Fx.s_asynchronousThreadExceptionHandler = value;
}
}
// Do not call the parameter "message" or else FxCop thinks it should be localized.
[Conditional("DEBUG")]
public static void Assert(bool condition, string description)
{
if (!condition)
{
Assert(description);
}
}
[Conditional("DEBUG")]
public static void Assert(string description)
{
AssertHelper.FireAssert(description);
}
public static void AssertAndThrow(bool condition, string description)
{
if (!condition)
{
AssertAndThrow(description);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Exception AssertAndThrow(string description)
{
Fx.Assert(description);
TraceCore.ShipAssertExceptionMessage(Trace, description);
throw new InternalException(description);
}
public static void AssertAndThrowFatal(bool condition, string description)
{
if (!condition)
{
AssertAndThrowFatal(description);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Exception AssertAndThrowFatal(string description)
{
Fx.Assert(description);
TraceCore.ShipAssertExceptionMessage(Trace, description);
throw new FatalInternalException(description);
}
public static void AssertAndFailFast(bool condition, string description)
{
if (!condition)
{
AssertAndFailFast(description);
}
}
// This never returns. The Exception return type lets you write 'throw AssertAndFailFast()' which tells the compiler/tools that
// execution stops.
[Fx.Tag.SecurityNote(Critical = "Calls into critical method Environment.FailFast",
Safe = "The side affect of the app crashing is actually intended here")]
[SecuritySafeCritical]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Exception AssertAndFailFast(string description)
{
Fx.Assert(description);
string failFastMessage = InternalSR.FailFastMessage(description);
// The catch is here to force the finally to run, as finallys don't run until the stack walk gets to a catch.
// The catch makes sure that the finally will run before the stack-walk leaves the frame, but the code inside is impossible to reach.
try
{
try
{
Fx.Exception.TraceFailFast(failFastMessage);
}
finally
{
Environment.FailFast(failFastMessage);
}
}
catch
{
throw;
}
return null; // we'll never get here since we've just fail-fasted
}
public static bool IsFatal(Exception exception)
{
while (exception != null)
{
if (exception is FatalException ||
exception is OutOfMemoryException ||
exception is FatalInternalException)
{
return true;
}
// These exceptions aren't themselves fatal, but since the CLR uses them to wrap other exceptions,
// we want to check to see whether they've been used to wrap a fatal exception. If so, then they
// count as fatal.
if (exception is TypeInitializationException ||
exception is TargetInvocationException)
{
exception = exception.InnerException;
}
else if (exception is AggregateException)
{
// AggregateExceptions have a collection of inner exceptions, which may themselves be other
// wrapping exceptions (including nested AggregateExceptions). Recursively walk this
// hierarchy. The (singular) InnerException is included in the collection.
ReadOnlyCollection<Exception> innerExceptions = ((AggregateException)exception).InnerExceptions;
foreach (Exception innerException in innerExceptions)
{
if (IsFatal(innerException))
{
return true;
}
}
break;
}
else
{
break;
}
}
return false;
}
// This method should be only used for debug build.
internal static bool AssertsFailFast
{
get
{
return false;
}
}
// This property should be only used for debug build.
internal static Type[] BreakOnExceptionTypes
{
get
{
#if DEBUG
if (!Fx.s_breakOnExceptionTypesRetrieved)
{
object value;
if (TryGetDebugSwitch(Fx.BreakOnExceptionTypesName, out value))
{
string[] typeNames = value as string[];
if (typeNames != null && typeNames.Length > 0)
{
List<Type> types = new List<Type>(typeNames.Length);
for (int i = 0; i < typeNames.Length; i++)
{
types.Add(Type.GetType(typeNames[i], false));
}
if (types.Count != 0)
{
Fx.s_breakOnExceptionTypesCache = types.ToArray();
}
}
}
Fx.s_breakOnExceptionTypesRetrieved = true;
}
return Fx.s_breakOnExceptionTypesCache;
#else
return null;
#endif
}
}
// This property should be only used for debug build.
internal static bool StealthDebugger
{
get
{
return false;
}
}
#if DEBUG
private static bool TryGetDebugSwitch(string name, out object value)
{
value = null;
return false;
}
#endif
public static AsyncCallback ThunkCallback(AsyncCallback callback)
{
return (new AsyncThunk(callback)).ThunkFrame;
}
[SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule,
Justification = "These are the core methods that should be used for all other Guid(string) calls.")]
public static Guid CreateGuid(string guidString)
{
bool success = false;
Guid result = Guid.Empty;
try
{
result = new Guid(guidString);
success = true;
}
finally
{
if (!success)
{
AssertAndThrow("Creation of the Guid failed.");
}
}
return result;
}
[SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule,
Justification = "These are the core methods that should be used for all other Guid(string) calls.")]
public static bool TryCreateGuid(string guidString, out Guid result)
{
bool success = false;
result = Guid.Empty;
try
{
result = new Guid(guidString);
success = true;
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
return success;
}
public static byte[] AllocateByteArray(int size)
{
try
{
// Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls).
return new byte[size];
}
catch (OutOfMemoryException exception)
{
// Desktop wraps the OOM inside a new InsufficientMemoryException, traces, and then throws it.
// Project N and K trace and throw the original OOM. InsufficientMemoryException does not exist in N and K.
Fx.Exception.AsError(exception);
throw;
}
}
public static char[] AllocateCharArray(int size)
{
try
{
// Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls).
return new char[size];
}
catch (OutOfMemoryException exception)
{
// Desktop wraps the OOM inside a new InsufficientMemoryException, traces, and then throws it.
// Project N and K trace and throw the original OOM. InsufficientMemoryException does not exist in N and K.
Fx.Exception.AsError(exception);
throw;
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes,
Justification = "Don't want to hide the exception which is about to crash the process.")]
[Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")]
private static void TraceExceptionNoThrow(Exception exception)
{
try
{
// This call exits the CER. However, when still inside a catch, normal ThreadAbort is prevented.
// Rude ThreadAbort will still be allowed to terminate processing.
Fx.Exception.TraceUnhandledException(exception);
}
catch
{
// This empty catch is only acceptable because we are a) in a CER and b) processing an exception
// which is about to crash the process anyway.
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes,
Justification = "Don't want to hide the exception which is about to crash the process.")]
[SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.IsFatalRule,
Justification = "Don't want to hide the exception which is about to crash the process.")]
[Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")]
private static bool HandleAtThreadBase(Exception exception)
{
// This area is too sensitive to do anything but return.
if (exception == null)
{
Fx.Assert("Null exception in HandleAtThreadBase.");
return false;
}
TraceExceptionNoThrow(exception);
try
{
ExceptionHandler handler = Fx.AsynchronousThreadExceptionHandler;
return handler == null ? false : handler.HandleException(exception);
}
catch (Exception secondException)
{
// Don't let a new exception hide the original exception.
TraceExceptionNoThrow(secondException);
}
return false;
}
private static void UpdateLevel(EtwDiagnosticTrace trace)
{
if (trace == null)
{
return;
}
if (TraceCore.ActionItemCallbackInvokedIsEnabled(trace) ||
TraceCore.ActionItemScheduledIsEnabled(trace))
{
trace.SetEnd2EndActivityTracingEnabled(true);
}
}
private static void UpdateLevel()
{
UpdateLevel(Fx.Trace);
}
public abstract class ExceptionHandler
{
[Fx.Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")]
public abstract bool HandleException(Exception exception);
}
public static class Tag
{
public enum CacheAttrition
{
None,
ElementOnTimer,
// A finalizer/WeakReference based cache, where the elements are held by WeakReferences (or hold an
// inner object by a WeakReference), and the weakly-referenced object has a finalizer which cleans the
// item from the cache.
ElementOnGC,
// A cache that provides a per-element token, delegate, interface, or other piece of context that can
// be used to remove the element (such as IDisposable).
ElementOnCallback,
FullPurgeOnTimer,
FullPurgeOnEachAccess,
PartialPurgeOnTimer,
PartialPurgeOnEachAccess,
}
public enum ThrottleAction
{
Reject,
Pause,
}
public enum ThrottleMetric
{
Count,
Rate,
Other,
}
public enum Location
{
InProcess,
OutOfProcess,
LocalSystem,
LocalOrRemoteSystem, // as in a file that might live on a share
RemoteSystem,
}
public enum SynchronizationKind
{
LockStatement,
MonitorWait,
MonitorExplicit,
InterlockedNoSpin,
InterlockedWithSpin,
// Same as LockStatement if the field type is object.
FromFieldType,
}
[Flags]
public enum BlocksUsing
{
MonitorEnter,
MonitorWait,
ManualResetEvent,
AutoResetEvent,
AsyncResult,
IAsyncResult,
PInvoke,
InputQueue,
ThreadNeutralSemaphore,
PrivatePrimitive,
OtherInternalPrimitive,
OtherFrameworkPrimitive,
OtherInterop,
Other,
NonBlocking, // For use by non-blocking SynchronizationPrimitives such as IOThreadScheduler
}
public static class Strings
{
internal const string ExternallyManaged = "externally managed";
internal const string AppDomain = "AppDomain";
internal const string DeclaringInstance = "instance of declaring class";
internal const string Unbounded = "unbounded";
internal const string Infinite = "infinite";
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property | AttributeTargets.Class,
AllowMultiple = true, Inherited = false)]
[Conditional("DEBUG")]
public sealed class FriendAccessAllowedAttribute : Attribute
{
public FriendAccessAllowedAttribute(string assemblyName) :
base()
{
this.AssemblyName = assemblyName;
}
public string AssemblyName { get; set; }
}
public static class Throws
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor,
AllowMultiple = true, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class TimeoutAttribute : ThrowsAttribute
{
public TimeoutAttribute() :
this("The operation timed out.")
{
}
public TimeoutAttribute(string diagnosis) :
base(typeof(TimeoutException), diagnosis)
{
}
}
}
[AttributeUsage(AttributeTargets.Field)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class CacheAttribute : Attribute
{
private readonly Type _elementType;
private readonly CacheAttrition _cacheAttrition;
public CacheAttribute(Type elementType, CacheAttrition cacheAttrition)
{
Scope = Strings.DeclaringInstance;
SizeLimit = Strings.Unbounded;
Timeout = Strings.Infinite;
if (elementType == null)
{
throw Fx.Exception.ArgumentNull("elementType");
}
_elementType = elementType;
_cacheAttrition = cacheAttrition;
}
public Type ElementType
{
get
{
return _elementType;
}
}
public CacheAttrition CacheAttrition
{
get
{
return _cacheAttrition;
}
}
public string Scope { get; set; }
public string SizeLimit { get; set; }
public string Timeout { get; set; }
}
[AttributeUsage(AttributeTargets.Field)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class QueueAttribute : Attribute
{
private readonly Type _elementType;
public QueueAttribute(Type elementType)
{
Scope = Strings.DeclaringInstance;
SizeLimit = Strings.Unbounded;
if (elementType == null)
{
throw Fx.Exception.ArgumentNull("elementType");
}
_elementType = elementType;
}
public Type ElementType
{
get
{
return _elementType;
}
}
public string Scope { get; set; }
public string SizeLimit { get; set; }
public bool StaleElementsRemovedImmediately { get; set; }
public bool EnqueueThrowsIfFull { get; set; }
}
[AttributeUsage(AttributeTargets.Field)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class ThrottleAttribute : Attribute
{
private readonly ThrottleAction _throttleAction;
private readonly ThrottleMetric _throttleMetric;
private readonly string _limit;
public ThrottleAttribute(ThrottleAction throttleAction, ThrottleMetric throttleMetric, string limit)
{
Scope = Strings.AppDomain;
if (string.IsNullOrEmpty(limit))
{
throw Fx.Exception.ArgumentNullOrEmpty("limit");
}
_throttleAction = throttleAction;
_throttleMetric = throttleMetric;
_limit = limit;
}
public ThrottleAction ThrottleAction
{
get
{
return _throttleAction;
}
}
public ThrottleMetric ThrottleMetric
{
get
{
return _throttleMetric;
}
}
public string Limit
{
get
{
return _limit;
}
}
public string Scope
{
get; set;
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Constructor,
AllowMultiple = true, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class ExternalResourceAttribute : Attribute
{
private readonly Location _location;
private readonly string _description;
public ExternalResourceAttribute(Location location, string description)
{
_location = location;
_description = description;
}
public Location Location
{
get
{
return _location;
}
}
public string Description
{
get
{
return _description;
}
}
}
// Set on a class when that class uses lock (this) - acts as though it were on a field
// private object this;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Class, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class SynchronizationObjectAttribute : Attribute
{
public SynchronizationObjectAttribute()
{
Blocking = true;
Scope = Strings.DeclaringInstance;
Kind = SynchronizationKind.FromFieldType;
}
public bool Blocking { get; set; }
public string Scope { get; set; }
public SynchronizationKind Kind { get; set; }
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class SynchronizationPrimitiveAttribute : Attribute
{
private readonly BlocksUsing _blocksUsing;
public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing)
{
_blocksUsing = blocksUsing;
}
public BlocksUsing BlocksUsing
{
get
{
return _blocksUsing;
}
}
public bool SupportsAsync { get; set; }
public bool Spins { get; set; }
public string ReleaseMethod { get; set; }
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class BlockingAttribute : Attribute
{
public BlockingAttribute()
{
}
public string CancelMethod { get; set; }
public Type CancelDeclaringType { get; set; }
public string Conditional { get; set; }
}
// Sometime a method will call a conditionally-blocking method in such a way that it is guaranteed
// not to block (i.e. the condition can be Asserted false). Such a method can be marked as
// GuaranteeNonBlocking as an assertion that the method doesn't block despite calling a blocking method.
//
// Methods that don't call blocking methods and aren't marked as Blocking are assumed not to block, so
// they do not require this attribute.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class GuaranteeNonBlockingAttribute : Attribute
{
public GuaranteeNonBlockingAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class NonThrowingAttribute : Attribute
{
public NonThrowingAttribute()
{
}
}
[SuppressMessage(FxCop.Category.Performance, "CA1813:AvoidUnsealedAttributes",
Justification = "This is intended to be an attribute heirarchy. It does not affect product perf.")]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor,
AllowMultiple = true, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public class ThrowsAttribute : Attribute
{
private readonly Type _exceptionType;
private readonly string _diagnosis;
public ThrowsAttribute(Type exceptionType, string diagnosis)
{
if (exceptionType == null)
{
throw Fx.Exception.ArgumentNull("exceptionType");
}
if (string.IsNullOrEmpty(diagnosis))
{
throw Fx.Exception.ArgumentNullOrEmpty("diagnosis");
}
_exceptionType = exceptionType;
_diagnosis = diagnosis;
}
public Type ExceptionType
{
get
{
return _exceptionType;
}
}
public string Diagnosis
{
get
{
return _diagnosis;
}
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class InheritThrowsAttribute : Attribute
{
public InheritThrowsAttribute()
{
}
public Type FromDeclaringType { get; set; }
public string From { get; set; }
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class KnownXamlExternalAttribute : Attribute
{
public KnownXamlExternalAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class XamlVisibleAttribute : Attribute
{
public XamlVisibleAttribute()
: this(true)
{
}
public XamlVisibleAttribute(bool visible)
{
this.Visible = visible;
}
public bool Visible
{
get;
private set;
}
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class |
AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface |
AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
[Conditional("CODE_ANALYSIS_CDF")]
public sealed class SecurityNoteAttribute : Attribute
{
public SecurityNoteAttribute()
{
}
public string Critical
{
get;
set;
}
public string Safe
{
get;
set;
}
public string Miscellaneous
{
get;
set;
}
}
}
internal abstract class Thunk<T> where T : class
{
[Fx.Tag.SecurityNote(Critical = "Make these safe to use in SecurityCritical contexts.")]
[SecurityCritical]
private T _callback;
[Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data provided by caller.")]
[SecuritySafeCritical]
protected Thunk(T callback)
{
_callback = callback;
}
internal T Callback
{
[Fx.Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data is not privileged.")]
[SecuritySafeCritical]
get
{
return _callback;
}
}
}
internal sealed class ActionThunk<T1> : Thunk<Action<T1>>
{
public ActionThunk(Action<T1> callback) : base(callback)
{
}
public Action<T1> ThunkFrame
{
get
{
return new Action<T1>(UnhandledExceptionFrame);
}
}
[Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand",
Safe = "Guaranteed not to call into PT user code from the finally.")]
[SecuritySafeCritical]
private void UnhandledExceptionFrame(T1 result)
{
try
{
Callback(result);
}
catch (Exception exception)
{
if (!Fx.HandleAtThreadBase(exception))
{
throw;
}
}
}
}
internal sealed class AsyncThunk : Thunk<AsyncCallback>
{
public AsyncThunk(AsyncCallback callback) : base(callback)
{
}
public AsyncCallback ThunkFrame
{
get
{
return new AsyncCallback(UnhandledExceptionFrame);
}
}
[Fx.Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand",
Safe = "Guaranteed not to call into PT user code from the finally.")]
[SecuritySafeCritical]
private void UnhandledExceptionFrame(IAsyncResult result)
{
try
{
Callback(result);
}
catch (Exception exception)
{
if (!Fx.HandleAtThreadBase(exception))
{
throw;
}
}
}
}
internal class InternalException : Exception
{
public InternalException(string description)
: base(InternalSR.ShipAssertExceptionMessage(description))
{
}
}
internal class FatalInternalException : InternalException
{
public FatalInternalException(string description)
: base(description)
{
}
}
}
}
| |
namespace KabMan.Forms
{
partial class ConnectionDetailForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
DevExpress.XtraGrid.GridLevelNode gridLevelNode1 = new DevExpress.XtraGrid.GridLevelNode();
this.CDetailView = new DevExpress.XtraGrid.Views.Grid.GridView();
this.gridColumn19 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn21 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn5 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn6 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn20 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn7 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn8 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn9 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn10 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn11 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn22 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn12 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn13 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn25 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn23 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn24 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn14 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn15 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn16 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn17 = new DevExpress.XtraGrid.Columns.GridColumn();
this.CGrid = new DevExpress.XtraGrid.GridControl();
this.CMasterView = new DevExpress.XtraGrid.Views.Grid.GridView();
this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn2 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn3 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn4 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn18 = new DevExpress.XtraGrid.Columns.GridColumn();
this.CDetailContextMenu = new DevExpress.XtraBars.PopupMenu(this.components);
this.itemReservation = new DevExpress.XtraBars.BarButtonItem();
this.itemSwitchUpdate = new DevExpress.XtraBars.BarButtonItem();
this.itemDetailDelete = new DevExpress.XtraBars.BarButtonItem();
this.barManager1 = new DevExpress.XtraBars.BarManager(this.components);
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.itemDelete = new DevExpress.XtraBars.BarButtonItem();
this.itemPrint = new DevExpress.XtraBars.BarButtonItem();
this.CMasterContextMenu = new DevExpress.XtraBars.PopupMenu(this.components);
this.layoutControl2 = new DevExpress.XtraLayout.LayoutControl();
this.DeviceIDLookUp = new KabMan.Controls.C_LookUpDeviceSpecific();
this.layoutControlGroup2 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
((System.ComponentModel.ISupportInitialize)(this.CDetailView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CGrid)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CMasterView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CDetailContextMenu)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CMasterContextMenu)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl2)).BeginInit();
this.layoutControl2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.DeviceIDLookUp.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
this.SuspendLayout();
//
// CDetailView
//
this.CDetailView.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
this.gridColumn19,
this.gridColumn21,
this.gridColumn5,
this.gridColumn6,
this.gridColumn20,
this.gridColumn7,
this.gridColumn8,
this.gridColumn9,
this.gridColumn10,
this.gridColumn11,
this.gridColumn22,
this.gridColumn12,
this.gridColumn13,
this.gridColumn23,
this.gridColumn24,
this.gridColumn25,
this.gridColumn14,
this.gridColumn15,
this.gridColumn16,
this.gridColumn17});
this.CDetailView.GridControl = this.CGrid;
this.CDetailView.Name = "CDetailView";
this.CDetailView.OptionsBehavior.AllowIncrementalSearch = true;
this.CDetailView.OptionsBehavior.Editable = false;
this.CDetailView.OptionsView.ShowGroupPanel = false;
this.CDetailView.OptionsView.ShowIndicator = false;
this.CDetailView.MouseMove += new System.Windows.Forms.MouseEventHandler(this.CDetailView_MouseMove);
this.CDetailView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.CDetailView_MouseDown);
this.CDetailView.ColumnWidthChanged += new DevExpress.XtraGrid.Views.Base.ColumnEventHandler(this.CDetailView_ColumnWidthChanged);
//
// gridColumn19
//
this.gridColumn19.Caption = "Type";
this.gridColumn19.FieldName = "DeviceType";
this.gridColumn19.Name = "gridColumn19";
this.gridColumn19.Visible = true;
this.gridColumn19.VisibleIndex = 0;
this.gridColumn19.Width = 33;
//
// gridColumn21
//
this.gridColumn21.Caption = "Connection Name";
this.gridColumn21.FieldName = "ConnectionName";
this.gridColumn21.Name = "gridColumn21";
this.gridColumn21.Visible = true;
this.gridColumn21.VisibleIndex = 1;
this.gridColumn21.Width = 53;
//
// gridColumn5
//
this.gridColumn5.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn5.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn5.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn5.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn5.Caption = "Server Name";
this.gridColumn5.FieldName = "ServerName";
this.gridColumn5.Name = "gridColumn5";
this.gridColumn5.Visible = true;
this.gridColumn5.VisibleIndex = 2;
this.gridColumn5.Width = 44;
//
// gridColumn6
//
this.gridColumn6.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn6.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn6.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn6.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn6.Caption = "Rack";
this.gridColumn6.FieldName = "Rack";
this.gridColumn6.Name = "gridColumn6";
this.gridColumn6.Visible = true;
this.gridColumn6.VisibleIndex = 4;
this.gridColumn6.Width = 42;
//
// gridColumn20
//
this.gridColumn20.Caption = "Port";
this.gridColumn20.FieldName = "Port";
this.gridColumn20.Name = "gridColumn20";
this.gridColumn20.Visible = true;
this.gridColumn20.VisibleIndex = 3;
this.gridColumn20.Width = 53;
//
// gridColumn7
//
this.gridColumn7.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn7.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn7.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn7.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn7.Caption = "LCURM";
this.gridColumn7.FieldName = "LCURM";
this.gridColumn7.Name = "gridColumn7";
this.gridColumn7.Visible = true;
this.gridColumn7.VisibleIndex = 5;
this.gridColumn7.Width = 42;
//
// gridColumn8
//
this.gridColumn8.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn8.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn8.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn8.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn8.Caption = "Blech";
this.gridColumn8.FieldName = "Blech";
this.gridColumn8.Name = "gridColumn8";
this.gridColumn8.Visible = true;
this.gridColumn8.VisibleIndex = 6;
this.gridColumn8.Width = 42;
//
// gridColumn9
//
this.gridColumn9.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn9.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn9.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn9.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn9.Caption = "Trunk";
this.gridColumn9.FieldName = "Trunk";
this.gridColumn9.Name = "gridColumn9";
this.gridColumn9.Visible = true;
this.gridColumn9.VisibleIndex = 7;
this.gridColumn9.Width = 42;
//
// gridColumn10
//
this.gridColumn10.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn10.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn10.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn10.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn10.Caption = "VTPort";
this.gridColumn10.FieldName = "VTPort";
this.gridColumn10.Name = "gridColumn10";
this.gridColumn10.Visible = true;
this.gridColumn10.VisibleIndex = 8;
this.gridColumn10.Width = 42;
//
// gridColumn11
//
this.gridColumn11.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn11.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn11.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn11.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn11.Caption = "UrmUrm";
this.gridColumn11.FieldName = "UrmUrm";
this.gridColumn11.Name = "gridColumn11";
this.gridColumn11.Visible = true;
this.gridColumn11.VisibleIndex = 9;
this.gridColumn11.Width = 46;
//
// gridColumn22
//
this.gridColumn22.Caption = "UrmUrm1";
this.gridColumn22.FieldName = "UrmUrm1";
this.gridColumn22.Name = "gridColumn22";
this.gridColumn22.Visible = true;
this.gridColumn22.VisibleIndex = 10;
this.gridColumn22.Width = 66;
//
// gridColumn12
//
this.gridColumn12.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn12.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn12.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn12.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn12.Caption = "VTPort1";
this.gridColumn12.FieldName = "VTPort1";
this.gridColumn12.Name = "gridColumn12";
this.gridColumn12.Visible = true;
this.gridColumn12.VisibleIndex = 13;
this.gridColumn12.Width = 51;
//
// gridColumn13
//
this.gridColumn13.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn13.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn13.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn13.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn13.Caption = "Trunk";
this.gridColumn13.FieldName = "Trunk1";
this.gridColumn13.Name = "gridColumn13";
this.gridColumn13.Visible = true;
this.gridColumn13.VisibleIndex = 12;
this.gridColumn13.Width = 40;
//
// gridColumn25
//
this.gridColumn25.Caption = "VTPort";
this.gridColumn25.FieldName = "VTPort3";
this.gridColumn25.Name = "gridColumn25";
this.gridColumn25.Visible = true;
this.gridColumn25.VisibleIndex = 15;
//
// gridColumn23
//
this.gridColumn23.Caption = "VTPort2";
this.gridColumn23.FieldName = "VTPort2";
this.gridColumn23.Name = "gridColumn23";
this.gridColumn23.Visible = true;
this.gridColumn23.VisibleIndex = 11;
//
// gridColumn24
//
this.gridColumn24.Caption = "UrmUrm2";
this.gridColumn24.FieldName = "UrmUrm2";
this.gridColumn24.Name = "gridColumn24";
this.gridColumn24.Visible = true;
this.gridColumn24.VisibleIndex = 14;
//
// gridColumn14
//
this.gridColumn14.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn14.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn14.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn14.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn14.Caption = "Blech";
this.gridColumn14.FieldName = "Blech1";
this.gridColumn14.Name = "gridColumn14";
this.gridColumn14.Visible = true;
this.gridColumn14.VisibleIndex = 16;
this.gridColumn14.Width = 40;
//
// gridColumn15
//
this.gridColumn15.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn15.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn15.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn15.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn15.Caption = "LCURM";
this.gridColumn15.FieldName = "LCURM1";
this.gridColumn15.Name = "gridColumn15";
this.gridColumn15.Visible = true;
this.gridColumn15.VisibleIndex = 17;
this.gridColumn15.Width = 40;
//
// gridColumn16
//
this.gridColumn16.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn16.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn16.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn16.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn16.Caption = "PortNo";
this.gridColumn16.FieldName = "PortNo";
this.gridColumn16.Name = "gridColumn16";
this.gridColumn16.Visible = true;
this.gridColumn16.VisibleIndex = 18;
this.gridColumn16.Width = 40;
//
// gridColumn17
//
this.gridColumn17.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn17.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn17.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn17.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn17.Caption = "Switch Name";
this.gridColumn17.FieldName = "Switch";
this.gridColumn17.Name = "gridColumn17";
this.gridColumn17.Visible = true;
this.gridColumn17.VisibleIndex = 19;
this.gridColumn17.Width = 90;
//
// CGrid
//
gridLevelNode1.LevelTemplate = this.CDetailView;
gridLevelNode1.RelationName = "Level1";
this.CGrid.LevelTree.Nodes.AddRange(new DevExpress.XtraGrid.GridLevelNode[] {
gridLevelNode1});
this.CGrid.Location = new System.Drawing.Point(7, 38);
this.CGrid.MainView = this.CMasterView;
this.CGrid.Name = "CGrid";
this.CGrid.ShowOnlyPredefinedDetails = true;
this.CGrid.Size = new System.Drawing.Size(810, 472);
this.CGrid.TabIndex = 4;
this.CGrid.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] {
this.CMasterView,
this.CDetailView});
this.CGrid.DragOver += new System.Windows.Forms.DragEventHandler(this.CGrid_DragOver);
this.CGrid.DragDrop += new System.Windows.Forms.DragEventHandler(this.CGrid_DragDrop);
this.CGrid.FocusedViewChanged += new DevExpress.XtraGrid.ViewFocusEventHandler(this.CGrid_FocusedViewChanged);
//
// CMasterView
//
this.CMasterView.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver;
this.CMasterView.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.CMasterView.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver;
this.CMasterView.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray;
this.CMasterView.Appearance.ColumnFilterButton.Options.UseBackColor = true;
this.CMasterView.Appearance.ColumnFilterButton.Options.UseBorderColor = true;
this.CMasterView.Appearance.ColumnFilterButton.Options.UseForeColor = true;
this.CMasterView.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.CMasterView.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.CMasterView.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.CMasterView.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue;
this.CMasterView.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true;
this.CMasterView.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true;
this.CMasterView.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true;
this.CMasterView.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.CMasterView.Appearance.Empty.Options.UseBackColor = true;
this.CMasterView.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.CMasterView.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite;
this.CMasterView.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black;
this.CMasterView.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.CMasterView.Appearance.EvenRow.Options.UseBackColor = true;
this.CMasterView.Appearance.EvenRow.Options.UseForeColor = true;
this.CMasterView.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CMasterView.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225)))));
this.CMasterView.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CMasterView.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black;
this.CMasterView.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.CMasterView.Appearance.FilterCloseButton.Options.UseBackColor = true;
this.CMasterView.Appearance.FilterCloseButton.Options.UseBorderColor = true;
this.CMasterView.Appearance.FilterCloseButton.Options.UseForeColor = true;
this.CMasterView.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135)))));
this.CMasterView.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CMasterView.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White;
this.CMasterView.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.CMasterView.Appearance.FilterPanel.Options.UseBackColor = true;
this.CMasterView.Appearance.FilterPanel.Options.UseForeColor = true;
this.CMasterView.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58)))));
this.CMasterView.Appearance.FixedLine.Options.UseBackColor = true;
this.CMasterView.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225)))));
this.CMasterView.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black;
this.CMasterView.Appearance.FocusedCell.Options.UseBackColor = true;
this.CMasterView.Appearance.FocusedCell.Options.UseForeColor = true;
this.CMasterView.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy;
this.CMasterView.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178)))));
this.CMasterView.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White;
this.CMasterView.Appearance.FocusedRow.Options.UseBackColor = true;
this.CMasterView.Appearance.FocusedRow.Options.UseForeColor = true;
this.CMasterView.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver;
this.CMasterView.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver;
this.CMasterView.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black;
this.CMasterView.Appearance.FooterPanel.Options.UseBackColor = true;
this.CMasterView.Appearance.FooterPanel.Options.UseBorderColor = true;
this.CMasterView.Appearance.FooterPanel.Options.UseForeColor = true;
this.CMasterView.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver;
this.CMasterView.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver;
this.CMasterView.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black;
this.CMasterView.Appearance.GroupButton.Options.UseBackColor = true;
this.CMasterView.Appearance.GroupButton.Options.UseBorderColor = true;
this.CMasterView.Appearance.GroupButton.Options.UseForeColor = true;
this.CMasterView.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.CMasterView.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.CMasterView.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black;
this.CMasterView.Appearance.GroupFooter.Options.UseBackColor = true;
this.CMasterView.Appearance.GroupFooter.Options.UseBorderColor = true;
this.CMasterView.Appearance.GroupFooter.Options.UseForeColor = true;
this.CMasterView.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165)))));
this.CMasterView.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White;
this.CMasterView.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.CMasterView.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White;
this.CMasterView.Appearance.GroupPanel.Options.UseBackColor = true;
this.CMasterView.Appearance.GroupPanel.Options.UseFont = true;
this.CMasterView.Appearance.GroupPanel.Options.UseForeColor = true;
this.CMasterView.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray;
this.CMasterView.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver;
this.CMasterView.Appearance.GroupRow.Options.UseBackColor = true;
this.CMasterView.Appearance.GroupRow.Options.UseForeColor = true;
this.CMasterView.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver;
this.CMasterView.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver;
this.CMasterView.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.CMasterView.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black;
this.CMasterView.Appearance.HeaderPanel.Options.UseBackColor = true;
this.CMasterView.Appearance.HeaderPanel.Options.UseBorderColor = true;
this.CMasterView.Appearance.HeaderPanel.Options.UseFont = true;
this.CMasterView.Appearance.HeaderPanel.Options.UseForeColor = true;
this.CMasterView.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray;
this.CMasterView.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CMasterView.Appearance.HideSelectionRow.Options.UseBackColor = true;
this.CMasterView.Appearance.HideSelectionRow.Options.UseForeColor = true;
this.CMasterView.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver;
this.CMasterView.Appearance.HorzLine.Options.UseBackColor = true;
this.CMasterView.Appearance.OddRow.BackColor = System.Drawing.Color.White;
this.CMasterView.Appearance.OddRow.BackColor2 = System.Drawing.Color.White;
this.CMasterView.Appearance.OddRow.ForeColor = System.Drawing.Color.Black;
this.CMasterView.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal;
this.CMasterView.Appearance.OddRow.Options.UseBackColor = true;
this.CMasterView.Appearance.OddRow.Options.UseForeColor = true;
this.CMasterView.Appearance.Preview.BackColor = System.Drawing.Color.White;
this.CMasterView.Appearance.Preview.ForeColor = System.Drawing.Color.Navy;
this.CMasterView.Appearance.Preview.Options.UseBackColor = true;
this.CMasterView.Appearance.Preview.Options.UseForeColor = true;
this.CMasterView.Appearance.Row.BackColor = System.Drawing.Color.White;
this.CMasterView.Appearance.Row.ForeColor = System.Drawing.Color.Black;
this.CMasterView.Appearance.Row.Options.UseBackColor = true;
this.CMasterView.Appearance.Row.Options.UseForeColor = true;
this.CMasterView.Appearance.RowSeparator.BackColor = System.Drawing.Color.White;
this.CMasterView.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.CMasterView.Appearance.RowSeparator.Options.UseBackColor = true;
this.CMasterView.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138)))));
this.CMasterView.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White;
this.CMasterView.Appearance.SelectedRow.Options.UseBackColor = true;
this.CMasterView.Appearance.SelectedRow.Options.UseForeColor = true;
this.CMasterView.Appearance.VertLine.BackColor = System.Drawing.Color.Silver;
this.CMasterView.Appearance.VertLine.Options.UseBackColor = true;
this.CMasterView.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
this.gridColumn1,
this.gridColumn2,
this.gridColumn3,
this.gridColumn4,
this.gridColumn18});
this.CMasterView.GridControl = this.CGrid;
this.CMasterView.Name = "CMasterView";
this.CMasterView.OptionsBehavior.Editable = false;
this.CMasterView.OptionsView.EnableAppearanceEvenRow = true;
this.CMasterView.OptionsView.EnableAppearanceOddRow = true;
this.CMasterView.OptionsView.ShowAutoFilterRow = true;
this.CMasterView.OptionsView.ShowGroupPanel = false;
this.CMasterView.OptionsView.ShowIndicator = false;
this.CMasterView.MasterRowExpanded += new DevExpress.XtraGrid.Views.Grid.CustomMasterRowEventHandler(this.CMasterView_MasterRowExpanded);
this.CMasterView.ColumnWidthChanged += new DevExpress.XtraGrid.Views.Base.ColumnEventHandler(this.CMasterView_ColumnWidthChanged);
this.CMasterView.ShowGridMenu += new DevExpress.XtraGrid.Views.Grid.GridMenuEventHandler(this.CMasterView_ShowGridMenu);
//
// gridColumn1
//
this.gridColumn1.Caption = "Name";
this.gridColumn1.FieldName = "Name";
this.gridColumn1.Name = "gridColumn1";
this.gridColumn1.Visible = true;
this.gridColumn1.VisibleIndex = 0;
//
// gridColumn2
//
this.gridColumn2.Caption = "Connection Name";
this.gridColumn2.FieldName = "ConnectionName";
this.gridColumn2.Name = "gridColumn2";
this.gridColumn2.Visible = true;
this.gridColumn2.VisibleIndex = 1;
//
// gridColumn3
//
this.gridColumn3.Caption = "Project Name";
this.gridColumn3.FieldName = "ProjectName";
this.gridColumn3.Name = "gridColumn3";
this.gridColumn3.Visible = true;
this.gridColumn3.VisibleIndex = 2;
//
// gridColumn4
//
this.gridColumn4.Caption = "Customer";
this.gridColumn4.FieldName = "Customer";
this.gridColumn4.Name = "gridColumn4";
this.gridColumn4.Visible = true;
this.gridColumn4.VisibleIndex = 3;
//
// gridColumn18
//
this.gridColumn18.Caption = "ID";
this.gridColumn18.FieldName = "ID";
this.gridColumn18.Name = "gridColumn18";
//
// CDetailContextMenu
//
this.CDetailContextMenu.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.itemReservation),
new DevExpress.XtraBars.LinkPersistInfo(this.itemSwitchUpdate),
new DevExpress.XtraBars.LinkPersistInfo(this.itemDetailDelete)});
this.CDetailContextMenu.Manager = this.barManager1;
this.CDetailContextMenu.Name = "CDetailContextMenu";
//
// itemReservation
//
this.itemReservation.Caption = "Reservation";
this.itemReservation.Id = 0;
this.itemReservation.Name = "itemReservation";
this.itemReservation.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemReservation_ItemClick);
//
// itemSwitchUpdate
//
this.itemSwitchUpdate.Caption = "Switch Update";
this.itemSwitchUpdate.Id = 4;
this.itemSwitchUpdate.Name = "itemSwitchUpdate";
this.itemSwitchUpdate.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemSwitchUpdate_ItemClick);
//
// itemDetailDelete
//
this.itemDetailDelete.Caption = "Delete";
this.itemDetailDelete.Id = 1;
this.itemDetailDelete.Name = "itemDetailDelete";
this.itemDetailDelete.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemDetailDelete_ItemClick);
//
// barManager1
//
this.barManager1.DockControls.Add(this.barDockControlTop);
this.barManager1.DockControls.Add(this.barDockControlBottom);
this.barManager1.DockControls.Add(this.barDockControlLeft);
this.barManager1.DockControls.Add(this.barDockControlRight);
this.barManager1.Form = this;
this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.itemReservation,
this.itemDetailDelete,
this.itemDelete,
this.itemPrint,
this.itemSwitchUpdate});
this.barManager1.MaxItemId = 5;
//
// itemDelete
//
this.itemDelete.Caption = "Delete";
this.itemDelete.Id = 2;
this.itemDelete.Name = "itemDelete";
this.itemDelete.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemDelete_ItemClick);
//
// itemPrint
//
this.itemPrint.Caption = "Print";
this.itemPrint.Id = 3;
this.itemPrint.Name = "itemPrint";
this.itemPrint.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemPrint_ItemClick);
//
// CMasterContextMenu
//
this.CMasterContextMenu.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.itemDelete),
new DevExpress.XtraBars.LinkPersistInfo(this.itemPrint)});
this.CMasterContextMenu.Manager = this.barManager1;
this.CMasterContextMenu.Name = "CMasterContextMenu";
//
// layoutControl2
//
this.layoutControl2.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl2.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl2.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl2.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl2.Controls.Add(this.DeviceIDLookUp);
this.layoutControl2.Controls.Add(this.CGrid);
this.layoutControl2.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl2.Location = new System.Drawing.Point(0, 0);
this.layoutControl2.Name = "layoutControl2";
this.layoutControl2.Root = this.layoutControlGroup2;
this.layoutControl2.Size = new System.Drawing.Size(823, 516);
this.layoutControl2.TabIndex = 6;
this.layoutControl2.Text = "layoutControl2";
//
// DeviceIDLookUp
//
this.DeviceIDLookUp.Location = new System.Drawing.Point(44, 7);
this.DeviceIDLookUp.MenuManager = this.barManager1;
this.DeviceIDLookUp.Name = "DeviceIDLookUp";
this.DeviceIDLookUp.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo),
new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo),
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")});
this.DeviceIDLookUp.Properties.NullText = "Select Device!";
this.DeviceIDLookUp.Size = new System.Drawing.Size(773, 20);
this.DeviceIDLookUp.StyleController = this.layoutControl2;
this.DeviceIDLookUp.TabIndex = 5;
this.DeviceIDLookUp.EditValueChanged += new System.EventHandler(this.c_LookUpDeviceSpecific1_EditValueChanged);
//
// layoutControlGroup2
//
this.layoutControlGroup2.CustomizationFormText = "layoutControlGroup1";
this.layoutControlGroup2.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1,
this.layoutControlItem2});
this.layoutControlGroup2.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup2.Name = "layoutControlGroup1";
this.layoutControlGroup2.Size = new System.Drawing.Size(823, 516);
this.layoutControlGroup2.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup2.Text = "layoutControlGroup1";
this.layoutControlGroup2.TextVisible = false;
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.CGrid;
this.layoutControlItem1.CustomizationFormText = "layoutControlItem1";
this.layoutControlItem1.Location = new System.Drawing.Point(0, 31);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(821, 483);
this.layoutControlItem1.Text = "layoutControlItem1";
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem1.TextToControlDistance = 0;
this.layoutControlItem1.TextVisible = false;
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.DeviceIDLookUp;
this.layoutControlItem2.CustomizationFormText = "Device";
this.layoutControlItem2.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem2.MaxSize = new System.Drawing.Size(0, 31);
this.layoutControlItem2.MinSize = new System.Drawing.Size(98, 31);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(821, 31);
this.layoutControlItem2.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
this.layoutControlItem2.Text = "Device";
this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem2.TextSize = new System.Drawing.Size(32, 13);
//
// ConnectionDetailForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(823, 516);
this.Controls.Add(this.layoutControl2);
this.Controls.Add(this.barDockControlLeft);
this.Controls.Add(this.barDockControlRight);
this.Controls.Add(this.barDockControlBottom);
this.Controls.Add(this.barDockControlTop);
this.Name = "ConnectionDetailForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Connection List";
this.Load += new System.EventHandler(this.ConnectionDetailForm_Load);
((System.ComponentModel.ISupportInitialize)(this.CDetailView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CGrid)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CMasterView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CDetailContextMenu)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CMasterContextMenu)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl2)).EndInit();
this.layoutControl2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.DeviceIDLookUp.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraBars.PopupMenu CDetailContextMenu;
private DevExpress.XtraBars.PopupMenu CMasterContextMenu;
private DevExpress.XtraGrid.GridControl CGrid;
private DevExpress.XtraGrid.Views.Grid.GridView CMasterView;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn1;
private DevExpress.XtraGrid.Views.Grid.GridView CDetailView;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn2;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn3;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn4;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn5;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn6;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn7;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn8;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn9;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn10;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn11;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn12;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn13;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn14;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn15;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn16;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn17;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn18;
private DevExpress.XtraBars.BarManager barManager1;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraBars.BarButtonItem itemReservation;
private DevExpress.XtraBars.BarButtonItem itemDetailDelete;
private DevExpress.XtraBars.BarButtonItem itemDelete;
private DevExpress.XtraBars.BarButtonItem itemPrint;
private DevExpress.XtraLayout.LayoutControl layoutControl2;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup2;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private KabMan.Controls.C_LookUpDeviceSpecific DeviceIDLookUp;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn19;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn20;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn21;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn22;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn23;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn24;
private DevExpress.XtraBars.BarButtonItem itemSwitchUpdate;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn25;
}
}
| |
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 ArmorDemoWeb.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;
}
}
}
| |
namespace Fixtures.SwaggerBatBodyComplex
{
using System;
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 Models;
internal partial class Polymorphicrecursive : IServiceOperations<AutoRestComplexTestService>, IPolymorphicrecursive
{
/// <summary>
/// Initializes a new instance of the Polymorphicrecursive class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal Polymorphicrecursive(AutoRestComplexTestService client)
{
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestComplexTestService
/// </summary>
public AutoRestComplexTestService Client { get; private set; }
/// <summary>
/// Get complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<Fish>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetValid", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//complex/polymorphicrecursive/valid";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<Fish>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Fish>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// "dtype": "salmon",
/// "species": "king",
/// "length": 1,
/// "age": 1,
/// "location": "alaska",
/// "iswild": true,
/// "siblings": [
/// {
/// "dtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6,
/// "siblings": [
/// {
/// "dtype": "salmon",
/// "species": "coho",
/// "length": 2,
/// "age": 2,
/// "location": "atlantic",
/// "iswild": true,
/// "siblings": [
/// {
/// "dtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "dtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "dtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "dtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//complex/polymorphicrecursive/valid";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
using System.IO;
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\fieldToRGrid.tcl
// output file is AVfieldToRGrid.cs
/// <summary>
/// The testing class derived from AVfieldToRGrid
/// </summary>
public class AVfieldToRGridClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVfieldToRGrid(String [] argv)
{
//Prefix Content is: ""
//# Generate a rectilinear grid from a field.[]
//#[]
// get the interactor ui[]
// Create a reader and write out the field[]
reader = new vtkDataSetReader();
reader.SetFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/RectGrid2.vtk");
ds2do = new vtkDataSetToDataObjectFilter();
ds2do.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort());
try
{
channel = new StreamWriter("RGridField.vtk");
tryCatchError = "NOERROR";
}
catch(Exception)
{tryCatchError = "ERROR";}
if(tryCatchError.Equals("NOERROR"))
{
channel.Close();
writer = new vtkDataObjectWriter();
writer.SetInputConnection((vtkAlgorithmOutput)ds2do.GetOutputPort());
writer.SetFileName((string)"RGridField.vtk");
writer.Write();
// Read the field[]
//[]
dor = new vtkDataObjectReader();
dor.SetFileName((string)"RGridField.vtk");
do2ds = new vtkDataObjectToDataSetFilter();
do2ds.SetInputConnection((vtkAlgorithmOutput)dor.GetOutputPort());
do2ds.SetDataSetTypeToRectilinearGrid();
do2ds.SetDimensionsComponent((string)"Dimensions",(int)0);
do2ds.SetPointComponent((int)0,(string)"XCoordinates",(int)0);
do2ds.SetPointComponent((int)1,(string)"YCoordinates",(int)0);
do2ds.SetPointComponent((int)2,(string)"ZCoordinates",(int)0);
do2ds.Update();
fd2ad = new vtkFieldDataToAttributeDataFilter();
fd2ad.SetInputData((vtkDataObject)do2ds.GetRectilinearGridOutput());
fd2ad.SetInputFieldToDataObjectField();
fd2ad.SetOutputAttributeDataToPointData();
fd2ad.SetVectorComponent((int)0,(string)"vectors",(int)0);
fd2ad.SetVectorComponent((int)1,(string)"vectors",(int)1);
fd2ad.SetVectorComponent((int)2,(string)"vectors",(int)2);
fd2ad.SetScalarComponent((int)0,(string)"scalars",(int)0);
fd2ad.Update();
// create pipeline[]
//[]
plane = new vtkRectilinearGridGeometryFilter();
plane.SetInputData((vtkDataObject)fd2ad.GetRectilinearGridOutput());
plane.SetExtent((int)0,(int)100,(int)0,(int)100,(int)15,(int)15);
warper = new vtkWarpVector();
warper.SetInputConnection((vtkAlgorithmOutput)plane.GetOutputPort());
warper.SetScaleFactor((double)0.05);
planeMapper = new vtkDataSetMapper();
planeMapper.SetInputConnection((vtkAlgorithmOutput)warper.GetOutputPort());
planeMapper.SetScalarRange((double)0.197813,(double)0.710419);
planeActor = new vtkActor();
planeActor.SetMapper((vtkMapper)planeMapper);
cutPlane = new vtkPlane();
cutPlane.SetOrigin(fd2ad.GetOutput().GetCenter()[0],fd2ad.GetOutput().GetCenter()[1],fd2ad.GetOutput().GetCenter()[2]);
cutPlane.SetNormal((double)1,(double)0,(double)0);
planeCut = new vtkCutter();
planeCut.SetInputData((vtkDataObject)fd2ad.GetRectilinearGridOutput());
planeCut.SetCutFunction((vtkImplicitFunction)cutPlane);
cutMapper = new vtkDataSetMapper();
cutMapper.SetInputConnection((vtkAlgorithmOutput)planeCut.GetOutputPort());
cutMapper.SetScalarRange(
(double)((vtkDataSet)fd2ad.GetOutput()).GetPointData().GetScalars().GetRange()[0],
(double)((vtkDataSet)fd2ad.GetOutput()).GetPointData().GetScalars().GetRange()[1]);
cutActor = new vtkActor();
cutActor.SetMapper((vtkMapper)cutMapper);
iso = new vtkContourFilter();
iso.SetInputData((vtkDataObject)fd2ad.GetRectilinearGridOutput());
iso.SetValue((int)0,(double)0.7);
normals = new vtkPolyDataNormals();
normals.SetInputConnection((vtkAlgorithmOutput)iso.GetOutputPort());
normals.SetFeatureAngle((double)45);
isoMapper = vtkPolyDataMapper.New();
isoMapper.SetInputConnection((vtkAlgorithmOutput)normals.GetOutputPort());
isoMapper.ScalarVisibilityOff();
isoActor = new vtkActor();
isoActor.SetMapper((vtkMapper)isoMapper);
isoActor.GetProperty().SetColor((double) 1.0000, 0.8941, 0.7686 );
isoActor.GetProperty().SetRepresentationToWireframe();
streamer = new vtkStreamLine();
streamer.SetInputConnection((vtkAlgorithmOutput)fd2ad.GetOutputPort());
streamer.SetStartPosition((double)-1.2,(double)-0.1,(double)1.3);
streamer.SetMaximumPropagationTime((double)500);
streamer.SetStepLength((double)0.05);
streamer.SetIntegrationStepLength((double)0.05);
streamer.SetIntegrationDirectionToIntegrateBothDirections();
streamTube = new vtkTubeFilter();
streamTube.SetInputConnection((vtkAlgorithmOutput)streamer.GetOutputPort());
streamTube.SetRadius((double)0.025);
streamTube.SetNumberOfSides((int)6);
streamTube.SetVaryRadiusToVaryRadiusByVector();
mapStreamTube = vtkPolyDataMapper.New();
mapStreamTube.SetInputConnection((vtkAlgorithmOutput)streamTube.GetOutputPort());
mapStreamTube.SetScalarRange(
(double)((vtkDataSet)fd2ad.GetOutput()).GetPointData().GetScalars().GetRange()[0],
(double)((vtkDataSet)fd2ad.GetOutput()).GetPointData().GetScalars().GetRange()[1]);
streamTubeActor = new vtkActor();
streamTubeActor.SetMapper((vtkMapper)mapStreamTube);
streamTubeActor.GetProperty().BackfaceCullingOn();
outline = new vtkOutlineFilter();
outline.SetInputData((vtkDataObject)fd2ad.GetRectilinearGridOutput());
outlineMapper = vtkPolyDataMapper.New();
outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort());
outlineActor = new vtkActor();
outlineActor.SetMapper((vtkMapper)outlineMapper);
outlineActor.GetProperty().SetColor((double) 0.0000, 0.0000, 0.0000 );
// Graphics stuff[]
// Create the RenderWindow, Renderer and both Actors[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.SetMultiSamples(0);
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
// Add the actors to the renderer, set the background and size[]
//[]
ren1.AddActor((vtkProp)outlineActor);
ren1.AddActor((vtkProp)planeActor);
ren1.AddActor((vtkProp)cutActor);
ren1.AddActor((vtkProp)isoActor);
ren1.AddActor((vtkProp)streamTubeActor);
ren1.SetBackground((double)1,(double)1,(double)1);
renWin.SetSize((int)300,(int)300);
ren1.GetActiveCamera().SetPosition((double)0.0390893,(double)0.184813,(double)-3.94026);
ren1.GetActiveCamera().SetFocalPoint((double)-0.00578326,(double)0,(double)0.701967);
ren1.GetActiveCamera().SetViewAngle((double)30);
ren1.GetActiveCamera().SetViewUp((double)0.00850257,(double)0.999169,(double)0.0398605);
ren1.GetActiveCamera().SetClippingRange((double)3.08127,(double)6.62716);
iren.Initialize();
// render the image[]
//[]
File.Delete("RGridField.vtk");
}
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkDataSetReader reader;
static vtkDataSetToDataObjectFilter ds2do;
static string tryCatchError;
static StreamWriter channel;
static vtkDataObjectWriter writer;
static vtkDataObjectReader dor;
static vtkDataObjectToDataSetFilter do2ds;
static vtkFieldDataToAttributeDataFilter fd2ad;
static vtkRectilinearGridGeometryFilter plane;
static vtkWarpVector warper;
static vtkDataSetMapper planeMapper;
static vtkActor planeActor;
static vtkPlane cutPlane;
static vtkCutter planeCut;
static vtkDataSetMapper cutMapper;
static vtkActor cutActor;
static vtkContourFilter iso;
static vtkPolyDataNormals normals;
static vtkPolyDataMapper isoMapper;
static vtkActor isoActor;
static vtkStreamLine streamer;
static vtkTubeFilter streamTube;
static vtkPolyDataMapper mapStreamTube;
static vtkActor streamTubeActor;
static vtkOutlineFilter outline;
static vtkPolyDataMapper outlineMapper;
static vtkActor outlineActor;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetReader Getreader()
{
return reader;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setreader(vtkDataSetReader toSet)
{
reader = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetToDataObjectFilter Getds2do()
{
return ds2do;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setds2do(vtkDataSetToDataObjectFilter toSet)
{
ds2do = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static string GettryCatchError()
{
return tryCatchError;
}
///<summary> A Set Method for Static Variables </summary>
public static void SettryCatchError(string toSet)
{
tryCatchError = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static StreamWriter Getchannel()
{
return channel;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setchannel(StreamWriter toSet)
{
channel = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataObjectWriter Getwriter()
{
return writer;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setwriter(vtkDataObjectWriter toSet)
{
writer = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataObjectReader Getdor()
{
return dor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setdor(vtkDataObjectReader toSet)
{
dor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataObjectToDataSetFilter Getdo2ds()
{
return do2ds;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setdo2ds(vtkDataObjectToDataSetFilter toSet)
{
do2ds = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkFieldDataToAttributeDataFilter Getfd2ad()
{
return fd2ad;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setfd2ad(vtkFieldDataToAttributeDataFilter toSet)
{
fd2ad = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRectilinearGridGeometryFilter Getplane()
{
return plane;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setplane(vtkRectilinearGridGeometryFilter toSet)
{
plane = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkWarpVector Getwarper()
{
return warper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setwarper(vtkWarpVector toSet)
{
warper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetMapper GetplaneMapper()
{
return planeMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetplaneMapper(vtkDataSetMapper toSet)
{
planeMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetplaneActor()
{
return planeActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetplaneActor(vtkActor toSet)
{
planeActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPlane GetcutPlane()
{
return cutPlane;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetcutPlane(vtkPlane toSet)
{
cutPlane = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCutter GetplaneCut()
{
return planeCut;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetplaneCut(vtkCutter toSet)
{
planeCut = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetMapper GetcutMapper()
{
return cutMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetcutMapper(vtkDataSetMapper toSet)
{
cutMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetcutActor()
{
return cutActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetcutActor(vtkActor toSet)
{
cutActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkContourFilter Getiso()
{
return iso;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiso(vtkContourFilter toSet)
{
iso = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataNormals Getnormals()
{
return normals;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setnormals(vtkPolyDataNormals toSet)
{
normals = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetisoMapper()
{
return isoMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetisoMapper(vtkPolyDataMapper toSet)
{
isoMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetisoActor()
{
return isoActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetisoActor(vtkActor toSet)
{
isoActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStreamLine Getstreamer()
{
return streamer;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setstreamer(vtkStreamLine toSet)
{
streamer = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTubeFilter GetstreamTube()
{
return streamTube;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetstreamTube(vtkTubeFilter toSet)
{
streamTube = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetmapStreamTube()
{
return mapStreamTube;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetmapStreamTube(vtkPolyDataMapper toSet)
{
mapStreamTube = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetstreamTubeActor()
{
return streamTubeActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetstreamTubeActor(vtkActor toSet)
{
streamTubeActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkOutlineFilter Getoutline()
{
return outline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setoutline(vtkOutlineFilter toSet)
{
outline = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetoutlineMapper()
{
return outlineMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineMapper(vtkPolyDataMapper toSet)
{
outlineMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetoutlineActor()
{
return outlineActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineActor(vtkActor toSet)
{
outlineActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(reader!= null){reader.Dispose();}
if(ds2do!= null){ds2do.Dispose();}
if(writer!= null){writer.Dispose();}
if(dor!= null){dor.Dispose();}
if(do2ds!= null){do2ds.Dispose();}
if(fd2ad!= null){fd2ad.Dispose();}
if(plane!= null){plane.Dispose();}
if(warper!= null){warper.Dispose();}
if(planeMapper!= null){planeMapper.Dispose();}
if(planeActor!= null){planeActor.Dispose();}
if(cutPlane!= null){cutPlane.Dispose();}
if(planeCut!= null){planeCut.Dispose();}
if(cutMapper!= null){cutMapper.Dispose();}
if(cutActor!= null){cutActor.Dispose();}
if(iso!= null){iso.Dispose();}
if(normals!= null){normals.Dispose();}
if(isoMapper!= null){isoMapper.Dispose();}
if(isoActor!= null){isoActor.Dispose();}
if(streamer!= null){streamer.Dispose();}
if(streamTube!= null){streamTube.Dispose();}
if(mapStreamTube!= null){mapStreamTube.Dispose();}
if(streamTubeActor!= null){streamTubeActor.Dispose();}
if(outline!= null){outline.Dispose();}
if(outlineMapper!= null){outlineMapper.Dispose();}
if(outlineActor!= null){outlineActor.Dispose();}
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
}
}
//--- end of script --//
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
using QuantConnect.Securities.Option;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regression algorithm tests In The Money (ITM) future option expiry for calls.
/// We test to make sure that FOPs have greeks enabled, same as equity options.
/// </summary>
public class FutureOptionCallITMGreeksExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private bool _invested;
private int _onDataCalls;
private Security _es19m20;
private Option _esOption;
private Symbol _expectedOptionContract;
public override void Initialize()
{
SetStartDate(2020, 1, 5);
SetEndDate(2020, 6, 30);
_es19m20 = AddFutureContract(
QuantConnect.Symbol.CreateFuture(
Futures.Indices.SP500EMini,
Market.CME,
new DateTime(2020, 6, 19)),
Resolution.Minute);
// We must set the volatility model on the underlying, since the defaults are
// too strict to calculate greeks with when we only have data for a single day
_es19m20.VolatilityModel = new StandardDeviationOfReturnsVolatilityModel(
60,
Resolution.Minute,
TimeSpan.FromMinutes(1));
// Select a future option expiring ITM, and adds it to the algorithm.
_esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20.Symbol, new DateTime(2020, 1, 5))
.Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Call)
.OrderByDescending(x => x.ID.StrikePrice)
.Take(1)
.Single(), Resolution.Minute);
_esOption.PriceModel = OptionPriceModels.BjerksundStensland();
_expectedOptionContract = QuantConnect.Symbol.CreateOption(_es19m20.Symbol, Market.CME, OptionStyle.American, OptionRight.Call, 3200m, new DateTime(2020, 6, 19));
if (_esOption.Symbol != _expectedOptionContract)
{
throw new Exception($"Contract {_expectedOptionContract} was not found in the chain");
}
}
public override void OnData(Slice data)
{
// Let the algo warmup, but without using SetWarmup. Otherwise, we get
// no contracts in the option chain
if (_invested || _onDataCalls++ < 40)
{
return;
}
if (data.OptionChains.Count == 0)
{
return;
}
if (data.OptionChains.Values.All(o => o.Contracts.Values.Any(c => !data.ContainsKey(c.Symbol))))
{
return;
}
if (data.OptionChains.Values.First().Contracts.Count == 0)
{
throw new Exception($"No contracts found in the option {data.OptionChains.Keys.First()}");
}
var deltas = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Delta).ToList();
var gammas = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Gamma).ToList();
var lambda = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Lambda).ToList();
var rho = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Rho).ToList();
var theta = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Theta).ToList();
var vega = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Vega).ToList();
// The commented out test cases all return zero.
// This is because of failure to evaluate the greeks in the option pricing model.
// For now, let's skip those.
if (deltas.Any(d => d == 0))
{
throw new AggregateException("Option contract Delta was equal to zero");
}
if (gammas.Any(g => g == 0))
{
throw new AggregateException("Option contract Gamma was equal to zero");
}
if (lambda.Any(l => l == 0))
{
throw new AggregateException("Option contract Lambda was equal to zero");
}
if (rho.Any(r => r == 0))
{
throw new AggregateException("Option contract Rho was equal to zero");
}
if (theta.Any(t => t == 0))
{
throw new AggregateException("Option contract Theta was equal to zero");
}
if (vega.Any(v => v == 0))
{
throw new AggregateException("Option contract Vega was equal to zero");
}
if (!_invested)
{
// the margin requirement for the FOPs is less than the one of the underlying so we can't allocate all our buying power
// into FOPs else we won't be able to exercise
SetHoldings(data.OptionChains.Values.First().Contracts.Values.First().Symbol, 0.25);
_invested = true;
}
}
/// <summary>
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
/// </summary>
/// <exception cref="Exception">The algorithm has holdings</exception>
public override void OnEndOfAlgorithm()
{
if (Portfolio.Invested)
{
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
}
if (!_invested)
{
throw new Exception($"Never checked greeks, maybe we have no option data?");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "3"},
{"Average Win", "8.71%"},
{"Average Loss", "-34.89%"},
{"Compounding Annual Return", "-50.850%"},
{"Drawdown", "29.200%"},
{"Expectancy", "-0.375"},
{"Net Profit", "-29.224%"},
{"Sharpe Ratio", "-1.025"},
{"Probabilistic Sharpe Ratio", "0.019%"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "0.25"},
{"Alpha", "-0.387"},
{"Beta", "0.017"},
{"Annual Standard Deviation", "0.377"},
{"Annual Variance", "0.142"},
{"Information Ratio", "-0.751"},
{"Tracking Error", "0.548"},
{"Treynor Ratio", "-22.299"},
{"Total Fees", "$37.00"},
{"Estimated Strategy Capacity", "$33000000.00"},
{"Lowest Capacity Asset", "ES XFH59UK0MYO1"},
{"Fitness Score", "0.056"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-0.155"},
{"Return Over Maximum Drawdown", "-1.741"},
{"Portfolio Turnover", "0.152"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "ca0898608da51d972723b1065a3f0d47"}
};
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: XMLParser and Tree builder internal to BCL
**
**
===========================================================*/
namespace System
{
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.Security;
using System.Globalization;
using System.IO;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[Serializable]
internal enum ConfigEvents
{
StartDocument = 0,
StartDTD = StartDocument + 1,
EndDTD = StartDTD + 1,
StartDTDSubset = EndDTD + 1,
EndDTDSubset = StartDTDSubset + 1,
EndProlog = EndDTDSubset + 1,
StartEntity = EndProlog + 1,
EndEntity = StartEntity + 1,
EndDocument = EndEntity + 1,
DataAvailable = EndDocument + 1,
LastEvent = DataAvailable
}
[Serializable]
internal enum ConfigNodeType
{
Element = 1,
Attribute = Element + 1,
Pi = Attribute + 1,
XmlDecl = Pi + 1,
DocType = XmlDecl + 1,
DTDAttribute = DocType + 1,
EntityDecl = DTDAttribute + 1,
ElementDecl = EntityDecl + 1,
AttlistDecl = ElementDecl + 1,
Notation = AttlistDecl + 1,
Group = Notation + 1,
IncludeSect = Group + 1,
PCData = IncludeSect + 1,
CData = PCData + 1,
IgnoreSect = CData + 1,
Comment = IgnoreSect + 1,
EntityRef = Comment + 1,
Whitespace = EntityRef + 1,
Name = Whitespace + 1,
NMToken = Name + 1,
String = NMToken + 1,
Peref = String + 1,
Model = Peref + 1,
ATTDef = Model + 1,
ATTType = ATTDef + 1,
ATTPresence = ATTType + 1,
DTDSubset = ATTPresence + 1,
LastNodeType = DTDSubset + 1
}
[Serializable]
internal enum ConfigNodeSubType
{
Version = (int)ConfigNodeType.LastNodeType,
Encoding = Version + 1,
Standalone = Encoding + 1,
NS = Standalone + 1,
XMLSpace = NS + 1,
XMLLang = XMLSpace + 1,
System = XMLLang + 1,
Public = System + 1,
NData = Public + 1,
AtCData = NData + 1,
AtId = AtCData + 1,
AtIdref = AtId + 1,
AtIdrefs = AtIdref + 1,
AtEntity = AtIdrefs + 1,
AtEntities = AtEntity + 1,
AtNmToken = AtEntities + 1,
AtNmTokens = AtNmToken + 1,
AtNotation = AtNmTokens + 1,
AtRequired = AtNotation + 1,
AtImplied = AtRequired + 1,
AtFixed = AtImplied + 1,
PentityDecl = AtFixed + 1,
Empty = PentityDecl + 1,
Any = Empty + 1,
Mixed = Any + 1,
Sequence = Mixed + 1,
Choice = Sequence + 1,
Star = Choice + 1,
Plus = Star + 1,
Questionmark = Plus + 1,
LastSubNodeType = Questionmark + 1
}
internal abstract class BaseConfigHandler
{
// These delegates must be at the very start of the object
// This is necessary because unmanaged code takes a dependency on this layout
// Any changes made to this must be reflected in ConfigHelper.h in ConfigFactory class
protected Delegate[] eventCallbacks;
public BaseConfigHandler()
{
InitializeCallbacks();
}
private void InitializeCallbacks()
{
if (eventCallbacks == null)
{
eventCallbacks = new Delegate[6];
eventCallbacks[0] = new NotifyEventCallback(this.NotifyEvent);
eventCallbacks[1] = new BeginChildrenCallback(this.BeginChildren);
eventCallbacks[2] = new EndChildrenCallback(this.EndChildren);
eventCallbacks[3] = new ErrorCallback(this.Error);
eventCallbacks[4] = new CreateNodeCallback(this.CreateNode);
eventCallbacks[5] = new CreateAttributeCallback(this.CreateAttribute);
}
}
private delegate void NotifyEventCallback(ConfigEvents nEvent);
public abstract void NotifyEvent(ConfigEvents nEvent);
private delegate void BeginChildrenCallback(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength);
public abstract void BeginChildren(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength);
private delegate void EndChildrenCallback(int fEmpty,
int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength);
public abstract void EndChildren(int fEmpty,
int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength);
private delegate void ErrorCallback(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
public abstract void Error(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
private delegate void CreateNodeCallback(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
public abstract void CreateNode(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
private delegate void CreateAttributeCallback(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
public abstract void CreateAttribute(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void RunParser(String fileName);
}
// Class used to build a DOM like tree of parsed XML
internal class ConfigTreeParser : BaseConfigHandler
{
ConfigNode rootNode = null;
ConfigNode currentNode = null;
String fileName = null;
int attributeEntry;
String key = null;
String [] treeRootPath = null; // element to start tree
bool parsing = false;
int depth = 0;
int pathDepth = 0;
int searchDepth = 0;
bool bNoSearchPath = false;
// Track state for error message formatting
String lastProcessed = null;
bool lastProcessedEndElement;
// NOTE: This parser takes a path eg. /configuration/system.runtime.remoting
// and will return a node which matches this.
internal ConfigNode Parse(String fileName, String configPath)
{
return Parse(fileName, configPath, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
internal ConfigNode Parse(String fileName, String configPath, bool skipSecurityStuff)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
Contract.EndContractBlock();
this.fileName = fileName;
if (configPath[0] == '/'){
treeRootPath = configPath.Substring(1).Split('/');
pathDepth = treeRootPath.Length - 1;
bNoSearchPath = false;
}
else{
treeRootPath = new String[1];
treeRootPath[0] = configPath;
bNoSearchPath = true;
}
if (!skipSecurityStuff) {
(new FileIOPermission( FileIOPermissionAccess.Read, System.IO.Path.GetFullPathInternal( fileName ) )).Demand();
}
#pragma warning disable 618
(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Assert();
#pragma warning restore 618
try
{
RunParser(fileName);
}
catch(FileNotFoundException) {
throw; // Pass these through unadulterated.
}
catch(DirectoryNotFoundException) {
throw; // Pass these through unadulterated.
}
catch(UnauthorizedAccessException) {
throw;
}
catch(FileLoadException) {
throw;
}
catch(Exception inner) {
String message = GetInvalidSyntaxMessage();
// Neither Exception nor ApplicationException are the "right" exceptions here.
// Desktop throws ApplicationException for backwards compatibility.
// On Silverlight we don't have ApplicationException, so fall back to Exception.
#if FEATURE_CORECLR
throw new Exception(message, inner);
#else
throw new ApplicationException(message, inner);
#endif
}
return rootNode;
}
public override void NotifyEvent(ConfigEvents nEvent)
{
BCLDebug.Trace("REMOTE", "NotifyEvent "+((Enum)nEvent).ToString()+"\n");
}
public override void BeginChildren(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength)
{
//Trace("BeginChildren",size,subType,nType,terminal,text,textLength,prefixLength,0);
if (!parsing &&
(!bNoSearchPath
&& depth == (searchDepth + 1)
&& String.Compare(text, treeRootPath[searchDepth], StringComparison.Ordinal) == 0))
{
searchDepth++;
}
}
public override void EndChildren(int fEmpty,
int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)] String text,
int textLength,
int prefixLength)
{
lastProcessed = text;
lastProcessedEndElement = true;
if (parsing)
{
//Trace("EndChildren",size,subType,nType,terminal,text,textLength,prefixLength,fEmpty);
if (currentNode == rootNode)
{
// End of section of tree which is parsed
parsing = false;
}
currentNode = currentNode.Parent;
}
else if (nType == ConfigNodeType.Element){
if(depth == searchDepth && String.Compare(text, treeRootPath[searchDepth - 1], StringComparison.Ordinal) == 0)
{
searchDepth--;
depth--;
}
else
depth--;
}
}
public override void Error(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength)
{
//Trace("Error",size,subType,nType,terminal,text,textLength,prefixLength,0);
}
public override void CreateNode(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength)
{
//Trace("CreateNode",size,subType,nType,terminal,text,textLength,prefixLength,0);
if (nType == ConfigNodeType.Element)
{
// New Node
lastProcessed = text;
lastProcessedEndElement = false;
if (parsing
|| (bNoSearchPath &&
String.Compare(text, treeRootPath[0], StringComparison.OrdinalIgnoreCase) == 0)
|| (depth == searchDepth && searchDepth == pathDepth &&
String.Compare(text, treeRootPath[pathDepth], StringComparison.OrdinalIgnoreCase) == 0 ))
{
parsing = true;
ConfigNode parentNode = currentNode;
currentNode = new ConfigNode(text, parentNode);
if (rootNode == null)
rootNode = currentNode;
else
parentNode.AddChild(currentNode);
}
else
depth++;
}
else if (nType == ConfigNodeType.PCData)
{
// Data node
if (currentNode != null)
{
currentNode.Value = text;
}
}
}
public override void CreateAttribute(int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength)
{
//Trace("CreateAttribute",size,subType,nType,terminal,text,textLength,prefixLength,0);
if (parsing)
{
// if the value of the attribute is null, the parser doesn't come back, so need to store the attribute when the
// attribute name is encountered
if (nType == ConfigNodeType.Attribute)
{
attributeEntry = currentNode.AddAttribute(text, "");
key = text;
}
else if (nType == ConfigNodeType.PCData)
{
currentNode.ReplaceAttribute(attributeEntry, key, text);
}
else
{
String message = GetInvalidSyntaxMessage();
// Neither Exception nor ApplicationException are the "right" exceptions here.
// Desktop throws ApplicationException for backwards compatibility.
// On Silverlight we don't have ApplicationException, so fall back to Exception.
#if FEATURE_CORECLR
throw new Exception(message);
#else
throw new ApplicationException(message);
#endif
}
}
}
#if _DEBUG
[System.Diagnostics.Conditional("_LOGGING")]
private void Trace(String name,
int size,
ConfigNodeSubType subType,
ConfigNodeType nType,
int terminal,
[MarshalAs(UnmanagedType.LPWStr)]String text,
int textLength,
int prefixLength, int fEmpty)
{
BCLDebug.Trace("REMOTE","Node "+name);
BCLDebug.Trace("REMOTE","text "+text);
BCLDebug.Trace("REMOTE","textLength "+textLength);
BCLDebug.Trace("REMOTE","size "+size);
BCLDebug.Trace("REMOTE","subType "+((Enum)subType).ToString());
BCLDebug.Trace("REMOTE","nType "+((Enum)nType).ToString());
BCLDebug.Trace("REMOTE","terminal "+terminal);
BCLDebug.Trace("REMOTE","prefixLength "+prefixLength);
BCLDebug.Trace("REMOTE","fEmpty "+fEmpty+"\n");
}
#endif
private String GetInvalidSyntaxMessage()
{
String lastProcessedTag = null;
if (lastProcessed != null)
lastProcessedTag = (lastProcessedEndElement ? "</" : "<") + lastProcessed + ">";
return Environment.GetResourceString("XML_Syntax_InvalidSyntaxInFile", fileName, lastProcessedTag);
}
}
// Node in Tree produced by ConfigTreeParser
internal class ConfigNode
{
String m_name = null;
String m_value = null;
ConfigNode m_parent = null;
List<ConfigNode> m_children = new List<ConfigNode>(5);
List<DictionaryEntry> m_attributes = new List<DictionaryEntry>(5);
internal ConfigNode(String name, ConfigNode parent)
{
m_name = name;
m_parent = parent;
}
internal String Name
{
get {return m_name;}
}
internal String Value
{
get {return m_value;}
set {m_value = value;}
}
internal ConfigNode Parent
{
get {return m_parent;}
}
internal List<ConfigNode> Children
{
get {return m_children;}
}
internal List<DictionaryEntry> Attributes
{
get {return m_attributes;}
}
internal void AddChild(ConfigNode child)
{
child.m_parent = this;
m_children.Add(child);
}
internal int AddAttribute(String key, String value)
{
m_attributes.Add(new DictionaryEntry(key, value));
return m_attributes.Count-1;
}
internal void ReplaceAttribute(int index, String key, String value)
{
m_attributes[index] = new DictionaryEntry(key, value);
}
#if _DEBUG
[System.Diagnostics.Conditional("_LOGGING")]
internal void Trace()
{
BCLDebug.Trace("REMOTE","************ConfigNode************");
BCLDebug.Trace("REMOTE","Name = "+m_name);
if (m_value != null)
BCLDebug.Trace("REMOTE","Value = "+m_value);
if (m_parent != null)
BCLDebug.Trace("REMOTE","Parent = "+m_parent.Name);
for (int i=0; i<m_attributes.Count; i++)
{
DictionaryEntry de = (DictionaryEntry)m_attributes[i];
BCLDebug.Trace("REMOTE","Key = "+de.Key+" Value = "+de.Value);
}
for (int i=0; i<m_children.Count; i++)
{
((ConfigNode)m_children[i]).Trace();
}
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Counters;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Providers;
using Orleans.Runtime.ReminderService;
using Orleans.Runtime.Scheduler;
using Orleans.Services;
using Orleans.ApplicationParts;
using Orleans.Configuration;
using Orleans.Serialization;
using Orleans.Internal;
namespace Orleans.Runtime
{
/// <summary>
/// Orleans silo.
/// </summary>
public class Silo
{
/// <summary> Standard name for Primary silo. </summary>
public const string PrimarySiloName = "Primary";
private static TimeSpan WaitForMessageToBeQueuedForOutbound = TimeSpan.FromSeconds(2);
/// <summary> Silo Types. </summary>
public enum SiloType
{
/// <summary> No silo type specified. </summary>
None = 0,
/// <summary> Primary silo. </summary>
Primary,
/// <summary> Secondary silo. </summary>
Secondary,
}
private readonly ILocalSiloDetails siloDetails;
private readonly MessageCenter messageCenter;
private readonly LocalGrainDirectory localGrainDirectory;
private readonly ActivationDirectory activationDirectory;
private readonly ILogger logger;
private readonly TaskCompletionSource<int> siloTerminatedTask = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly SiloStatisticsManager siloStatistics;
private readonly InsideRuntimeClient runtimeClient;
private IReminderService reminderService;
private SystemTarget fallbackScheduler;
private readonly ISiloStatusOracle siloStatusOracle;
private Watchdog platformWatchdog;
private readonly TimeSpan initTimeout;
private readonly TimeSpan stopTimeout = TimeSpan.FromMinutes(1);
private readonly Catalog catalog;
private readonly object lockable = new object();
private readonly GrainFactory grainFactory;
private readonly ISiloLifecycleSubject siloLifecycle;
private readonly IMembershipService membershipService;
internal List<GrainService> grainServices = new List<GrainService>();
private readonly ILoggerFactory loggerFactory;
/// <summary>
/// Gets the type of this
/// </summary>
internal string Name => this.siloDetails.Name;
internal OrleansTaskScheduler LocalScheduler { get; private set; }
internal ILocalGrainDirectory LocalGrainDirectory { get { return localGrainDirectory; } }
internal IConsistentRingProvider RingProvider { get; private set; }
internal List<GrainService> GrainServices => grainServices;
internal SystemStatus SystemStatus { get; set; }
internal IServiceProvider Services { get; }
/// <summary> SiloAddress for this silo. </summary>
public SiloAddress SiloAddress => this.siloDetails.SiloAddress;
public Task SiloTerminated { get { return this.siloTerminatedTask.Task; } } // one event for all types of termination (shutdown, stop and fast kill).
private bool isFastKilledNeeded = false; // Set to true if something goes wrong in the shutdown/stop phase
private IGrainContext reminderServiceContext;
private LifecycleSchedulingSystemTarget lifecycleSchedulingSystemTarget;
/// <summary>
/// Initializes a new instance of the <see cref="Silo"/> class.
/// </summary>
/// <param name="siloDetails">The silo initialization parameters</param>
/// <param name="services">Dependency Injection container</param>
[Obsolete("This constructor is obsolete and may be removed in a future release. Use SiloHostBuilder to create an instance of ISiloHost instead.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "Should not Dispose of messageCenter in this method because it continues to run / exist after this point.")]
public Silo(ILocalSiloDetails siloDetails, IServiceProvider services)
{
string name = siloDetails.Name;
// Temporarily still require this. Hopefuly gone when 2.0 is released.
this.siloDetails = siloDetails;
this.SystemStatus = SystemStatus.Creating;
var startTime = DateTime.UtcNow;
IOptions<ClusterMembershipOptions> clusterMembershipOptions = services.GetRequiredService<IOptions<ClusterMembershipOptions>>();
initTimeout = clusterMembershipOptions.Value.MaxJoinAttemptTime;
if (Debugger.IsAttached)
{
initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), clusterMembershipOptions.Value.MaxJoinAttemptTime);
stopTimeout = initTimeout;
}
var localEndpoint = this.siloDetails.SiloAddress.Endpoint;
services.GetService<SerializationManager>().RegisterSerializers(services.GetService<IApplicationPartManager>());
this.Services = services;
this.Services.InitializeSiloUnobservedExceptionsHandler();
//set PropagateActivityId flag from node config
IOptions<SiloMessagingOptions> messagingOptions = services.GetRequiredService<IOptions<SiloMessagingOptions>>();
RequestContext.PropagateActivityId = messagingOptions.Value.PropagateActivityId;
this.loggerFactory = this.Services.GetRequiredService<ILoggerFactory>();
logger = this.loggerFactory.CreateLogger<Silo>();
logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode));
if (!GCSettings.IsServerGC)
{
logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\">");
logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines).");
}
if (logger.IsEnabled(LogLevel.Debug))
{
var highestLogLevel = logger.IsEnabled(LogLevel.Trace) ? nameof(LogLevel.Trace) : nameof(LogLevel.Debug);
logger.LogWarning(
new EventId((int)ErrorCode.SiloGcWarning),
$"A verbose logging level ({highestLogLevel}) is configured. This will impact performance. The recommended log level is {nameof(LogLevel.Information)}.");
}
logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing silo on host {0} MachineName {1} at {2}, gen {3} --------------",
this.siloDetails.DnsHostName, Environment.MachineName, localEndpoint, this.siloDetails.SiloAddress.Generation);
logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0}", name);
var siloMessagingOptions = this.Services.GetRequiredService<IOptions<SiloMessagingOptions>>();
BufferPool.InitGlobalBufferPool(siloMessagingOptions.Value);
try
{
grainFactory = Services.GetRequiredService<GrainFactory>();
}
catch (InvalidOperationException exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc);
throw;
}
// Performance metrics
siloStatistics = Services.GetRequiredService<SiloStatisticsManager>();
// The scheduler
LocalScheduler = Services.GetRequiredService<OrleansTaskScheduler>();
runtimeClient = Services.GetRequiredService<InsideRuntimeClient>();
// Initialize the message center
messageCenter = Services.GetRequiredService<MessageCenter>();
var dispatcher = this.Services.GetRequiredService<Dispatcher>();
messageCenter.RerouteHandler = dispatcher.RerouteMessage;
messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage;
// Now the router/directory service
// This has to come after the message center //; note that it then gets injected back into the message center.;
localGrainDirectory = Services.GetRequiredService<LocalGrainDirectory>();
// Now the activation directory.
activationDirectory = Services.GetRequiredService<ActivationDirectory>();
// Now the consistent ring provider
RingProvider = Services.GetRequiredService<IConsistentRingProvider>();
catalog = Services.GetRequiredService<Catalog>();
siloStatusOracle = Services.GetRequiredService<ISiloStatusOracle>();
this.membershipService = Services.GetRequiredService<IMembershipService>();
this.SystemStatus = SystemStatus.Created;
StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME,
() => LogFormatter.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs.
this.siloLifecycle = this.Services.GetRequiredService<ISiloLifecycleSubject>();
// register all lifecycle participants
IEnumerable<ILifecycleParticipant<ISiloLifecycle>> lifecycleParticipants = this.Services.GetServices<ILifecycleParticipant<ISiloLifecycle>>();
foreach(ILifecycleParticipant<ISiloLifecycle> participant in lifecycleParticipants)
{
participant?.Participate(this.siloLifecycle);
}
// register all named lifecycle participants
IKeyedServiceCollection<string, ILifecycleParticipant<ISiloLifecycle>> namedLifecycleParticipantCollection = this.Services.GetService<IKeyedServiceCollection<string,ILifecycleParticipant<ISiloLifecycle>>>();
foreach (ILifecycleParticipant<ISiloLifecycle> participant in namedLifecycleParticipantCollection
?.GetServices(this.Services)
?.Select(s => s.GetService(this.Services)))
{
participant?.Participate(this.siloLifecycle);
}
// add self to lifecycle
this.Participate(this.siloLifecycle);
logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
}
public async Task StartAsync(CancellationToken cancellationToken)
{
// SystemTarget for provider init calls
this.lifecycleSchedulingSystemTarget = Services.GetRequiredService<LifecycleSchedulingSystemTarget>();
this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>();
RegisterSystemTarget(lifecycleSchedulingSystemTarget);
try
{
await this.LocalScheduler.QueueTask(() => this.siloLifecycle.OnStart(cancellationToken), this.lifecycleSchedulingSystemTarget);
}
catch (Exception exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start", exc);
throw;
}
}
private void CreateSystemTargets()
{
var siloControl = ActivatorUtilities.CreateInstance<SiloControl>(Services);
RegisterSystemTarget(siloControl);
RegisterSystemTarget(Services.GetRequiredService<DeploymentLoadPublisher>());
RegisterSystemTarget(LocalGrainDirectory.RemoteGrainDirectory);
RegisterSystemTarget(LocalGrainDirectory.CacheValidator);
this.RegisterSystemTarget(this.Services.GetRequiredService<ClientDirectory>());
if (this.membershipService is SystemTarget)
{
RegisterSystemTarget((SystemTarget)this.membershipService);
}
}
private async Task InjectDependencies()
{
catalog.SiloStatusOracle = this.siloStatusOracle;
this.siloStatusOracle.SubscribeToSiloStatusEvents(localGrainDirectory);
// consistentRingProvider is not a system target per say, but it behaves like the localGrainDirectory, so it is here
this.siloStatusOracle.SubscribeToSiloStatusEvents((ISiloStatusListener)RingProvider);
this.siloStatusOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<DeploymentLoadPublisher>());
var reminderTable = Services.GetService<IReminderTable>();
if (reminderTable != null)
{
logger.Info($"Creating reminder grain service for type={reminderTable.GetType()}");
// Start the reminder service system target
var timerFactory = this.Services.GetRequiredService<IAsyncTimerFactory>();
reminderService = new LocalReminderService(this, reminderTable, this.initTimeout, this.loggerFactory, timerFactory);
this.Services.GetService<SiloLoggingHelper>()?.RegisterGrainService(reminderService);
RegisterSystemTarget((SystemTarget)reminderService);
}
RegisterSystemTarget(catalog);
await LocalScheduler.QueueActionAsync(catalog.Start, catalog)
.WithTimeout(initTimeout, $"Starting Catalog failed due to timeout {initTimeout}");
// SystemTarget for provider init calls
this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>();
RegisterSystemTarget(fallbackScheduler);
}
private Task OnRuntimeInitializeStart(CancellationToken ct)
{
lock (lockable)
{
if (!this.SystemStatus.Equals(SystemStatus.Created))
throw new InvalidOperationException(String.Format("Calling Silo.Start() on a silo which is not in the Created state. This silo is in the {0} state.", this.SystemStatus));
this.SystemStatus = SystemStatus.Starting;
}
logger.Info(ErrorCode.SiloStarting, "Silo Start()");
//TODO: setup thead pool directly to lifecycle
StartTaskWithPerfAnalysis("ConfigureThreadPoolAndServicePointSettings",
this.ConfigureThreadPoolAndServicePointSettings, Stopwatch.StartNew());
return Task.CompletedTask;
}
private void StartTaskWithPerfAnalysis(string taskName, Action task, Stopwatch stopWatch)
{
stopWatch.Restart();
task.Invoke();
stopWatch.Stop();
this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish");
}
private async Task StartAsyncTaskWithPerfAnalysis(string taskName, Func<Task> task, Stopwatch stopWatch)
{
stopWatch.Restart();
await task.Invoke();
stopWatch.Stop();
this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish");
}
private async Task OnRuntimeServicesStart(CancellationToken ct)
{
//TODO: Setup all (or as many as possible) of the class started in this call to work directly with lifecyce
var stopWatch = Stopwatch.StartNew();
// The order of these 4 is pretty much arbitrary.
StartTaskWithPerfAnalysis("Start Message center",messageCenter.Start,stopWatch);
StartTaskWithPerfAnalysis("Start local grain directory", LocalGrainDirectory.Start, stopWatch);
// This has to follow the above steps that start the runtime components
await StartAsyncTaskWithPerfAnalysis("Create system targets and inject dependencies", () =>
{
CreateSystemTargets();
return InjectDependencies();
}, stopWatch);
// Validate the configuration.
// TODO - refactor validation - jbragg
//GlobalConfig.Application.ValidateConfiguration(logger);
}
private async Task OnRuntimeGrainServicesStart(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
// Load and init grain services before silo becomes active.
await StartAsyncTaskWithPerfAnalysis("Init grain services",
() => CreateGrainServices(), stopWatch);
try
{
StatisticsOptions statisticsOptions = Services.GetRequiredService<IOptions<StatisticsOptions>>().Value;
StartTaskWithPerfAnalysis("Start silo statistics", () => this.siloStatistics.Start(statisticsOptions), stopWatch);
logger.Debug("Silo statistics manager started successfully.");
// Finally, initialize the deployment load collector, for grains with load-based placement
await StartAsyncTaskWithPerfAnalysis("Start deployment load collector", StartDeploymentLoadCollector, stopWatch);
async Task StartDeploymentLoadCollector()
{
var deploymentLoadPublisher = Services.GetRequiredService<DeploymentLoadPublisher>();
await this.LocalScheduler.QueueTask(deploymentLoadPublisher.Start, deploymentLoadPublisher)
.WithTimeout(this.initTimeout, $"Starting DeploymentLoadPublisher failed due to timeout {initTimeout}");
logger.Debug("Silo deployment load publisher started successfully.");
}
// Start background timer tick to watch for platform execution stalls, such as when GC kicks in
var healthCheckParticipants = this.Services.GetService<IEnumerable<IHealthCheckParticipant>>().ToList();
this.platformWatchdog = new Watchdog(statisticsOptions.LogWriteInterval, healthCheckParticipants, this.loggerFactory.CreateLogger<Watchdog>());
this.platformWatchdog.Start();
if (this.logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo platform watchdog started successfully."); }
}
catch (Exception exc)
{
this.SafeExecute(() => this.logger.Error(ErrorCode.Runtime_Error_100330, String.Format("Error starting silo {0}. Going to FastKill().", this.SiloAddress), exc));
throw;
}
if (logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo.Start complete: System status = {0}", this.SystemStatus); }
}
private Task OnBecomeActiveStart(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
StartTaskWithPerfAnalysis("Start gateway", StartGateway, stopWatch);
void StartGateway()
{
// Now that we're active, we can start the gateway
var mc = this.messageCenter as MessageCenter;
mc?.StartGateway();
logger.Debug("Message gateway service started successfully.");
}
this.SystemStatus = SystemStatus.Running;
return Task.CompletedTask;
}
private async Task OnActiveStart(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
if (this.reminderService != null)
{
await StartAsyncTaskWithPerfAnalysis("Start reminder service", StartReminderService, stopWatch);
async Task StartReminderService()
{
// so, we have the view of the membership in the consistentRingProvider. We can start the reminder service
this.reminderServiceContext = (this.reminderService as IGrainContext) ?? this.fallbackScheduler;
await this.LocalScheduler.QueueTask(this.reminderService.Start, this.reminderServiceContext)
.WithTimeout(this.initTimeout, $"Starting ReminderService failed due to timeout {initTimeout}");
this.logger.Debug("Reminder service started successfully.");
}
}
foreach (var grainService in grainServices)
{
await StartGrainService(grainService);
}
}
private async Task CreateGrainServices()
{
var grainServices = this.Services.GetServices<IGrainService>();
var loggingHelper = this.Services.GetService<SiloLoggingHelper>();
foreach (var grainService in grainServices)
{
loggingHelper?.RegisterGrainService(grainService);
await RegisterGrainService(grainService);
}
}
private async Task RegisterGrainService(IGrainService service)
{
var grainService = (GrainService)service;
RegisterSystemTarget(grainService);
grainServices.Add(grainService);
await this.LocalScheduler.QueueTask(() => grainService.Init(Services), grainService).WithTimeout(this.initTimeout, $"GrainService Initializing failed due to timeout {initTimeout}");
logger.Info($"Grain Service {service.GetType().FullName} registered successfully.");
}
private async Task StartGrainService(IGrainService service)
{
var grainService = (GrainService)service;
await this.LocalScheduler.QueueTask(grainService.Start, grainService).WithTimeout(this.initTimeout, $"Starting GrainService failed due to timeout {initTimeout}");
logger.Info($"Grain Service {service.GetType().FullName} started successfully.");
}
private void ConfigureThreadPoolAndServicePointSettings()
{
PerformanceTuningOptions performanceTuningOptions = Services.GetRequiredService<IOptions<PerformanceTuningOptions>>().Value;
if (performanceTuningOptions.MinDotNetThreadPoolSize > 0 || performanceTuningOptions.MinIOThreadPoolSize > 0)
{
int workerThreads;
int completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
if (performanceTuningOptions.MinDotNetThreadPoolSize > workerThreads ||
performanceTuningOptions.MinIOThreadPoolSize > completionPortThreads)
{
// if at least one of the new values is larger, set the new min values to be the larger of the prev. and new config value.
int newWorkerThreads = Math.Max(performanceTuningOptions.MinDotNetThreadPoolSize, workerThreads);
int newCompletionPortThreads = Math.Max(performanceTuningOptions.MinIOThreadPoolSize, completionPortThreads);
bool ok = ThreadPool.SetMinThreads(newWorkerThreads, newCompletionPortThreads);
if (ok)
{
logger.Info(ErrorCode.SiloConfiguredThreadPool,
"Configured ThreadPool.SetMinThreads() to values: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
else
{
logger.Warn(ErrorCode.SiloFailedToConfigureThreadPool,
"Failed to configure ThreadPool.SetMinThreads(). Tried to set values to: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
}
}
// Set .NET ServicePointManager settings to optimize throughput performance when using Azure storage
// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx
logger.Info(ErrorCode.SiloConfiguredServicePointManager,
"Configured .NET ServicePointManager to Expect100Continue={0}, DefaultConnectionLimit={1}, UseNagleAlgorithm={2} to improve Azure storage performance.",
performanceTuningOptions.Expect100Continue, performanceTuningOptions.DefaultConnectionLimit, performanceTuningOptions.UseNagleAlgorithm);
ServicePointManager.Expect100Continue = performanceTuningOptions.Expect100Continue;
ServicePointManager.DefaultConnectionLimit = performanceTuningOptions.DefaultConnectionLimit;
ServicePointManager.UseNagleAlgorithm = performanceTuningOptions.UseNagleAlgorithm;
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// Grains are not deactivated.
/// </summary>
public void Stop()
{
var cancellationSource = new CancellationTokenSource();
cancellationSource.Cancel();
StopAsync(cancellationSource.Token).GetAwaiter().GetResult();
}
/// <summary>
/// Gracefully stop the run time system and the application.
/// All grains will be properly deactivated.
/// All in-flight applications requests would be awaited and finished gracefully.
/// </summary>
public void Shutdown()
{
var cancellationSource = new CancellationTokenSource(this.stopTimeout);
StopAsync(cancellationSource.Token).GetAwaiter().GetResult();
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// </summary>
public async Task StopAsync(CancellationToken cancellationToken)
{
logger.LogInformation((int)ErrorCode.SiloShuttingDown, "Silo shutting down");
bool gracefully = !cancellationToken.IsCancellationRequested;
bool stopAlreadyInProgress = false;
lock (lockable)
{
if (this.SystemStatus.Equals(SystemStatus.Stopping) ||
this.SystemStatus.Equals(SystemStatus.ShuttingDown) ||
this.SystemStatus.Equals(SystemStatus.Terminated))
{
stopAlreadyInProgress = true;
// Drop through to wait below
}
else if (!this.SystemStatus.Equals(SystemStatus.Running))
{
throw new InvalidOperationException($"Attempted to stop a silo which is not in the {nameof(SystemStatus.Running)} state. This silo is in the {this.SystemStatus} state.");
}
else
{
if (gracefully)
this.SystemStatus = SystemStatus.ShuttingDown;
else
this.SystemStatus = SystemStatus.Stopping;
}
}
if (stopAlreadyInProgress)
{
logger.Info(ErrorCode.SiloStopInProgress, "Silo termination is in progress - Will wait for it to finish");
var pause = TimeSpan.FromSeconds(1);
while (!this.SystemStatus.Equals(SystemStatus.Terminated))
{
logger.Info(ErrorCode.WaitingForSiloStop, "Waiting {0} for termination to complete", pause);
await Task.Delay(pause).ConfigureAwait(false);
}
await this.SiloTerminated.ConfigureAwait(false);
return;
}
try
{
await this.LocalScheduler.QueueTask(() => this.siloLifecycle.OnStop(cancellationToken), this.lifecycleSchedulingSystemTarget).ConfigureAwait(false);
}
finally
{
// Signal to all awaiters that the silo has terminated.
logger.LogInformation((int)ErrorCode.SiloShutDown, "Silo shutdown completed");
SafeExecute(LocalScheduler.Stop);
await Task.Run(() => this.siloTerminatedTask.TrySetResult(0)).ConfigureAwait(false);
}
}
private Task OnRuntimeServicesStop(CancellationToken ct)
{
if (this.isFastKilledNeeded || ct.IsCancellationRequested) // No time for this
return Task.CompletedTask;
// Start rejecting all silo to silo application messages
SafeExecute(messageCenter.BlockApplicationMessages);
// Stop scheduling/executing application turns
SafeExecute(LocalScheduler.StopApplicationTurns);
return Task.CompletedTask;
}
private Task OnRuntimeInitializeStop(CancellationToken ct)
{
// 10, 11, 12: Write Dead in the table, Drain scheduler, Stop msg center, ...
// timers
if (platformWatchdog != null)
SafeExecute(platformWatchdog.Stop); // Silo may be dying before platformWatchdog was set up
if (!ct.IsCancellationRequested)
SafeExecute(activationDirectory.PrintActivationDirectory);
SafeExecute(messageCenter.Stop);
SafeExecute(siloStatistics.Stop);
SafeExecute(() => this.SystemStatus = SystemStatus.Terminated);
return Task.CompletedTask;
}
private async Task OnBecomeActiveStop(CancellationToken ct)
{
if (this.isFastKilledNeeded)
return;
bool gracefully = !ct.IsCancellationRequested;
try
{
if (gracefully)
{
// Stop LocalGrainDirectory
await LocalScheduler.QueueActionAsync(() => localGrainDirectory.Stop(), localGrainDirectory.CacheValidator);
SafeExecute(() => catalog.DeactivateAllActivations().Wait(ct));
// Wait for all queued message sent to OutboundMessageQueue before MessageCenter stop and OutboundMessageQueue stop.
await Task.Delay(WaitForMessageToBeQueuedForOutbound);
}
}
catch (Exception exc)
{
logger.LogError(
(int)ErrorCode.SiloFailedToStopMembership,
exc,
"Failed to shutdown gracefully. About to terminate ungracefully");
this.isFastKilledNeeded = true;
}
// Stop the gateway
SafeExecute(messageCenter.StopAcceptingClientMessages);
SafeExecute(() => catalog?.Stop());
}
private async Task OnActiveStop(CancellationToken ct)
{
if (this.isFastKilledNeeded || ct.IsCancellationRequested)
return;
if (this.messageCenter.Gateway != null)
{
await this.LocalScheduler
.QueueTask(() => this.messageCenter.Gateway.SendStopSendMessages(this.grainFactory), this.lifecycleSchedulingSystemTarget)
.WithCancellation(ct, "Sending gateway disconnection requests failed because the task was cancelled");
}
if (reminderService != null)
{
await this.LocalScheduler
.QueueTask(reminderService.Stop, this.reminderServiceContext)
.WithCancellation(ct, "Stopping ReminderService failed because the task was cancelled");
}
foreach (var grainService in grainServices)
{
await this.LocalScheduler
.QueueTask(grainService.Stop, grainService)
.WithCancellation(ct, "Stopping GrainService failed because the task was cancelled");
if (this.logger.IsEnabled(LogLevel.Debug))
{
logger.Debug(
"{GrainServiceType} Grain Service with Id {GrainServiceId} stopped successfully.",
grainService.GetType().FullName,
grainService.GetPrimaryKeyLong(out string ignored));
}
}
}
private void SafeExecute(Action action)
{
Utils.SafeExecute(action, logger, "Silo.Stop");
}
private void HandleProcessExit(object sender, EventArgs e)
{
// NOTE: We need to minimize the amount of processing occurring on this code path -- we only have under approx 2-3 seconds before process exit will occur
this.logger.Warn(ErrorCode.Runtime_Error_100220, "Process is exiting");
this.isFastKilledNeeded = true;
this.Stop();
}
internal void RegisterSystemTarget(SystemTarget target) => this.catalog.RegisterSystemTarget(target);
/// <summary> Return dump of diagnostic data from this silo. </summary>
/// <param name="all"></param>
/// <returns>Debug data for this silo.</returns>
public string GetDebugDump(bool all = true)
{
var sb = new StringBuilder();
foreach (var systemTarget in activationDirectory.AllSystemTargets())
sb.AppendFormat("System target {0}:", ((ISystemTargetBase)systemTarget).GrainId.ToString()).AppendLine();
var enumerator = activationDirectory.GetEnumerator();
while(enumerator.MoveNext())
{
Utils.SafeExecute(() =>
{
var activationData = enumerator.Current.Value;
var workItemGroup = LocalScheduler.GetWorkItemGroup(activationData);
if (workItemGroup == null)
{
sb.AppendFormat("Activation with no work item group!! Grain {0}, activation {1}.",
activationData.GrainId,
activationData.ActivationId);
sb.AppendLine();
return;
}
if (all || activationData.State.Equals(ActivationState.Valid))
{
sb.AppendLine(workItemGroup.DumpStatus());
sb.AppendLine(activationData.DumpStatus());
}
});
}
logger.Info(ErrorCode.SiloDebugDump, sb.ToString());
return sb.ToString();
}
/// <summary> Object.ToString override -- summary info for this silo. </summary>
public override string ToString()
{
return localGrainDirectory.ToString();
}
private void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeInitialize, (ct) => Task.Run(() => OnRuntimeInitializeStart(ct)), (ct) => Task.Run(() => OnRuntimeInitializeStop(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeServices, (ct) => Task.Run(() => OnRuntimeServicesStart(ct)), (ct) => Task.Run(() => OnRuntimeServicesStop(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeGrainServices, (ct) => Task.Run(() => OnRuntimeGrainServicesStart(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.BecomeActive, (ct) => Task.Run(() => OnBecomeActiveStart(ct)), (ct) => Task.Run(() => OnBecomeActiveStop(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.Active, (ct) => Task.Run(() => OnActiveStart(ct)), (ct) => Task.Run(() => OnActiveStop(ct)));
}
}
// A dummy system target for fallback scheduler
internal class FallbackSystemTarget : SystemTarget
{
public FallbackSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory)
: base(Constants.FallbackSystemTargetType, localSiloDetails.SiloAddress, loggerFactory)
{
}
}
// A dummy system target for fallback scheduler
internal class LifecycleSchedulingSystemTarget : SystemTarget
{
public LifecycleSchedulingSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory)
: base(Constants.LifecycleSchedulingSystemTargetType, localSiloDetails.SiloAddress, loggerFactory)
{
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.ComponentModel;
using System.Linq;
using XenAdmin.Core;
using XenAdmin.Network;
using XenAdmin.Utils;
using XenAPI;
namespace XenAdmin.Dialogs
{
public interface ILicenseStatus : IDisposable
{
LicenseStatus.HostState CurrentState { get; }
Host.Edition LicenseEdition { get; }
TimeSpan LicenseExpiresIn { get; }
TimeSpan LicenseExpiresExactlyIn { get; }
DateTime? ExpiryDate { get; }
event LicenseStatus.StatusUpdatedEvent ItemUpdated;
bool Updated { get; }
void BeginUpdate();
Host LicencedHost { get; }
LicenseStatus.LicensingModel PoolLicensingModel { get; }
string LicenseEntitlements { get; }
}
public class LicenseStatus : ILicenseStatus
{
public enum HostState
{
Unknown,
Expired,
ExpiresSoon,
RegularGrace,
UpgradeGrace,
Licensed,
PartiallyLicensed,
Free,
Unavailable
}
private readonly EventHandlerList events = new EventHandlerList();
protected EventHandlerList Events { get { return events; } }
private const string StatusUpdatedEventKey = "LicenseStatusStatusUpdatedEventKey";
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public Host LicencedHost { get; private set; }
private readonly AsyncServerTime serverTime = new AsyncServerTime();
public delegate void StatusUpdatedEvent(object sender, EventArgs e);
public static bool IsInfinite(TimeSpan span)
{
return span.TotalDays >= 3653;
}
public static bool IsGraceLicence(TimeSpan span)
{
return span.TotalDays < 30;
}
private IXenObject XenObject { get; set; }
public bool Updated { get; set; }
public LicenseStatus(IXenObject xo)
{
SetDefaultOptions();
XenObject = xo;
if (XenObject is Host)
LicencedHost = XenObject as Host;
if (XenObject is Pool)
{
Pool pool = XenObject as Pool;
SetMinimumLicenseValueHost(pool);
}
serverTime.ServerTimeObtained -= ServerTimeUpdatedEventHandler;
serverTime.ServerTimeObtained += ServerTimeUpdatedEventHandler;
if (XenObject != null)
{
XenObject.Connection.ConnectionStateChanged -= Connection_ConnectionStateChanged;
XenObject.Connection.ConnectionStateChanged += Connection_ConnectionStateChanged;
}
}
void Connection_ConnectionStateChanged(object sender, EventArgs e)
{
if (LicencedHost != null)
{
TriggerStatusUpdatedEvent();
}
}
private void SetMinimumLicenseValueHost(Pool pool)
{
LicencedHost = pool.Connection.Resolve(pool.master);
if(LicencedHost == null)
return;
foreach (Host host in pool.Connection.Cache.Hosts)
{
if(host.LicenseExpiryUTC < LicencedHost.LicenseExpiryUTC)
LicencedHost = host;
}
}
private void SetDefaultOptions()
{
CurrentState = HostState.Unknown;
Updated = false;
LicenseExpiresExactlyIn = new TimeSpan();
}
public void BeginUpdate()
{
SetDefaultOptions();
serverTime.Fetch(LicencedHost);
}
private void ServerTimeUpdatedEventHandler(object sender, AsyncServerTimeEventArgs e)
{
if (!e.Success)
{
if(e.QueriedHost == null)
{
log.ErrorFormat("Couldn't get the server time because: {0}", e.Failure.Message);
return;
}
log.ErrorFormat("Couldn't get the server time for {0} because: {1}", e.QueriedHost.name_label, e.Failure.Message);
return;
}
if (LicencedHost != null)
{
CalculateLicenseState();
TriggerStatusUpdatedEvent();
}
}
protected void CalculateLicenseState()
{
PoolLicensingModel = GetLicensingModel(XenObject.Connection);
LicenseExpiresExactlyIn = CalculateLicenceExpiresIn();
CurrentState = CalculateCurrentState();
Updated = true;
}
private void TriggerStatusUpdatedEvent()
{
StatusUpdatedEvent handler = Events[StatusUpdatedEventKey] as StatusUpdatedEvent;
if (handler != null)
handler.Invoke(this, EventArgs.Empty);
}
private bool InRegularGrace
{
get
{
return LicencedHost.license_params != null && LicencedHost.license_params.ContainsKey("grace") && LicenseExpiresIn.Ticks > 0 && LicencedHost.license_params["grace"] == "regular grace";
}
}
private bool InUpgradeGrace
{
get
{
return LicencedHost.license_params != null && LicencedHost.license_params.ContainsKey("grace") && LicenseExpiresIn.Ticks > 0 && LicencedHost.license_params["grace"] == "upgrade grace";
}
}
protected virtual TimeSpan CalculateLicenceExpiresIn()
{
//ServerTime is UTC
DateTime currentRefTime = serverTime.ServerTime;
return LicencedHost.LicenseExpiryUTC.Subtract(currentRefTime);
}
internal static bool PoolIsMixedFreeAndExpiring(IXenObject xenObject)
{
if (xenObject is Pool)
{
if (xenObject.Connection.Cache.Hosts.Length == 1)
return false;
int freeCount = xenObject.Connection.Cache.Hosts.Count(h => Host.GetEdition(h.edition) == Host.Edition.Free);
if (freeCount == 0 || freeCount < xenObject.Connection.Cache.Hosts.Length)
return false;
var expiryGroups = from Host h in xenObject.Connection.Cache.Hosts
let exp = h.LicenseExpiryUTC
group h by exp
into g
select new { ExpiryDate = g.Key, Hosts = g };
if(expiryGroups.Count() > 1)
{
expiryGroups.OrderBy(g => g.ExpiryDate);
if ((expiryGroups.ElementAt(1).ExpiryDate - expiryGroups.ElementAt(0).ExpiryDate).TotalDays > 30)
return true;
}
}
return false;
}
internal static bool PoolIsPartiallyLicensed(IXenObject xenObject)
{
if (xenObject is Pool)
{
if (xenObject.Connection.Cache.Hosts.Length == 1)
return false;
int freeCount = xenObject.Connection.Cache.Hosts.Count(h => Host.GetEdition(h.edition) == Host.Edition.Free);
return freeCount > 0 && freeCount < xenObject.Connection.Cache.Hosts.Length;
}
return false;
}
internal static bool PoolHasMixedLicenses(IXenObject xenObject)
{
var pool = xenObject as Pool;
if (pool != null)
{
if (xenObject.Connection.Cache.Hosts.Length == 1)
return false;
if (xenObject.Connection.Cache.Hosts.Any(h => Host.GetEdition(h.edition) == Host.Edition.Free))
return false;
var licenseGroups = from Host h in xenObject.Connection.Cache.Hosts
let ed = Host.GetEdition(h.edition)
group h by ed;
return licenseGroups.Count() > 1;
}
return false;
}
private HostState CalculateCurrentState()
{
if (ExpiryDate.HasValue && ExpiryDate.Value.Day == 1 && ExpiryDate.Value.Month == 1 && ExpiryDate.Value.Year == 1970)
{
return HostState.Unavailable;
}
if (PoolIsPartiallyLicensed(XenObject))
return HostState.PartiallyLicensed;
if (PoolLicensingModel != LicensingModel.PreClearwater)
{
if (LicenseEdition == Host.Edition.Free)
return HostState.Free;
if (!IsGraceLicence(LicenseExpiresIn))
return HostState.Licensed;
}
if (IsInfinite(LicenseExpiresIn))
{
return HostState.Licensed;
}
if (LicenseExpiresIn.Ticks <= 0)
{
return HostState.Expired;
}
if (IsGraceLicence(LicenseExpiresIn))
{
if (InRegularGrace)
return HostState.RegularGrace;
if (InUpgradeGrace)
return HostState.UpgradeGrace;
return HostState.ExpiresSoon;
}
return LicenseEdition == Host.Edition.Free ? HostState.Free : HostState.Licensed;
}
#region ILicenseStatus Members
public event StatusUpdatedEvent ItemUpdated
{
add { Events.AddHandler(StatusUpdatedEventKey, value); }
remove { Events.RemoveHandler(StatusUpdatedEventKey, value); }
}
public Host.Edition LicenseEdition { get { return Host.GetEdition(LicencedHost.edition); } }
public HostState CurrentState { get; private set; }
public TimeSpan LicenseExpiresExactlyIn { get; private set; }
/// <summary>
/// License expiry, just days, hrs, mins
/// </summary>
public TimeSpan LicenseExpiresIn
{
get
{
return new TimeSpan(LicenseExpiresExactlyIn.Days, LicenseExpiresExactlyIn.Hours, LicenseExpiresExactlyIn.Minutes, 0, 0);
}
}
public DateTime? ExpiryDate
{
get
{
if (LicencedHost.license_params != null && LicencedHost.license_params.ContainsKey("expiry"))
return LicencedHost.LicenseExpiryUTC.ToLocalTime();
return null;
}
}
public LicensingModel PoolLicensingModel { get; private set; }
public string LicenseEntitlements
{
get
{
if (PoolLicensingModel == LicensingModel.Creedence && CurrentState == HostState.Licensed)
{
if (XenObject.Connection.Cache.Hosts.All(h => h.EnterpriseFeaturesEnabled))
return Messages.LICENSE_SUPPORT_AND_ENTERPRISE_FEATURES_ENABLED;
if (XenObject.Connection.Cache.Hosts.All(h => h.DesktopPlusFeaturesEnabled))
return Messages.LICENSE_SUPPORT_AND_DESKTOP_PLUS_FEATURES_ENABLED;
if (XenObject.Connection.Cache.Hosts.All(h => h.DesktopFeaturesEnabled))
return Messages.LICENSE_SUPPORT_AND_DESKTOP_FEATURES_ENABLED;
if (XenObject.Connection.Cache.Hosts.All(h => h.PremiumFeaturesEnabled))
return Messages.LICENSE_SUPPORT_AND_PREMIUM_FEATURES_ENABLED;
if (XenObject.Connection.Cache.Hosts.All(h => h.StandardFeaturesEnabled))
return Messages.LICENSE_SUPPORT_AND_STANDARD_FEATURES_ENABLED;
if (XenObject.Connection.Cache.Hosts.All(h => h.EligibleForSupport))
return Messages.LICENSE_SUPPORT_AND_STANDARD_FEATURES_ENABLED;
return Messages.LICENSE_NOT_ELIGIBLE_FOR_SUPPORT;
}
if ((PoolLicensingModel == LicensingModel.Creedence || PoolLicensingModel == LicensingModel.Clearwater)
&& CurrentState == HostState.Free)
{
return Messages.LICENSE_NOT_ELIGIBLE_FOR_SUPPORT;
}
return Messages.UNKNOWN;
}
}
#endregion
#region LicensingModel
public enum LicensingModel
{
PreClearwater,
Clearwater,
Creedence
}
public static LicensingModel GetLicensingModel(IXenConnection connection)
{
if (Helpers.CreedenceOrGreater(connection))
return LicensingModel.Creedence;
if (Helpers.ClearwaterOrGreater(connection))
return LicensingModel.Clearwater;
return LicensingModel.PreClearwater;
}
#endregion
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool disposed;
public void Dispose(bool disposing)
{
if(!disposed)
{
if(disposing)
{
if (serverTime != null)
serverTime.ServerTimeObtained -= ServerTimeUpdatedEventHandler;
if (XenObject != null && XenObject.Connection != null)
XenObject.Connection.ConnectionStateChanged -= Connection_ConnectionStateChanged;
Events.Dispose();
}
disposed = true;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareUnorderedSingle()
{
var test = new SimpleBinaryOpTest__CompareUnorderedSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareUnorderedSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareUnorderedSingle testClass)
{
var result = Sse.CompareUnordered(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareUnorderedSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.CompareUnordered(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareUnorderedSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleBinaryOpTest__CompareUnorderedSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse.CompareUnordered(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse.CompareUnordered(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse.CompareUnordered(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareUnordered), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareUnordered), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareUnordered), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse.CompareUnordered(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
{
var result = Sse.CompareUnordered(
Sse.LoadVector128((Single*)(pClsVar1)),
Sse.LoadVector128((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareUnordered(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareUnordered(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareUnordered(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareUnorderedSingle();
var result = Sse.CompareUnordered(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareUnorderedSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
{
var result = Sse.CompareUnordered(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse.CompareUnordered(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.CompareUnordered(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse.CompareUnordered(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse.CompareUnordered(
Sse.LoadVector128((Single*)(&test._fld1)),
Sse.LoadVector128((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != ((float.IsNaN(left[0]) || float.IsNaN(right[0])) ? -1 : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != ((float.IsNaN(left[i]) || float.IsNaN(right[i])) ? -1 : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareUnordered)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions
{
/// <summary>
/// Creates a <see cref="LambdaExpression"/> node.
/// This captures a block of code that is similar to a .NET method body.
/// </summary>
/// <remarks>
/// Lambda expressions take input through parameters and are expected to be fully bound.
/// </remarks>
[DebuggerTypeProxy(typeof(LambdaExpressionProxy))]
public abstract class LambdaExpression : Expression, IParameterProvider
{
private readonly Expression _body;
internal LambdaExpression(Expression body)
{
_body = body;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression"/> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type => TypeCore;
internal abstract Type TypeCore { get; }
internal abstract Type PublicType { get; }
/// <summary>
/// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType => ExpressionType.Lambda;
/// <summary>
/// Gets the parameters of the lambda expression.
/// </summary>
public ReadOnlyCollection<ParameterExpression> Parameters => GetOrMakeParameters();
/// <summary>
/// Gets the name of the lambda expression.
/// </summary>
/// <remarks>Used for debugging purposes.</remarks>
public string Name => NameCore;
internal virtual string NameCore => null;
/// <summary>
/// Gets the body of the lambda expression.
/// </summary>
public Expression Body => _body;
/// <summary>
/// Gets the return type of the lambda expression.
/// </summary>
public Type ReturnType => Type.GetInvokeMethod().ReturnType;
/// <summary>
/// Gets the value that indicates if the lambda expression will be compiled with
/// tail call optimization.
/// </summary>
public bool TailCall => TailCallCore;
internal virtual bool TailCallCore => false;
[ExcludeFromCodeCoverage] // Unreachable
internal virtual ReadOnlyCollection<ParameterExpression> GetOrMakeParameters()
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
ParameterExpression IParameterProvider.GetParameter(int index) => GetParameter(index);
[ExcludeFromCodeCoverage] // Unreachable
internal virtual ParameterExpression GetParameter(int index)
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
int IParameterProvider.ParameterCount => ParameterCount;
[ExcludeFromCodeCoverage] // Unreachable
internal virtual int ParameterCount
{
get
{
throw ContractUtils.Unreachable;
}
}
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public Delegate Compile()
{
#if FEATURE_COMPILE
return Compiler.LambdaCompiler.Compile(this);
#else
return new Interpreter.LightCompiler().CompileTop(this).CreateDelegate();
#endif
}
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <param name="preferInterpretation">A <see cref="bool"/> that indicates if the expression should be compiled to an interpreted form, if available.</param>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public Delegate Compile(bool preferInterpretation)
{
#if FEATURE_COMPILE && FEATURE_INTERPRET
if (preferInterpretation)
{
return new Interpreter.LightCompiler().CompileTop(this).CreateDelegate();
}
#endif
return Compile();
}
#if FEATURE_COMPILE_TO_METHODBUILDER
/// <summary>
/// Compiles the lambda into a method definition.
/// </summary>
/// <param name="method">A <see cref="Emit.MethodBuilder"/> which will be used to hold the lambda's IL.</param>
public void CompileToMethod(System.Reflection.Emit.MethodBuilder method)
{
ContractUtils.RequiresNotNull(method, nameof(method));
ContractUtils.Requires(method.IsStatic, nameof(method));
var type = method.DeclaringType as System.Reflection.Emit.TypeBuilder;
if (type == null) throw Error.MethodBuilderDoesNotHaveTypeBuilder();
Compiler.LambdaCompiler.Compile(this, method);
}
#endif
#if FEATURE_COMPILE
internal abstract LambdaExpression Accept(Compiler.StackSpiller spiller);
#endif
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public Delegate Compile(DebugInfoGenerator debugInfoGenerator)
{
return Compile();
}
}
/// <summary>
/// Defines a <see cref="Expression{TDelegate}"/> node.
/// This captures a block of code that is similar to a .NET method body.
/// </summary>
/// <typeparam name="TDelegate">The type of the delegate.</typeparam>
/// <remarks>
/// Lambda expressions take input through parameters and are expected to be fully bound.
/// </remarks>
public class Expression<TDelegate> : LambdaExpression
{
internal Expression(Expression body)
: base(body)
{
}
internal sealed override Type TypeCore => typeof(TDelegate);
internal override Type PublicType => typeof(Expression<TDelegate>);
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public new TDelegate Compile()
{
#if FEATURE_COMPILE
return (TDelegate)(object)Compiler.LambdaCompiler.Compile(this);
#else
return (TDelegate)(object)new Interpreter.LightCompiler().CompileTop(this).CreateDelegate();
#endif
}
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <param name="preferInterpretation">A <see cref="bool"/> that indicates if the expression should be compiled to an interpreted form, if available.</param>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public new TDelegate Compile(bool preferInterpretation)
{
#if FEATURE_COMPILE && FEATURE_INTERPRET
if (preferInterpretation)
{
return (TDelegate)(object)new Interpreter.LightCompiler().CompileTop(this).CreateDelegate();
}
#endif
return Compile();
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="body">The <see cref="LambdaExpression.Body" /> property of the result.</param>
/// <param name="parameters">The <see cref="LambdaExpression.Parameters" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public Expression<TDelegate> Update(Expression body, IEnumerable<ParameterExpression> parameters)
{
if (body == Body)
{
// Ensure parameters is safe to enumerate twice.
// (If this means a second call to ToReadOnly it will return quickly).
ICollection<ParameterExpression> pars;
if (parameters == null)
{
pars = null;
}
else
{
pars = parameters as ICollection<ParameterExpression>;
if (pars == null)
{
parameters = pars = parameters.ToReadOnly();
}
}
if (SameParameters(pars))
{
return this;
}
}
return Lambda<TDelegate>(body, Name, TailCall, parameters);
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual bool SameParameters(ICollection<ParameterExpression> parameters)
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters)
{
throw ContractUtils.Unreachable;
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitLambda(this);
}
#if FEATURE_COMPILE
internal override LambdaExpression Accept(Compiler.StackSpiller spiller)
{
return spiller.Rewrite(this);
}
internal static Expression<TDelegate> Create(Expression body, string name, bool tailCall, IReadOnlyList<ParameterExpression> parameters)
{
if (name == null && !tailCall)
{
return parameters.Count switch
{
0 => new Expression0<TDelegate>(body),
1 => new Expression1<TDelegate>(body, parameters[0]),
2 => new Expression2<TDelegate>(body, parameters[0], parameters[1]),
3 => new Expression3<TDelegate>(body, parameters[0], parameters[1], parameters[2]),
_ => new ExpressionN<TDelegate>(body, parameters),
};
}
return new FullExpression<TDelegate>(body, name, tailCall, parameters);
}
#endif
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public new TDelegate Compile(DebugInfoGenerator debugInfoGenerator)
{
return Compile();
}
}
#if !FEATURE_COMPILE
// Separate expression creation class to hide the CreateExpressionFunc function from users reflecting on Expression<T>
public class ExpressionCreator<TDelegate>
{
public static LambdaExpression CreateExpressionFunc(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters)
{
if (name == null && !tailCall)
{
switch (parameters.Count)
{
case 0: return new Expression0<TDelegate>(body);
case 1: return new Expression1<TDelegate>(body, parameters[0]);
case 2: return new Expression2<TDelegate>(body, parameters[0], parameters[1]);
case 3: return new Expression3<TDelegate>(body, parameters[0], parameters[1], parameters[2]);
default: return new ExpressionN<TDelegate>(body, parameters);
}
}
return new FullExpression<TDelegate>(body, name, tailCall, parameters);
}
}
#endif
internal sealed class Expression0<TDelegate> : Expression<TDelegate>
{
public Expression0(Expression body)
: base(body)
{
}
internal override int ParameterCount => 0;
internal override bool SameParameters(ICollection<ParameterExpression> parameters) =>
parameters == null || parameters.Count == 0;
internal override ParameterExpression GetParameter(int index)
{
throw Error.ArgumentOutOfRange(nameof(index));
}
internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => EmptyReadOnlyCollection<ParameterExpression>.Instance;
internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters)
{
Debug.Assert(body != null);
Debug.Assert(parameters == null || parameters.Length == 0);
return Expression.Lambda<TDelegate>(body, parameters);
}
}
internal sealed class Expression1<TDelegate> : Expression<TDelegate>
{
private object _par0;
public Expression1(Expression body, ParameterExpression par0)
: base(body)
{
_par0 = par0;
}
internal override int ParameterCount => 1;
internal override ParameterExpression GetParameter(int index) =>
index switch
{
0 => ExpressionUtils.ReturnObject<ParameterExpression>(_par0),
_ => throw Error.ArgumentOutOfRange(nameof(index)),
};
internal override bool SameParameters(ICollection<ParameterExpression> parameters)
{
if (parameters != null && parameters.Count == 1)
{
using (IEnumerator<ParameterExpression> en = parameters.GetEnumerator())
{
en.MoveNext();
return en.Current == ExpressionUtils.ReturnObject<ParameterExpression>(_par0);
}
}
return false;
}
internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(this, ref _par0);
internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters)
{
Debug.Assert(body != null);
Debug.Assert(parameters == null || parameters.Length == 1);
if (parameters != null)
{
return Expression.Lambda<TDelegate>(body, parameters);
}
return Expression.Lambda<TDelegate>(body, ExpressionUtils.ReturnObject<ParameterExpression>(_par0));
}
}
internal sealed class Expression2<TDelegate> : Expression<TDelegate>
{
private object _par0;
private readonly ParameterExpression _par1;
public Expression2(Expression body, ParameterExpression par0, ParameterExpression par1)
: base(body)
{
_par0 = par0;
_par1 = par1;
}
internal override int ParameterCount => 2;
internal override ParameterExpression GetParameter(int index) =>
index switch
{
0 => ExpressionUtils.ReturnObject<ParameterExpression>(_par0),
1 => _par1,
_ => throw Error.ArgumentOutOfRange(nameof(index)),
};
internal override bool SameParameters(ICollection<ParameterExpression> parameters)
{
if (parameters != null && parameters.Count == 2)
{
ReadOnlyCollection<ParameterExpression> alreadyCollection = _par0 as ReadOnlyCollection<ParameterExpression>;
if (alreadyCollection != null)
{
return ExpressionUtils.SameElements(parameters, alreadyCollection);
}
using (IEnumerator<ParameterExpression> en = parameters.GetEnumerator())
{
en.MoveNext();
if (en.Current == _par0)
{
en.MoveNext();
return en.Current == _par1;
}
}
}
return false;
}
internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(this, ref _par0);
internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters)
{
Debug.Assert(body != null);
Debug.Assert(parameters == null || parameters.Length == 2);
if (parameters != null)
{
return Expression.Lambda<TDelegate>(body, parameters);
}
return Expression.Lambda<TDelegate>(body, ExpressionUtils.ReturnObject<ParameterExpression>(_par0), _par1);
}
}
internal sealed class Expression3<TDelegate> : Expression<TDelegate>
{
private object _par0;
private readonly ParameterExpression _par1;
private readonly ParameterExpression _par2;
public Expression3(Expression body, ParameterExpression par0, ParameterExpression par1, ParameterExpression par2)
: base(body)
{
_par0 = par0;
_par1 = par1;
_par2 = par2;
}
internal override int ParameterCount => 3;
internal override ParameterExpression GetParameter(int index) =>
index switch
{
0 => ExpressionUtils.ReturnObject<ParameterExpression>(_par0),
1 => _par1,
2 => _par2,
_ => throw Error.ArgumentOutOfRange(nameof(index)),
};
internal override bool SameParameters(ICollection<ParameterExpression> parameters)
{
if (parameters != null && parameters.Count == 3)
{
ReadOnlyCollection<ParameterExpression> alreadyCollection = _par0 as ReadOnlyCollection<ParameterExpression>;
if (alreadyCollection != null)
{
return ExpressionUtils.SameElements(parameters, alreadyCollection);
}
using (IEnumerator<ParameterExpression> en = parameters.GetEnumerator())
{
en.MoveNext();
if (en.Current == _par0)
{
en.MoveNext();
if (en.Current == _par1)
{
en.MoveNext();
return en.Current == _par2;
}
}
}
}
return false;
}
internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(this, ref _par0);
internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters)
{
Debug.Assert(body != null);
Debug.Assert(parameters == null || parameters.Length == 3);
if (parameters != null)
{
return Expression.Lambda<TDelegate>(body, parameters);
}
return Expression.Lambda<TDelegate>(body, ExpressionUtils.ReturnObject<ParameterExpression>(_par0), _par1, _par2);
}
}
internal class ExpressionN<TDelegate> : Expression<TDelegate>
{
private IReadOnlyList<ParameterExpression> _parameters;
public ExpressionN(Expression body, IReadOnlyList<ParameterExpression> parameters)
: base(body)
{
_parameters = parameters;
}
internal override int ParameterCount => _parameters.Count;
internal override ParameterExpression GetParameter(int index) => _parameters[index];
internal override bool SameParameters(ICollection<ParameterExpression> parameters) =>
ExpressionUtils.SameElements(parameters, _parameters);
internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(ref _parameters);
internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters)
{
Debug.Assert(body != null);
Debug.Assert(parameters == null || parameters.Length == _parameters.Count);
return Expression.Lambda<TDelegate>(body, Name, TailCall, parameters ?? _parameters);
}
}
internal sealed class FullExpression<TDelegate> : ExpressionN<TDelegate>
{
public FullExpression(Expression body, string name, bool tailCall, IReadOnlyList<ParameterExpression> parameters)
: base(body, parameters)
{
NameCore = name;
TailCallCore = tailCall;
}
internal override string NameCore { get; }
internal override bool TailCallCore { get; }
}
public partial class Expression
{
/// <summary>
/// Creates an Expression{T} given the delegate type. Caches the
/// factory method to speed up repeated creations for the same T.
/// </summary>
internal static LambdaExpression CreateLambda(Type delegateType, Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters)
{
// Get or create a delegate to the public Expression.Lambda<T>
// method and call that will be used for creating instances of this
// delegate type
Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression> fastPath;
CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>> factories = s_lambdaFactories;
if (factories == null)
{
s_lambdaFactories = factories = new CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>(50);
}
if (!factories.TryGetValue(delegateType, out fastPath))
{
#if FEATURE_COMPILE
MethodInfo create = typeof(Expression<>).MakeGenericType(delegateType).GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic);
#else
MethodInfo create = typeof(ExpressionCreator<>).MakeGenericType(delegateType).GetMethod("CreateExpressionFunc", BindingFlags.Static | BindingFlags.Public);
#endif
if (delegateType.IsCollectible)
{
return (LambdaExpression)create.Invoke(null, new object[] { body, name, tailCall, parameters });
}
factories[delegateType] = fastPath = (Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)create.CreateDelegate(typeof(Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>));
}
return fastPath(body, name, tailCall, parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type.</typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters)
{
return Lambda<TDelegate>(body, false, (IEnumerable<ParameterExpression>)parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type.</typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, params ParameterExpression[] parameters)
{
return Lambda<TDelegate>(body, tailCall, (IEnumerable<ParameterExpression>)parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type.</typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, IEnumerable<ParameterExpression> parameters)
{
return Lambda<TDelegate>(body, null, false, parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type.</typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
return Lambda<TDelegate>(body, null, tailCall, parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type.</typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <param name="name">The name of the lambda. Used for generating debugging info.</param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, string name, IEnumerable<ParameterExpression> parameters)
{
return Lambda<TDelegate>(body, name, false, parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type.</typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="name">The name of the lambda. Used for generating debugging info.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
ReadOnlyCollection<ParameterExpression> parameterList = parameters.ToReadOnly();
ValidateLambdaArgs(typeof(TDelegate), ref body, parameterList, nameof(TDelegate));
return (Expression<TDelegate>)CreateLambda(typeof(TDelegate), body, name, tailCall, parameterList);
}
/// <summary>
/// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, params ParameterExpression[] parameters)
{
return Lambda(body, false, (IEnumerable<ParameterExpression>)parameters);
}
/// <summary>
/// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, bool tailCall, params ParameterExpression[] parameters)
{
return Lambda(body, tailCall, (IEnumerable<ParameterExpression>)parameters);
}
/// <summary>
/// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, IEnumerable<ParameterExpression> parameters)
{
return Lambda(body, null, false, parameters);
}
/// <summary>
/// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
return Lambda(body, null, tailCall, parameters);
}
/// <summary>
/// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, params ParameterExpression[] parameters)
{
return Lambda(delegateType, body, null, false, parameters);
}
/// <summary>
/// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, params ParameterExpression[] parameters)
{
return Lambda(delegateType, body, null, tailCall, parameters);
}
/// <summary>
/// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters)
{
return Lambda(delegateType, body, null, false, parameters);
}
/// <summary>
/// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
return Lambda(delegateType, body, null, tailCall, parameters);
}
/// <summary>
/// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <param name="name">The name for the lambda. Used for emitting debug information.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, string name, IEnumerable<ParameterExpression> parameters)
{
return Lambda(body, name, false, parameters);
}
/// <summary>
/// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="name">The name for the lambda. Used for emitting debug information.</param>
/// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
ContractUtils.RequiresNotNull(body, nameof(body));
ReadOnlyCollection<ParameterExpression> parameterList = parameters.ToReadOnly();
int paramCount = parameterList.Count;
Type[] typeArgs = new Type[paramCount + 1];
if (paramCount > 0)
{
var set = new HashSet<ParameterExpression>();
for (int i = 0; i < paramCount; i++)
{
ParameterExpression param = parameterList[i];
ContractUtils.RequiresNotNull(param, "parameter");
typeArgs[i] = param.IsByRef ? param.Type.MakeByRefType() : param.Type;
if (!set.Add(param))
{
throw Error.DuplicateVariable(param, nameof(parameters), i);
}
}
}
typeArgs[paramCount] = body.Type;
Type delegateType = Compiler.DelegateHelpers.MakeDelegateType(typeArgs);
return CreateLambda(delegateType, body, name, tailCall, parameterList);
}
/// <summary>
/// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <param name="name">The name for the lambda. Used for emitting debug information.</param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, string name, IEnumerable<ParameterExpression> parameters)
{
ReadOnlyCollection<ParameterExpression> paramList = parameters.ToReadOnly();
ValidateLambdaArgs(delegateType, ref body, paramList, nameof(delegateType));
return CreateLambda(delegateType, body, name, false, paramList);
}
/// <summary>
/// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type.
/// </summary>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param>
/// <param name="name">The name for the lambda. Used for emitting debug information.</param>
/// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
ReadOnlyCollection<ParameterExpression> paramList = parameters.ToReadOnly();
ValidateLambdaArgs(delegateType, ref body, paramList, nameof(delegateType));
return CreateLambda(delegateType, body, name, tailCall, paramList);
}
private static void ValidateLambdaArgs(Type delegateType, ref Expression body, ReadOnlyCollection<ParameterExpression> parameters, string paramName)
{
ContractUtils.RequiresNotNull(delegateType, nameof(delegateType));
ExpressionUtils.RequiresCanRead(body, nameof(body));
if (!typeof(MulticastDelegate).IsAssignableFrom(delegateType) || delegateType == typeof(MulticastDelegate))
{
throw Error.LambdaTypeMustBeDerivedFromSystemDelegate(paramName);
}
TypeUtils.ValidateType(delegateType, nameof(delegateType), allowByRef: true, allowPointer: true);
CacheDict<Type, MethodInfo> ldc = s_lambdaDelegateCache;
if (!ldc.TryGetValue(delegateType, out MethodInfo mi))
{
mi = delegateType.GetInvokeMethod();
if (!delegateType.IsCollectible)
{
ldc[delegateType] = mi;
}
}
ParameterInfo[] pis = mi.GetParametersCached();
if (pis.Length > 0)
{
if (pis.Length != parameters.Count)
{
throw Error.IncorrectNumberOfLambdaDeclarationParameters();
}
var set = new HashSet<ParameterExpression>();
for (int i = 0, n = pis.Length; i < n; i++)
{
ParameterExpression pex = parameters[i];
ParameterInfo pi = pis[i];
ExpressionUtils.RequiresCanRead(pex, nameof(parameters), i);
Type pType = pi.ParameterType;
if (pex.IsByRef)
{
if (!pType.IsByRef)
{
//We cannot pass a parameter of T& to a delegate that takes T or any non-ByRef type.
throw Error.ParameterExpressionNotValidAsDelegate(pex.Type.MakeByRefType(), pType);
}
pType = pType.GetElementType();
}
if (!TypeUtils.AreReferenceAssignable(pex.Type, pType))
{
throw Error.ParameterExpressionNotValidAsDelegate(pex.Type, pType);
}
if (!set.Add(pex))
{
throw Error.DuplicateVariable(pex, nameof(parameters), i);
}
}
}
else if (parameters.Count > 0)
{
throw Error.IncorrectNumberOfLambdaDeclarationParameters();
}
if (mi.ReturnType != typeof(void) && !TypeUtils.AreReferenceAssignable(mi.ReturnType, body.Type))
{
if (!TryQuote(mi.ReturnType, ref body))
{
throw Error.ExpressionTypeDoesNotMatchReturn(body.Type, mi.ReturnType);
}
}
}
private enum TryGetFuncActionArgsResult
{
Valid,
ArgumentNull,
ByRef,
PointerOrVoid
}
private static TryGetFuncActionArgsResult ValidateTryGetFuncActionArgs(Type[] typeArgs)
{
if (typeArgs == null)
{
return TryGetFuncActionArgsResult.ArgumentNull;
}
for (int i = 0; i < typeArgs.Length; i++)
{
Type a = typeArgs[i];
if (a == null)
{
return TryGetFuncActionArgsResult.ArgumentNull;
}
if (a.IsByRef)
{
return TryGetFuncActionArgsResult.ByRef;
}
if (a == typeof(void) || a.IsPointer)
{
return TryGetFuncActionArgsResult.PointerOrVoid;
}
}
return TryGetFuncActionArgsResult.Valid;
}
/// <summary>
/// Creates a <see cref="System.Type"/> object that represents a generic System.Func delegate type that has specific type arguments.
/// The last type argument specifies the return type of the created delegate.
/// </summary>
/// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Func delegate type.</param>
/// <returns>The type of a System.Func delegate that has the specified type arguments.</returns>
public static Type GetFuncType(params Type[] typeArgs)
{
switch (ValidateTryGetFuncActionArgs(typeArgs))
{
case TryGetFuncActionArgsResult.ArgumentNull:
throw new ArgumentNullException(nameof(typeArgs));
case TryGetFuncActionArgsResult.ByRef:
throw Error.TypeMustNotBeByRef(nameof(typeArgs));
default:
// This includes pointers or void. We allow the exception that comes
// from trying to use them as generic arguments to pass through.
Type result = Compiler.DelegateHelpers.GetFuncType(typeArgs);
if (result == null)
{
throw Error.IncorrectNumberOfTypeArgsForFunc(nameof(typeArgs));
}
return result;
}
}
/// <summary>
/// Creates a <see cref="System.Type"/> object that represents a generic System.Func delegate type that has specific type arguments.
/// The last type argument specifies the return type of the created delegate.
/// </summary>
/// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Func delegate type.</param>
/// <param name="funcType">When this method returns, contains the generic System.Func delegate type that has specific type arguments. Contains null if there is no generic System.Func delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param>
/// <returns>true if generic System.Func delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns>
public static bool TryGetFuncType(Type[] typeArgs, out Type funcType)
{
if (ValidateTryGetFuncActionArgs(typeArgs) == TryGetFuncActionArgsResult.Valid)
{
return (funcType = Compiler.DelegateHelpers.GetFuncType(typeArgs)) != null;
}
funcType = null;
return false;
}
/// <summary>
/// Creates a <see cref="System.Type"/> object that represents a generic System.Action delegate type that has specific type arguments.
/// </summary>
/// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Action delegate type.</param>
/// <returns>The type of a System.Action delegate that has the specified type arguments.</returns>
public static Type GetActionType(params Type[] typeArgs)
{
switch (ValidateTryGetFuncActionArgs(typeArgs))
{
case TryGetFuncActionArgsResult.ArgumentNull:
throw new ArgumentNullException(nameof(typeArgs));
case TryGetFuncActionArgsResult.ByRef:
throw Error.TypeMustNotBeByRef(nameof(typeArgs));
default:
// This includes pointers or void. We allow the exception that comes
// from trying to use them as generic arguments to pass through.
Type result = Compiler.DelegateHelpers.GetActionType(typeArgs);
if (result == null)
{
throw Error.IncorrectNumberOfTypeArgsForAction(nameof(typeArgs));
}
return result;
}
}
/// <summary>
/// Creates a <see cref="System.Type"/> object that represents a generic System.Action delegate type that has specific type arguments.
/// </summary>
/// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Action delegate type.</param>
/// <param name="actionType">When this method returns, contains the generic System.Action delegate type that has specific type arguments. Contains null if there is no generic System.Action delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param>
/// <returns>true if generic System.Action delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns>
public static bool TryGetActionType(Type[] typeArgs, out Type actionType)
{
if (ValidateTryGetFuncActionArgs(typeArgs) == TryGetFuncActionArgsResult.Valid)
{
return (actionType = Compiler.DelegateHelpers.GetActionType(typeArgs)) != null;
}
actionType = null;
return false;
}
/// <summary>
/// Gets a <see cref="System.Type"/> object that represents a generic System.Func or System.Action delegate type that has specific type arguments.
/// The last type argument determines the return type of the delegate. If no Func or Action is large enough, it will generate a custom
/// delegate type.
/// </summary>
/// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments of the delegate type.</param>
/// <returns>The delegate type.</returns>
/// <remarks>
/// As with Func, the last argument is the return type. It can be set
/// to <see cref="System.Void"/> to produce an Action.</remarks>
public static Type GetDelegateType(params Type[] typeArgs)
{
ContractUtils.RequiresNotEmpty(typeArgs, nameof(typeArgs));
ContractUtils.RequiresNotNullItems(typeArgs, nameof(typeArgs));
return Compiler.DelegateHelpers.MakeDelegateType(typeArgs);
}
}
}
| |
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using Should;
using Xunit;
namespace AutoMapper.UnitTests
{
using Internal;
public class DelegateFactoryTests
{
protected DelegateFactory DelegateFactory => new DelegateFactory();
[Fact]
public void MethodTests()
{
MethodInfo method = typeof(String).GetMethod("StartsWith", new[] { typeof(string) });
LateBoundMethod callback = DelegateFactory.CreateGet(method);
string foo = "this is a test";
bool result = (bool)callback(foo, new[] { "this" });
result.ShouldBeTrue();
}
[Fact]
public void PropertyTests()
{
PropertyInfo property = typeof(Source).GetProperty("Value", typeof(int));
LateBoundPropertyGet callback = DelegateFactory.CreateGet(property);
var source = new Source {Value = 5};
int result = (int)callback(source);
result.ShouldEqual(5);
}
[Fact]
public void FieldTests()
{
FieldInfo field = typeof(Source).GetField("Value2");
LateBoundFieldGet callback = DelegateFactory.CreateGet(field);
var source = new Source {Value2 = 15};
int result = (int)callback(source);
result.ShouldEqual(15);
}
[Fact]
public void Should_set_field_when_field_is_a_value_type()
{
var sourceType = typeof (Source);
FieldInfo field = sourceType.GetField("Value2");
LateBoundFieldSet callback = DelegateFactory.CreateSet(field);
var source = new Source();
callback(source, 5);
source.Value2.ShouldEqual(5);
}
[Fact]
public void Should_set_field_when_field_is_a_reference_type()
{
var sourceType = typeof (Source);
FieldInfo field = sourceType.GetField("Value3");
LateBoundFieldSet callback = DelegateFactory.CreateSet(field);
var source = new Source();
callback(source, "hello");
source.Value3.ShouldEqual("hello");
}
[Fact]
public void Should_set_property_when_property_is_a_value_type()
{
var sourceType = typeof (Source);
PropertyInfo property = sourceType.GetProperty("Value");
LateBoundPropertySet callback = DelegateFactory.CreateSet(property);
var source = new Source();
callback(source, 5);
source.Value.ShouldEqual(5);
}
[Fact]
public void Should_set_property_when_property_is_a_value_type_and_type_is_interface()
{
var sourceType = typeof (ISource);
PropertyInfo property = sourceType.GetProperty("Value");
LateBoundPropertySet callback = DelegateFactory.CreateSet(property);
var source = new Source();
callback(source, 5);
source.Value.ShouldEqual(5);
}
[Fact]
public void Should_set_property_when_property_is_a_reference_type()
{
var sourceType = typeof(Source);
PropertyInfo property = sourceType.GetProperty("Value4");
LateBoundPropertySet callback = DelegateFactory.CreateSet(property);
var source = new Source();
callback(source, "hello");
source.Value4.ShouldEqual("hello");
}
internal delegate void DoIt3(ref ValueSource source, string value);
private void SetValue(object thing, object value)
{
var source = ((ValueSource) thing);
source.Value = (string)value;
}
[Fact]
public void Test_with_create_ctor()
{
var sourceType = typeof(Source);
LateBoundCtor ctor = DelegateFactory.CreateCtor(sourceType);
var target = ctor();
target.ShouldBeType<Source>();
}
[Fact]
public void Test_with_value_object_create_ctor()
{
var sourceType = typeof(ValueSource);
LateBoundCtor ctor = DelegateFactory.CreateCtor(sourceType);
var target = ctor();
target.ShouldBeType<ValueSource>();
}
public object CreateValueSource()
{
return new ValueSource();
}
public delegate void SetValueDelegate(ref ValueSource source, string value);
private static void SetValue2(ref object thing, object value)
{
var source = ((ValueSource)thing);
source.Value = (string)value;
thing = source;
}
private void SetValue(ref ValueSource thing, string value)
{
thing.Value = value;
}
private void DoIt(object source, object value)
{
((Source)source).Value2 = (int)value;
}
private void DoIt4(object source, object value)
{
var valueSource = ((ValueSource)source);
valueSource.Value = (string)value;
}
private void DoIt2(object source, object value)
{
int toSet = value == null ? default(int) : (int) value;
((Source)source).Value = toSet;
}
private void DoIt4(ref object source, object value)
{
var valueSource = (ValueSource) source;
valueSource.Value = (string) value;
}
private static class Test<T>
{
private static T DoIt()
{
return default(T);
}
}
public struct ValueSource
{
public string Value { get; set; }
}
public interface ISource
{
int Value { get; set; }
}
public class Source : ISource
{
public int Value { get; set; }
public int Value2;
public string Value3;
public string Value4 { get; set; }
}
}
}
| |
// 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.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.Common
{
internal static class ADP
{
// The class ADP defines the exceptions that are specific to the Adapters.
// The class contains functions that take the proper informational variables and then construct
// the appropriate exception with an error string obtained from the resource framework.
// The exception is then returned to the caller, so that the caller may then throw from its
// location so that the catcher of the exception will have the appropriate call stack.
// This class is used so that there will be compile time checking of error messages.
internal static Task<T> CreatedTaskWithCancellation<T>() => Task.FromCanceled<T>(new CancellationToken(true));
internal static readonly Task<bool> s_trueTask = Task.FromResult(true);
internal static readonly Task<bool> s_falseTask = Task.FromResult(false);
// this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it
private static void TraceException(string trace, Exception e)
{
Debug.Assert(e != null, "TraceException: null Exception");
if (e != null)
{
DataCommonEventSource.Log.Trace(trace, e);
}
}
internal static void TraceExceptionAsReturnValue(Exception e)
{
TraceException("<comm.ADP.TraceException|ERR|THROW> '{0}'", e);
}
internal static void TraceExceptionForCapture(Exception e)
{
Debug.Assert(IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
TraceException("<comm.ADP.TraceException|ERR|CATCH> '{0}'", e);
}
internal static void TraceExceptionWithoutRethrow(Exception e)
{
Debug.Assert(IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
TraceException("<comm.ADP.TraceException|ERR|CATCH> '{0}'", e);
}
internal static ArgumentException Argument(string error)
{
ArgumentException e = new ArgumentException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException Argument(string error, Exception inner)
{
ArgumentException e = new ArgumentException(error, inner);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException Argument(string error, string parameter)
{
ArgumentException e = new ArgumentException(error, parameter);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentNullException ArgumentNull(string parameter)
{
ArgumentNullException e = new ArgumentNullException(parameter);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentNullException ArgumentNull(string parameter, string error)
{
ArgumentNullException e = new ArgumentNullException(parameter, error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName)
{
ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName)
{
ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message);
TraceExceptionAsReturnValue(e);
return e;
}
internal static DataException Data(string message)
{
DataException e = new DataException(message);
TraceExceptionAsReturnValue(e);
return e;
}
internal static IndexOutOfRangeException IndexOutOfRange(string error)
{
IndexOutOfRangeException e = new IndexOutOfRangeException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static InvalidCastException InvalidCast(string error)
{
return InvalidCast(error, null);
}
internal static InvalidCastException InvalidCast(string error, Exception inner)
{
InvalidCastException e = new InvalidCastException(error, inner);
TraceExceptionAsReturnValue(e);
return e;
}
internal static InvalidOperationException InvalidOperation(string error)
{
InvalidOperationException e = new InvalidOperationException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static NotSupportedException NotSupported()
{
NotSupportedException e = new NotSupportedException();
TraceExceptionAsReturnValue(e);
return e;
}
internal static NotSupportedException NotSupported(string error)
{
NotSupportedException e = new NotSupportedException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static InvalidOperationException DataAdapter(string error)
{
return InvalidOperation(error);
}
private static InvalidOperationException Provider(string error)
{
return InvalidOperation(error);
}
internal static ArgumentException InvalidMultipartName(string property, string value)
{
ArgumentException e = new ArgumentException(SR.Format(SR.ADP_InvalidMultipartName, property, value));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value)
{
ArgumentException e = new ArgumentException(SR.Format(SR.ADP_InvalidMultipartNameQuoteUsage, property, value));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit)
{
ArgumentException e = new ArgumentException(SR.Format(SR.ADP_InvalidMultipartNameToManyParts, property, value, limit));
TraceExceptionAsReturnValue(e);
return e;
}
internal static void CheckArgumentLength(string value, string parameterName)
{
CheckArgumentNull(value, parameterName);
if (0 == value.Length)
{
throw Argument(SR.Format(SR.ADP_EmptyString, parameterName));
}
}
internal static void CheckArgumentLength(Array value, string parameterName)
{
CheckArgumentNull(value, parameterName);
if (0 == value.Length)
{
throw Argument(SR.Format(SR.ADP_EmptyArray, parameterName));
}
}
internal static void CheckArgumentNull(object value, string parameterName)
{
if (null == value)
{
throw ArgumentNull(parameterName);
}
}
private static readonly Type s_outOfMemoryType = typeof(OutOfMemoryException);
private static readonly Type s_nullReferenceType = typeof(NullReferenceException);
private static readonly Type s_accessViolationType = typeof(AccessViolationException);
private static readonly Type s_securityType = typeof(SecurityException);
internal static bool IsCatchableExceptionType(Exception e)
{
Debug.Assert(e != null, "Unexpected null exception!");
// a 'catchable' exception is defined by what it is not.
Type type = e.GetType();
return
type != s_outOfMemoryType &&
type != s_nullReferenceType &&
type != s_accessViolationType &&
!s_securityType.IsAssignableFrom(type);
}
internal static bool IsCatchableOrSecurityExceptionType(Exception e)
{
Debug.Assert(e != null, "Unexpected null exception!");
// a 'catchable' exception is defined by what it is not.
// since IsCatchableExceptionType defined SecurityException as not 'catchable'
// this method will return true for SecurityException has being catchable.
// the other way to write this method is, but then SecurityException is checked twice
// return ((e is SecurityException) || IsCatchableExceptionType(e));
Type type = e.GetType();
return
type != s_outOfMemoryType &&
type != s_nullReferenceType &&
type != s_accessViolationType;
}
// Invalid Enumeration
internal static ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value)
{
return ArgumentOutOfRange(SR.Format(SR.ADP_InvalidEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
}
internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, string value, string method)
{
return ArgumentOutOfRange(SR.Format(SR.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name);
}
internal static ArgumentOutOfRangeException InvalidAcceptRejectRule(AcceptRejectRule value)
{
#if DEBUG
switch (value)
{
case AcceptRejectRule.None:
case AcceptRejectRule.Cascade:
Debug.Assert(false, "valid AcceptRejectRule " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(AcceptRejectRule), (int)value);
}
// DbCommandBuilder.CatalogLocation
internal static ArgumentOutOfRangeException InvalidCatalogLocation(CatalogLocation value)
{
#if DEBUG
switch (value)
{
case CatalogLocation.Start:
case CatalogLocation.End:
Debug.Assert(false, "valid CatalogLocation " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(CatalogLocation), (int)value);
}
internal static ArgumentOutOfRangeException InvalidConflictOptions(ConflictOption value)
{
#if DEBUG
switch (value)
{
case ConflictOption.CompareAllSearchableValues:
case ConflictOption.CompareRowVersion:
case ConflictOption.OverwriteChanges:
Debug.Assert(false, "valid ConflictOption " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(ConflictOption), (int)value);
}
// IDataAdapter.Update
internal static ArgumentOutOfRangeException InvalidDataRowState(DataRowState value)
{
#if DEBUG
switch (value)
{
case DataRowState.Detached:
case DataRowState.Unchanged:
case DataRowState.Added:
case DataRowState.Deleted:
case DataRowState.Modified:
Debug.Assert(false, "valid DataRowState " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(DataRowState), (int)value);
}
// KeyRestrictionBehavior
internal static ArgumentOutOfRangeException InvalidKeyRestrictionBehavior(KeyRestrictionBehavior value)
{
#if DEBUG
switch (value)
{
case KeyRestrictionBehavior.PreventUsage:
case KeyRestrictionBehavior.AllowOnly:
Debug.Assert(false, "valid KeyRestrictionBehavior " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(KeyRestrictionBehavior), (int)value);
}
// IDataAdapter.FillLoadOption
internal static ArgumentOutOfRangeException InvalidLoadOption(LoadOption value)
{
#if DEBUG
switch (value)
{
case LoadOption.OverwriteChanges:
case LoadOption.PreserveChanges:
case LoadOption.Upsert:
Debug.Assert(false, "valid LoadOption " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(LoadOption), (int)value);
}
// IDataAdapter.MissingMappingAction
internal static ArgumentOutOfRangeException InvalidMissingMappingAction(MissingMappingAction value)
{
#if DEBUG
switch (value)
{
case MissingMappingAction.Passthrough:
case MissingMappingAction.Ignore:
case MissingMappingAction.Error:
Debug.Assert(false, "valid MissingMappingAction " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(MissingMappingAction), (int)value);
}
// IDataAdapter.MissingSchemaAction
internal static ArgumentOutOfRangeException InvalidMissingSchemaAction(MissingSchemaAction value)
{
#if DEBUG
switch (value)
{
case MissingSchemaAction.Add:
case MissingSchemaAction.Ignore:
case MissingSchemaAction.Error:
case MissingSchemaAction.AddWithKey:
Debug.Assert(false, "valid MissingSchemaAction " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(MissingSchemaAction), (int)value);
}
internal static ArgumentOutOfRangeException InvalidRule(Rule value)
{
#if DEBUG
switch (value)
{
case Rule.None:
case Rule.Cascade:
case Rule.SetNull:
case Rule.SetDefault:
Debug.Assert(false, "valid Rule " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(Rule), (int)value);
}
// IDataAdapter.FillSchema
internal static ArgumentOutOfRangeException InvalidSchemaType(SchemaType value)
{
#if DEBUG
switch (value)
{
case SchemaType.Source:
case SchemaType.Mapped:
Debug.Assert(false, "valid SchemaType " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(SchemaType), (int)value);
}
// RowUpdatingEventArgs.StatementType
internal static ArgumentOutOfRangeException InvalidStatementType(StatementType value)
{
#if DEBUG
switch (value)
{
case StatementType.Select:
case StatementType.Insert:
case StatementType.Update:
case StatementType.Delete:
case StatementType.Batch:
Debug.Assert(false, "valid StatementType " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(StatementType), (int)value);
}
// RowUpdatingEventArgs.UpdateStatus
internal static ArgumentOutOfRangeException InvalidUpdateStatus(UpdateStatus value)
{
#if DEBUG
switch (value)
{
case UpdateStatus.Continue:
case UpdateStatus.ErrorsOccurred:
case UpdateStatus.SkipAllRemainingRows:
case UpdateStatus.SkipCurrentRow:
Debug.Assert(false, "valid UpdateStatus " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(UpdateStatus), (int)value);
}
internal static ArgumentOutOfRangeException NotSupportedStatementType(StatementType value, string method)
{
return NotSupportedEnumerationValue(typeof(StatementType), value.ToString(), method);
}
//
// DbConnectionOptions, DataAccess
//
internal static ArgumentException ConnectionStringSyntax(int index)
{
return Argument(SR.Format(SR.ADP_ConnectionStringSyntax, index));
}
internal static ArgumentException KeywordNotSupported(string keyword)
{
return Argument(SR.Format(SR.ADP_KeywordNotSupported, keyword));
}
internal static ArgumentException InvalidKeyname(string parameterName)
{
return Argument(SR.ADP_InvalidKey, parameterName);
}
internal static ArgumentException InvalidValue(string parameterName)
{
return Argument(SR.ADP_InvalidValue, parameterName);
}
internal static ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException)
{
return ADP.Argument(SR.Format(SR.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException);
}
//
// DbConnection
//
private static string ConnectionStateMsg(ConnectionState state)
{
switch (state)
{
case (ConnectionState.Closed):
case (ConnectionState.Connecting | ConnectionState.Broken): // treated the same as closed
return SR.ADP_ConnectionStateMsg_Closed;
case (ConnectionState.Connecting):
return SR.ADP_ConnectionStateMsg_Connecting;
case (ConnectionState.Open):
return SR.ADP_ConnectionStateMsg_Open;
case (ConnectionState.Open | ConnectionState.Executing):
return SR.ADP_ConnectionStateMsg_OpenExecuting;
case (ConnectionState.Open | ConnectionState.Fetching):
return SR.ADP_ConnectionStateMsg_OpenFetching;
default:
return SR.Format(SR.ADP_ConnectionStateMsg, state.ToString());
}
}
//
// : DbConnectionOptions, DataAccess, SqlClient
//
internal static Exception InvalidConnectionOptionValue(string key)
{
return InvalidConnectionOptionValue(key, null);
}
internal static Exception InvalidConnectionOptionValue(string key, Exception inner)
{
return Argument(SR.Format(SR.ADP_InvalidConnectionOptionValue, key), inner);
}
//
// DataAccess
//
internal static Exception WrongType(Type got, Type expected)
{
return Argument(SR.Format(SR.SQL_WrongType, got.ToString(), expected.ToString()));
}
//
// Generic Data Provider Collection
//
internal static ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection)
{
return Argument(SR.Format(SR.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name));
}
internal static ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType)
{
return ArgumentNull(parameter, SR.Format(SR.ADP_CollectionNullValue, collection.Name, itemType.Name));
}
internal static IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count)
{
return IndexOutOfRange(SR.Format(SR.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture)));
}
internal static IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection)
{
return IndexOutOfRange(SR.Format(SR.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name));
}
internal static InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue)
{
return InvalidCast(SR.Format(SR.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name));
}
internal static Exception CollectionUniqueValue(Type itemType, string propertyName, string propertyValue)
{
return Argument(SR.Format(SR.ADP_CollectionUniqueValue, itemType.Name, propertyName, propertyValue));
}
internal static ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection)
{
return Argument(SR.Format(SR.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
}
internal static ArgumentException ParametersIsParent(Type parameterType, ICollection collection)
{
return Argument(SR.Format(SR.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
}
// IDbDataAdapter.Fill(Schema)
internal static InvalidOperationException MissingSelectCommand(string method)
{
return Provider(SR.Format(SR.ADP_MissingSelectCommand, method));
}
//
// AdapterMappingException
//
private static InvalidOperationException DataMapping(string error)
{
return InvalidOperation(error);
}
// DataColumnMapping.GetDataColumnBySchemaAction
internal static InvalidOperationException ColumnSchemaExpression(string srcColumn, string cacheColumn)
{
return DataMapping(SR.Format(SR.ADP_ColumnSchemaExpression, srcColumn, cacheColumn));
}
// DataColumnMapping.GetDataColumnBySchemaAction
internal static InvalidOperationException ColumnSchemaMismatch(string srcColumn, Type srcType, DataColumn column)
{
return DataMapping(SR.Format(SR.ADP_ColumnSchemaMismatch, srcColumn, srcType.Name, column.ColumnName, column.DataType.Name));
}
// DataColumnMapping.GetDataColumnBySchemaAction
internal static InvalidOperationException ColumnSchemaMissing(string cacheColumn, string tableName, string srcColumn)
{
if (string.IsNullOrEmpty(tableName))
{
return InvalidOperation(SR.Format(SR.ADP_ColumnSchemaMissing1, cacheColumn, tableName, srcColumn));
}
return DataMapping(SR.Format(SR.ADP_ColumnSchemaMissing2, cacheColumn, tableName, srcColumn));
}
// DataColumnMappingCollection.GetColumnMappingBySchemaAction
internal static InvalidOperationException MissingColumnMapping(string srcColumn)
{
return DataMapping(SR.Format(SR.ADP_MissingColumnMapping, srcColumn));
}
// DataTableMapping.GetDataTableBySchemaAction
internal static InvalidOperationException MissingTableSchema(string cacheTable, string srcTable)
{
return DataMapping(SR.Format(SR.ADP_MissingTableSchema, cacheTable, srcTable));
}
// DataTableMappingCollection.GetTableMappingBySchemaAction
internal static InvalidOperationException MissingTableMapping(string srcTable)
{
return DataMapping(SR.Format(SR.ADP_MissingTableMapping, srcTable));
}
// DbDataAdapter.Update
internal static InvalidOperationException MissingTableMappingDestination(string dstTable)
{
return DataMapping(SR.Format(SR.ADP_MissingTableMappingDestination, dstTable));
}
//
// DataColumnMappingCollection, DataAccess
//
internal static Exception InvalidSourceColumn(string parameter)
{
return Argument(SR.ADP_InvalidSourceColumn, parameter);
}
internal static Exception ColumnsAddNullAttempt(string parameter)
{
return CollectionNullValue(parameter, typeof(DataColumnMappingCollection), typeof(DataColumnMapping));
}
internal static Exception ColumnsDataSetColumn(string cacheColumn)
{
return CollectionIndexString(typeof(DataColumnMapping), ADP.DataSetColumn, cacheColumn, typeof(DataColumnMappingCollection));
}
internal static Exception ColumnsIndexInt32(int index, IColumnMappingCollection collection)
{
return CollectionIndexInt32(index, collection.GetType(), collection.Count);
}
internal static Exception ColumnsIndexSource(string srcColumn)
{
return CollectionIndexString(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn, typeof(DataColumnMappingCollection));
}
internal static Exception ColumnsIsNotParent(ICollection collection)
{
return ParametersIsNotParent(typeof(DataColumnMapping), collection);
}
internal static Exception ColumnsIsParent(ICollection collection)
{
return ParametersIsParent(typeof(DataColumnMapping), collection);
}
internal static Exception ColumnsUniqueSourceColumn(string srcColumn)
{
return CollectionUniqueValue(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn);
}
internal static Exception NotADataColumnMapping(object value)
{
return CollectionInvalidType(typeof(DataColumnMappingCollection), typeof(DataColumnMapping), value);
}
//
// DataTableMappingCollection, DataAccess
//
internal static Exception InvalidSourceTable(string parameter)
{
return Argument(SR.ADP_InvalidSourceTable, parameter);
}
internal static Exception TablesAddNullAttempt(string parameter)
{
return CollectionNullValue(parameter, typeof(DataTableMappingCollection), typeof(DataTableMapping));
}
internal static Exception TablesDataSetTable(string cacheTable)
{
return CollectionIndexString(typeof(DataTableMapping), ADP.DataSetTable, cacheTable, typeof(DataTableMappingCollection));
}
internal static Exception TablesIndexInt32(int index, ITableMappingCollection collection)
{
return CollectionIndexInt32(index, collection.GetType(), collection.Count);
}
internal static Exception TablesIsNotParent(ICollection collection)
{
return ParametersIsNotParent(typeof(DataTableMapping), collection);
}
internal static Exception TablesIsParent(ICollection collection)
{
return ParametersIsParent(typeof(DataTableMapping), collection);
}
internal static Exception TablesSourceIndex(string srcTable)
{
return CollectionIndexString(typeof(DataTableMapping), ADP.SourceTable, srcTable, typeof(DataTableMappingCollection));
}
internal static Exception TablesUniqueSourceTable(string srcTable)
{
return CollectionUniqueValue(typeof(DataTableMapping), ADP.SourceTable, srcTable);
}
internal static Exception NotADataTableMapping(object value)
{
return CollectionInvalidType(typeof(DataTableMappingCollection), typeof(DataTableMapping), value);
}
//
// IDbCommand
//
internal static InvalidOperationException UpdateConnectionRequired(StatementType statementType, bool isRowUpdatingCommand)
{
string resource;
if (isRowUpdatingCommand)
{
resource = SR.ADP_ConnectionRequired_Clone;
}
else
{
switch (statementType)
{
case StatementType.Insert:
resource = SR.ADP_ConnectionRequired_Insert;
break;
case StatementType.Update:
resource = SR.ADP_ConnectionRequired_Update;
break;
case StatementType.Delete:
resource = SR.ADP_ConnectionRequired_Delete;
break;
case StatementType.Batch:
resource = SR.ADP_ConnectionRequired_Batch;
goto default;
#if DEBUG
case StatementType.Select:
Debug.Assert(false, "shouldn't be here");
goto default;
#endif
default:
throw ADP.InvalidStatementType(statementType);
}
}
return InvalidOperation(resource);
}
internal static InvalidOperationException ConnectionRequired_Res(string method) =>
InvalidOperation("ADP_ConnectionRequired_" + method);
internal static InvalidOperationException UpdateOpenConnectionRequired(StatementType statementType, bool isRowUpdatingCommand, ConnectionState state)
{
string resource;
if (isRowUpdatingCommand)
{
resource = SR.ADP_OpenConnectionRequired_Clone;
}
else
{
switch (statementType)
{
case StatementType.Insert:
resource = SR.ADP_OpenConnectionRequired_Insert;
break;
case StatementType.Update:
resource = SR.ADP_OpenConnectionRequired_Update;
break;
case StatementType.Delete:
resource = SR.ADP_OpenConnectionRequired_Delete;
break;
#if DEBUG
case StatementType.Select:
Debug.Assert(false, "shouldn't be here");
goto default;
case StatementType.Batch:
Debug.Assert(false, "isRowUpdatingCommand should have been true");
goto default;
#endif
default:
throw ADP.InvalidStatementType(statementType);
}
}
return InvalidOperation(SR.Format(resource, ADP.ConnectionStateMsg(state)));
}
internal static Exception InvalidSeekOrigin(string parameterName)
{
return ArgumentOutOfRange(SR.ADP_InvalidSeekOrigin, parameterName);
}
//
// DbDataAdapter
//
internal static ArgumentException UnwantedStatementType(StatementType statementType)
{
return Argument(SR.Format(SR.ADP_UnwantedStatementType, statementType.ToString()));
}
//
// DbDataAdapter.FillSchema
//
internal static Exception FillSchemaRequiresSourceTableName(string parameter)
{
return Argument(SR.ADP_FillSchemaRequiresSourceTableName, parameter);
}
//
// DbDataAdapter.Fill
//
internal static Exception InvalidMaxRecords(string parameter, int max)
{
return Argument(SR.Format(SR.ADP_InvalidMaxRecords, max.ToString(CultureInfo.InvariantCulture)), parameter);
}
internal static Exception InvalidStartRecord(string parameter, int start)
{
return Argument(SR.Format(SR.ADP_InvalidStartRecord, start.ToString(CultureInfo.InvariantCulture)), parameter);
}
internal static Exception FillRequires(string parameter)
{
return ArgumentNull(parameter);
}
internal static Exception FillRequiresSourceTableName(string parameter)
{
return Argument(SR.ADP_FillRequiresSourceTableName, parameter);
}
internal static Exception FillChapterAutoIncrement()
{
return InvalidOperation(SR.ADP_FillChapterAutoIncrement);
}
internal static InvalidOperationException MissingDataReaderFieldType(int index)
{
return DataAdapter(SR.Format(SR.ADP_MissingDataReaderFieldType, index));
}
internal static InvalidOperationException OnlyOneTableForStartRecordOrMaxRecords()
{
return DataAdapter(SR.ADP_OnlyOneTableForStartRecordOrMaxRecords);
}
//
// DbDataAdapter.Update
//
internal static ArgumentNullException UpdateRequiresNonNullDataSet(string parameter)
{
return ArgumentNull(parameter);
}
internal static InvalidOperationException UpdateRequiresSourceTable(string defaultSrcTableName)
{
return InvalidOperation(SR.Format(SR.ADP_UpdateRequiresSourceTable, defaultSrcTableName));
}
internal static InvalidOperationException UpdateRequiresSourceTableName(string srcTable)
{
return InvalidOperation(SR.Format(SR.ADP_UpdateRequiresSourceTableName, srcTable));
}
internal static ArgumentNullException UpdateRequiresDataTable(string parameter)
{
return ArgumentNull(parameter);
}
internal static Exception UpdateConcurrencyViolation(StatementType statementType, int affected, int expected, DataRow[] dataRows)
{
string resource;
switch (statementType)
{
case StatementType.Update:
resource = SR.ADP_UpdateConcurrencyViolation_Update;
break;
case StatementType.Delete:
resource = SR.ADP_UpdateConcurrencyViolation_Delete;
break;
case StatementType.Batch:
resource = SR.ADP_UpdateConcurrencyViolation_Batch;
break;
#if DEBUG
case StatementType.Select:
case StatementType.Insert:
Debug.Assert(false, "should be here");
goto default;
#endif
default:
throw ADP.InvalidStatementType(statementType);
}
DBConcurrencyException exception = new DBConcurrencyException(SR.Format(resource, affected.ToString(CultureInfo.InvariantCulture), expected.ToString(CultureInfo.InvariantCulture)), null, dataRows);
TraceExceptionAsReturnValue(exception);
return exception;
}
internal static InvalidOperationException UpdateRequiresCommand(StatementType statementType, bool isRowUpdatingCommand)
{
string resource;
if (isRowUpdatingCommand)
{
resource = SR.ADP_UpdateRequiresCommandClone;
}
else
{
switch (statementType)
{
case StatementType.Select:
resource = SR.ADP_UpdateRequiresCommandSelect;
break;
case StatementType.Insert:
resource = SR.ADP_UpdateRequiresCommandInsert;
break;
case StatementType.Update:
resource = SR.ADP_UpdateRequiresCommandUpdate;
break;
case StatementType.Delete:
resource = SR.ADP_UpdateRequiresCommandDelete;
break;
#if DEBUG
case StatementType.Batch:
Debug.Assert(false, "isRowUpdatingCommand should have been true");
goto default;
#endif
default:
throw ADP.InvalidStatementType(statementType);
}
}
return InvalidOperation(resource);
}
internal static ArgumentException UpdateMismatchRowTable(int i)
{
return Argument(SR.Format(SR.ADP_UpdateMismatchRowTable, i.ToString(CultureInfo.InvariantCulture)));
}
internal static DataException RowUpdatedErrors()
{
return Data(SR.ADP_RowUpdatedErrors);
}
internal static DataException RowUpdatingErrors()
{
return Data(SR.ADP_RowUpdatingErrors);
}
internal static InvalidOperationException ResultsNotAllowedDuringBatch()
{
return DataAdapter(SR.ADP_ResultsNotAllowedDuringBatch);
}
internal enum InternalErrorCode
{
UnpooledObjectHasOwner = 0,
UnpooledObjectHasWrongOwner = 1,
PushingObjectSecondTime = 2,
PooledObjectHasOwner = 3,
PooledObjectInPoolMoreThanOnce = 4,
CreateObjectReturnedNull = 5,
NewObjectCannotBePooled = 6,
NonPooledObjectUsedMoreThanOnce = 7,
AttemptingToPoolOnRestrictedToken = 8,
ConvertSidToStringSidWReturnedNull = 10,
AttemptingToConstructReferenceCollectionOnStaticObject = 12,
AttemptingToEnlistTwice = 13,
CreateReferenceCollectionReturnedNull = 14,
PooledObjectWithoutPool = 15,
UnexpectedWaitAnyResult = 16,
SynchronousConnectReturnedPending = 17,
CompletedConnectReturnedPending = 18,
NameValuePairNext = 20,
InvalidParserState1 = 21,
InvalidParserState2 = 22,
InvalidParserState3 = 23,
InvalidBuffer = 30,
UnimplementedSMIMethod = 40,
InvalidSmiCall = 41,
SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50,
SqlDependencyProcessDispatcherFailureCreateInstance = 51,
SqlDependencyProcessDispatcherFailureAppDomain = 52,
SqlDependencyCommandHashIsNotAssociatedWithNotification = 53,
UnknownTransactionFailure = 60,
}
internal static Exception InternalError(InternalErrorCode internalError)
{
return InvalidOperation(SR.Format(SR.ADP_InternalProviderError, (int)internalError));
}
//
// : DbDataReader
//
internal static Exception DataReaderClosed(string method)
{
return InvalidOperation(SR.Format(SR.ADP_DataReaderClosed, method));
}
internal static ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName)
{
return ArgumentOutOfRange(SR.Format(SR.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
}
internal static ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName)
{
return ArgumentOutOfRange(SR.Format(SR.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
}
internal static IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex)
{
return IndexOutOfRange(SR.Format(SR.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture)));
}
internal static Exception InvalidDataLength(long length)
{
return IndexOutOfRange(SR.Format(SR.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture)));
}
//
// : Stream
//
internal static Exception StreamClosed(string method)
{
return InvalidOperation(SR.Format(SR.ADP_StreamClosed, method));
}
//
// : DbDataAdapter
//
internal static InvalidOperationException DynamicSQLJoinUnsupported()
{
return InvalidOperation(SR.ADP_DynamicSQLJoinUnsupported);
}
internal static InvalidOperationException DynamicSQLNoTableInfo()
{
return InvalidOperation(SR.ADP_DynamicSQLNoTableInfo);
}
internal static InvalidOperationException DynamicSQLNoKeyInfoDelete()
{
return InvalidOperation(SR.ADP_DynamicSQLNoKeyInfoDelete);
}
internal static InvalidOperationException DynamicSQLNoKeyInfoUpdate()
{
return InvalidOperation(SR.ADP_DynamicSQLNoKeyInfoUpdate);
}
internal static InvalidOperationException DynamicSQLNoKeyInfoRowVersionDelete()
{
return InvalidOperation(SR.ADP_DynamicSQLNoKeyInfoRowVersionDelete);
}
internal static InvalidOperationException DynamicSQLNoKeyInfoRowVersionUpdate()
{
return InvalidOperation(SR.ADP_DynamicSQLNoKeyInfoRowVersionUpdate);
}
internal static InvalidOperationException DynamicSQLNestedQuote(string name, string quote)
{
return InvalidOperation(SR.Format(SR.ADP_DynamicSQLNestedQuote, name, quote));
}
internal static InvalidOperationException NoQuoteChange()
{
return InvalidOperation(SR.ADP_NoQuoteChange);
}
internal static InvalidOperationException MissingSourceCommand()
{
return InvalidOperation(SR.ADP_MissingSourceCommand);
}
internal static InvalidOperationException MissingSourceCommandConnection()
{
return InvalidOperation(SR.ADP_MissingSourceCommandConnection);
}
// global constant strings
internal const string ConnectionString = "ConnectionString";
internal const string DataSetColumn = "DataSetColumn";
internal const string DataSetTable = "DataSetTable";
internal const string Fill = "Fill";
internal const string FillSchema = "FillSchema";
internal const string SourceColumn = "SourceColumn";
internal const string SourceTable = "SourceTable";
internal const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout;
internal static bool CompareInsensitiveInvariant(string strvalue, string strconst) =>
0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase);
internal static string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString)
{
var resultString = new StringBuilder();
if (!string.IsNullOrEmpty(quotePrefix))
{
resultString.Append(quotePrefix);
}
// Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar".
if (!string.IsNullOrEmpty(quoteSuffix))
{
resultString.Append(unQuotedString.Replace(quoteSuffix, quoteSuffix + quoteSuffix));
resultString.Append(quoteSuffix);
}
else
{
resultString.Append(unQuotedString);
}
return resultString.ToString();
}
internal static DataRow[] SelectAdapterRows(DataTable dataTable, bool sorted)
{
const DataRowState rowStates = DataRowState.Added | DataRowState.Deleted | DataRowState.Modified;
// equivalent to but faster than 'return dataTable.Select("", "", rowStates);'
int countAdded = 0, countDeleted = 0, countModifed = 0;
DataRowCollection rowCollection = dataTable.Rows;
foreach (DataRow dataRow in rowCollection)
{
switch (dataRow.RowState)
{
case DataRowState.Added:
countAdded++;
break;
case DataRowState.Deleted:
countDeleted++;
break;
case DataRowState.Modified:
countModifed++;
break;
default:
Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
break;
}
}
var dataRows = new DataRow[countAdded + countDeleted + countModifed];
if (sorted)
{
countModifed = countAdded + countDeleted;
countDeleted = countAdded;
countAdded = 0;
foreach (DataRow dataRow in rowCollection)
{
switch (dataRow.RowState)
{
case DataRowState.Added:
dataRows[countAdded++] = dataRow;
break;
case DataRowState.Deleted:
dataRows[countDeleted++] = dataRow;
break;
case DataRowState.Modified:
dataRows[countModifed++] = dataRow;
break;
default:
Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
break;
}
}
}
else
{
int index = 0;
foreach (DataRow dataRow in rowCollection)
{
if (0 != (dataRow.RowState & rowStates))
{
dataRows[index++] = dataRow;
if (index == dataRows.Length)
{
break;
}
}
}
}
return dataRows;
}
// { "a", "a", "a" } -> { "a", "a1", "a2" }
// { "a", "a", "a1" } -> { "a", "a2", "a1" }
// { "a", "A", "a" } -> { "a", "A1", "a2" }
// { "a", "A", "a1" } -> { "a", "A2", "a1" }
internal static void BuildSchemaTableInfoTableNames(string[] columnNameArray)
{
Dictionary<string, int> hash = new Dictionary<string, int>(columnNameArray.Length);
int startIndex = columnNameArray.Length; // lowest non-unique index
for (int i = columnNameArray.Length - 1; 0 <= i; --i)
{
string columnName = columnNameArray[i];
if ((null != columnName) && (0 < columnName.Length))
{
columnName = columnName.ToLower(CultureInfo.InvariantCulture);
int index;
if (hash.TryGetValue(columnName, out index))
{
startIndex = Math.Min(startIndex, index);
}
hash[columnName] = i;
}
else
{
columnNameArray[i] = string.Empty;
startIndex = i;
}
}
int uniqueIndex = 1;
for (int i = startIndex; i < columnNameArray.Length; ++i)
{
string columnName = columnNameArray[i];
if (0 == columnName.Length)
{
// generate a unique name
columnNameArray[i] = "Column";
uniqueIndex = GenerateUniqueName(hash, ref columnNameArray[i], i, uniqueIndex);
}
else
{
columnName = columnName.ToLower(CultureInfo.InvariantCulture);
if (i != hash[columnName])
{
GenerateUniqueName(hash, ref columnNameArray[i], i, 1);
}
}
}
}
private static int GenerateUniqueName(Dictionary<string, int> hash, ref string columnName, int index, int uniqueIndex)
{
for (; ; ++uniqueIndex)
{
string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture);
string lowerName = uniqueName.ToLower(CultureInfo.InvariantCulture);
if (!hash.ContainsKey(lowerName))
{
columnName = uniqueName;
hash.Add(lowerName, index);
break;
}
}
return uniqueIndex;
}
internal static int SrcCompare(string strA, string strB) => strA == strB ? 0 : 1;
internal static int DstCompare(string strA, string strB) => CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.DefaultCompareOptions);
internal static bool IsEmptyArray(string[] array) => (null == array) || (0 == array.Length);
internal static bool IsNull(object value)
{
if ((null == value) || (DBNull.Value == value))
{
return true;
}
INullable nullable = (value as INullable);
return ((null != nullable) && nullable.IsNull);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web.Mvc;
using System.Web.Security;
using MvcMembership;
using MvcMembership.Settings;
using HydroData.admin.Areas.MvcMembership.Models.UserAdministration;
namespace HydroData.admin.Areas.MvcMembership.Controllers
{
[UrlLang]
[AuthorizeUnlessOnlyUser(Roles = "Administrator")] // allows access if you're the only user, only validates role if role provider is enabled
public class UserAdministrationController : Controller
{
private const int PageSize = 10;
private const string ResetPasswordBody = "Your new password is: ";
private const string ResetPasswordSubject = "Your New Password";
private readonly IRolesService _rolesService;
private readonly ISmtpClient _smtpClient;
private readonly IMembershipSettings _membershipSettings;
private readonly IUserService _userService;
private readonly IPasswordService _passwordService;
public UserAdministrationController()
: this(new AspNetMembershipProviderWrapper(), new AspNetRoleProviderWrapper(), new SmtpClientProxy())
{
}
public UserAdministrationController(AspNetMembershipProviderWrapper membership, IRolesService roles, ISmtpClient smtp)
: this(membership.Settings, membership, membership, roles, smtp)
{
}
public UserAdministrationController(
IMembershipSettings membershipSettings,
IUserService userService,
IPasswordService passwordService,
IRolesService rolesService,
ISmtpClient smtpClient)
{
_membershipSettings = membershipSettings;
_userService = userService;
_passwordService = passwordService;
_rolesService = rolesService;
_smtpClient = smtpClient;
}
public ActionResult Index(int? page, string search)
{
var users = string.IsNullOrWhiteSpace(search)
? _userService.FindAll(page ?? 1, PageSize)
: search.Contains("@")
? _userService.FindByEmail(search, page ?? 1, PageSize)
: _userService.FindByUserName(search, page ?? 1, PageSize);
if (!string.IsNullOrWhiteSpace(search) && users.Count == 1)
return RedirectToAction("Details", new { id = users[0].ProviderUserKey.ToString() });
return View(new IndexViewModel
{
Search = search,
Users = users,
Roles = _rolesService.Enabled
? _rolesService.FindAll()
: Enumerable.Empty<string>(),
IsRolesEnabled = _rolesService.Enabled
});
}
[AcceptVerbs(HttpVerbs.Post)]
public RedirectToRouteResult CreateRole(string id)
{
if (_rolesService.Enabled)
_rolesService.Create(id);
return RedirectToAction("Index");
}
[AcceptVerbs(HttpVerbs.Post)]
public RedirectToRouteResult DeleteRole(string id)
{
_rolesService.Delete(id);
return RedirectToAction("Index");
}
public ViewResult Role(string id)
{
return View(new RoleViewModel
{
Role = id,
Users = _rolesService.FindUserNamesByRole(id)
.ToDictionary(
k => k,
v => _userService.Get(v)
)
});
}
public ViewResult Details(Guid id)
{
var user = _userService.Get(id);
var userRoles = _rolesService.Enabled
? _rolesService.FindByUser(user)
: Enumerable.Empty<string>();
return View(new DetailsViewModel
{
CanResetPassword = _membershipSettings.Password.ResetOrRetrieval.CanReset,
RequirePasswordQuestionAnswerToResetPassword = _membershipSettings.Password.ResetOrRetrieval.RequiresQuestionAndAnswer,
DisplayName = user.UserName,
User = user,
Roles = _rolesService.Enabled
? _rolesService.FindAll().ToDictionary(role => role, role => userRoles.Contains(role))
: new Dictionary<string, bool>(0),
IsRolesEnabled = _rolesService.Enabled,
Status = user.IsOnline
? DetailsViewModel.StatusEnum.Online
: !user.IsApproved
? DetailsViewModel.StatusEnum.Unapproved
: user.IsLockedOut
? DetailsViewModel.StatusEnum.LockedOut
: DetailsViewModel.StatusEnum.Offline
});
}
public ViewResult Password(Guid id)
{
var user = _userService.Get(id);
var userRoles = _rolesService.Enabled
? _rolesService.FindByUser(user)
: Enumerable.Empty<string>();
return View(new DetailsViewModel
{
CanResetPassword = _membershipSettings.Password.ResetOrRetrieval.CanReset,
RequirePasswordQuestionAnswerToResetPassword = _membershipSettings.Password.ResetOrRetrieval.RequiresQuestionAndAnswer,
DisplayName = user.UserName,
User = user,
Roles = _rolesService.Enabled
? _rolesService.FindAll().ToDictionary(role => role, role => userRoles.Contains(role))
: new Dictionary<string, bool>(0),
IsRolesEnabled = _rolesService.Enabled,
Status = user.IsOnline
? DetailsViewModel.StatusEnum.Online
: !user.IsApproved
? DetailsViewModel.StatusEnum.Unapproved
: user.IsLockedOut
? DetailsViewModel.StatusEnum.LockedOut
: DetailsViewModel.StatusEnum.Offline
});
}
public ViewResult UsersRoles(Guid id)
{
var user = _userService.Get(id);
var userRoles = _rolesService.FindByUser(user);
return View(new DetailsViewModel
{
CanResetPassword = _membershipSettings.Password.ResetOrRetrieval.CanReset,
RequirePasswordQuestionAnswerToResetPassword = _membershipSettings.Password.ResetOrRetrieval.RequiresQuestionAndAnswer,
DisplayName = user.UserName,
User = user,
Roles = _rolesService.FindAll().ToDictionary(role => role, role => userRoles.Contains(role)),
IsRolesEnabled = true,
Status = user.IsOnline
? DetailsViewModel.StatusEnum.Online
: !user.IsApproved
? DetailsViewModel.StatusEnum.Unapproved
: user.IsLockedOut
? DetailsViewModel.StatusEnum.LockedOut
: DetailsViewModel.StatusEnum.Offline
});
}
public ViewResult CreateUser()
{
var model = new CreateUserViewModel
{
InitialRoles = _rolesService.FindAll().ToDictionary(k => k, v => false)
};
return View(model);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateUser(CreateUserViewModel createUserViewModel)
{
if (!ModelState.IsValid)
return View(createUserViewModel);
try
{
if (createUserViewModel.Password != createUserViewModel.ConfirmPassword)
throw new MembershipCreateUserException("Passwords do not match.");
var user = _userService.Create(
createUserViewModel.Username,
createUserViewModel.Password,
createUserViewModel.Email,
createUserViewModel.PasswordQuestion,
createUserViewModel.PasswordAnswer,
true);
if (createUserViewModel.InitialRoles != null)
{
var rolesToAddUserTo = createUserViewModel.InitialRoles.Where(x => x.Value).Select(x => x.Key);
foreach (var role in rolesToAddUserTo)
_rolesService.AddToRole(user, role);
}
return RedirectToAction("Details", new { id = user.ProviderUserKey });
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError(string.Empty, e.Message);
return View(createUserViewModel);
}
}
[AcceptVerbs(HttpVerbs.Post)]
public RedirectToRouteResult Details(Guid id, string email, string comments)
{
var user = _userService.Get(id);
user.Email = email;
user.Comment = comments;
_userService.Update(user);
return RedirectToAction("Details", new { id });
}
[AcceptVerbs(HttpVerbs.Post)]
public RedirectToRouteResult DeleteUser(Guid id)
{
var user = _userService.Get(id);
if (_rolesService.Enabled)
_rolesService.RemoveFromAllRoles(user);
_userService.Delete(user);
return RedirectToAction("Index");
}
[AcceptVerbs(HttpVerbs.Post)]
public RedirectToRouteResult ChangeApproval(Guid id, bool isApproved)
{
var user = _userService.Get(id);
user.IsApproved = isApproved;
_userService.Update(user);
return RedirectToAction("Details", new { id });
}
[AcceptVerbs(HttpVerbs.Post)]
public RedirectToRouteResult Unlock(Guid id)
{
_passwordService.Unlock(_userService.Get(id));
return RedirectToAction("Details", new { id });
}
[AcceptVerbs(HttpVerbs.Post)]
public RedirectToRouteResult ResetPassword(Guid id)
{
var user = _userService.Get(id);
var newPassword = _passwordService.ResetPassword(user);
var body = ResetPasswordBody + newPassword;
var msg = new MailMessage();
msg.To.Add(user.Email);
msg.Subject = ResetPasswordSubject;
msg.Body = body;
_smtpClient.Send(msg);
return RedirectToAction("Password", new { id });
}
[AcceptVerbs(HttpVerbs.Post)]
public RedirectToRouteResult ResetPasswordWithAnswer(Guid id, string answer)
{
var user = _userService.Get(id);
var newPassword = _passwordService.ResetPassword(user, answer);
var body = ResetPasswordBody + newPassword;
var msg = new MailMessage();
msg.To.Add(user.Email);
msg.Subject = ResetPasswordSubject;
msg.Body = body;
_smtpClient.Send(msg);
return RedirectToAction("Password", new { id });
}
[AcceptVerbs(HttpVerbs.Post)]
public RedirectToRouteResult SetPassword(Guid id, string password)
{
var user = _userService.Get(id);
_passwordService.ChangePassword(user, password);
var body = ResetPasswordBody + password;
var msg = new MailMessage();
msg.To.Add(user.Email);
msg.Subject = ResetPasswordSubject;
msg.Body = body;
_smtpClient.Send(msg);
return RedirectToAction("Password", new { id });
}
[AcceptVerbs(HttpVerbs.Post)]
public RedirectToRouteResult AddToRole(Guid id, string role)
{
_rolesService.AddToRole(_userService.Get(id), role);
return RedirectToAction("UsersRoles", new { id });
}
[AcceptVerbs(HttpVerbs.Post)]
public RedirectToRouteResult RemoveFromRole(Guid id, string role)
{
_rolesService.RemoveFromRole(_userService.Get(id), role);
return RedirectToAction("UsersRoles", new { id });
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Common
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
using Microsoft.Azure.Devices.Common.Interop;
using Microsoft.Azure.Devices.Common.Tracing;
class ExceptionTrace
{
const ushort FailFastEventLogCategory = 6;
readonly string eventSourceName;
public ExceptionTrace(string eventSourceName)
{
this.eventSourceName = eventSourceName;
}
public Exception AsError(Exception exception, EventTraceActivity activity = null)
{
return TraceException<Exception>(exception, TraceEventType.Error, activity);
}
public Exception AsInformation(Exception exception, EventTraceActivity activity = null)
{
return TraceException<Exception>(exception, TraceEventType.Information, activity);
}
public Exception AsWarning(Exception exception, EventTraceActivity activity = null)
{
return TraceException<Exception>(exception, TraceEventType.Warning, activity);
}
public Exception AsVerbose(Exception exception, EventTraceActivity activity = null)
{
return TraceException<Exception>(exception, TraceEventType.Verbose, activity);
}
public ArgumentException Argument(string paramName, string message)
{
return TraceException<ArgumentException>(new ArgumentException(message, paramName), TraceEventType.Error);
}
public ArgumentNullException ArgumentNull(string paramName)
{
return TraceException<ArgumentNullException>(new ArgumentNullException(paramName), TraceEventType.Error);
}
public ArgumentNullException ArgumentNull(string paramName, string message)
{
return TraceException<ArgumentNullException>(new ArgumentNullException(paramName, message), TraceEventType.Error);
}
public ArgumentException ArgumentNullOrEmpty(string paramName)
{
return this.Argument(paramName, CommonResources.GetString(CommonResources.ArgumentNullOrEmpty, paramName));
}
public ArgumentException ArgumentNullOrWhiteSpace(string paramName)
{
return this.Argument(paramName, CommonResources.GetString(CommonResources.ArgumentNullOrWhiteSpace, paramName));
}
public ArgumentOutOfRangeException ArgumentOutOfRange(string paramName, object actualValue, string message)
{
return TraceException<ArgumentOutOfRangeException>(new ArgumentOutOfRangeException(paramName, actualValue, message), TraceEventType.Error);
}
// When throwing ObjectDisposedException, it is highly recommended that you use this ctor
// [C#]
// public ObjectDisposedException(string objectName, string message);
// And provide null for objectName but meaningful and relevant message for message.
// It is recommended because end user really does not care or can do anything on the disposed object, commonly an internal or private object.
public ObjectDisposedException ObjectDisposed(string message)
{
// pass in null, not disposedObject.GetType().FullName as per the above guideline
return TraceException<ObjectDisposedException>(new ObjectDisposedException(null, message), TraceEventType.Error);
}
public void TraceHandled(Exception exception, string catchLocation, EventTraceActivity activity = null)
{
#if DEBUG
Trace.WriteLine(string.Format(
CultureInfo.InvariantCulture,
"IotHub/TraceHandled ThreadID=\"{0}\" catchLocation=\"{1}\" exceptionType=\"{2}\" exception=\"{3}\"",
Thread.CurrentThread.ManagedThreadId,
catchLocation,
exception.GetType(),
exception.ToStringSlim()));
#endif
////MessagingClientEtwProvider.Provider.HandledExceptionWithFunctionName(
//// activity, catchLocation, exception.ToStringSlim(), string.Empty);
this.BreakOnException(exception);
}
public void TraceUnhandled(Exception exception)
{
////MessagingClientEtwProvider.Provider.EventWriteUnhandledException(this.eventSourceName + ": " + exception.ToStringSlim());
}
[ResourceConsumption(ResourceScope.Process)]
[Fx.Tag.SecurityNote(Critical = "Calls 'System.Runtime.Interop.UnsafeNativeMethods.IsDebuggerPresent()' which is a P/Invoke method",
Safe = "Does not leak any resource, needed for debugging")]
public TException TraceException<TException>(TException exception, TraceEventType level, EventTraceActivity activity = null)
where TException : Exception
{
if (!exception.Data.Contains(this.eventSourceName))
{
// Only trace if this is the first time an exception is thrown by this ExceptionTrace/EventSource.
exception.Data[this.eventSourceName] = this.eventSourceName;
switch (level)
{
case TraceEventType.Critical:
case TraceEventType.Error:
Trace.TraceError("An Exception is being thrown: {0}", GetDetailsForThrownException(exception));
////if (MessagingClientEtwProvider.Provider.IsEnabled(
//// EventLevel.Error,
//// MessagingClientEventSource.Keywords.Client,
//// MessagingClientEventSource.Channels.DebugChannel))
////{
//// MessagingClientEtwProvider.Provider.ThrowingExceptionError(activity, GetDetailsForThrownException(exception));
////}
break;
case TraceEventType.Warning:
Trace.TraceWarning("An Exception is being thrown: {0}", GetDetailsForThrownException(exception));
////if (MessagingClientEtwProvider.Provider.IsEnabled(
//// EventLevel.Warning,
//// MessagingClientEventSource.Keywords.Client,
//// MessagingClientEventSource.Channels.DebugChannel))
////{
//// MessagingClientEtwProvider.Provider.ThrowingExceptionWarning(activity, GetDetailsForThrownException(exception));
////}
break;
default:
#if DEBUG
////if (MessagingClientEtwProvider.Provider.IsEnabled(
//// EventLevel.Verbose,
//// MessagingClientEventSource.Keywords.Client,
//// MessagingClientEventSource.Channels.DebugChannel))
////{
//// MessagingClientEtwProvider.Provider.ThrowingExceptionVerbose(activity, GetDetailsForThrownException(exception));
////}
#endif
break;
}
}
BreakOnException(exception);
return exception;
}
public static string GetDetailsForThrownException(Exception e)
{
const int MaxStackFrames = 10;
string details = e.GetType().ToString();
// Include the current callstack (this ensures we see the Stack in case exception is not output when caught)
var stackTrace = new StackTrace();
string stackTraceString = stackTrace.ToString();
if (stackTrace.FrameCount > MaxStackFrames)
{
string[] frames = stackTraceString.Split(new[] { Environment.NewLine }, MaxStackFrames + 1, StringSplitOptions.RemoveEmptyEntries);
stackTraceString = string.Join(Environment.NewLine, frames, 0, MaxStackFrames) + "...";
}
details += Environment.NewLine + stackTraceString;
details += Environment.NewLine + "Exception ToString:" + Environment.NewLine;
details += e.ToStringSlim();
return details;
}
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.MarkMembersAsStatic, Justification = "CSDMain #183668")]
[Fx.Tag.SecurityNote(Critical = "Calls into critical method UnsafeNativeMethods.IsDebuggerPresent and UnsafeNativeMethods.DebugBreak",
Safe = "Safe because it's a no-op in retail builds.")]
internal void BreakOnException(Exception exception)
{
#if DEBUG
if (Fx.BreakOnExceptionTypes != null)
{
foreach (Type breakType in Fx.BreakOnExceptionTypes)
{
if (breakType.IsAssignableFrom(exception.GetType()))
{
// This is intended to "crash" the process so that a debugger can be attached. If a managed
// debugger is already attached, it will already be able to hook these exceptions. We don't
// want to simulate an unmanaged crash (DebugBreak) in that case.
if (!Debugger.IsAttached && !UnsafeNativeMethods.IsDebuggerPresent())
{
Debugger.Launch();
}
}
}
}
#endif
}
[MethodImpl(MethodImplOptions.NoInlining)]
public void TraceFailFast(string message)
{
//// EventLogger logger = null;
////#pragma warning disable 618
//// logger = new EventLogger(this.eventSourceName, Fx.Trace);
////#pragma warning restore 618
//// TraceFailFast(message, logger);
}
// Generate an event Log entry for failfast purposes
// To force a Watson on a dev machine, do the following:
// 1. Set \HKLM\SOFTWARE\Microsoft\PCHealth\ErrorReporting ForceQueueMode = 0
// 2. In the command environment, set COMPLUS_DbgJitDebugLaunchSetting=0
////[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.MarkMembersAsStatic, Justification = "CSDMain #183668")]
////[MethodImpl(MethodImplOptions.NoInlining)]
////internal void TraceFailFast(string message, EventLogger logger)
////{
//// if (logger != null)
//// {
//// try
//// {
//// string stackTrace = null;
//// try
//// {
//// stackTrace = new StackTrace().ToString();
//// }
//// catch (Exception exception)
//// {
//// stackTrace = exception.Message;
//// if (Fx.IsFatal(exception))
//// {
//// throw;
//// }
//// }
//// finally
//// {
//// logger.LogEvent(TraceEventType.Critical,
//// FailFastEventLogCategory,
//// (uint)EventLogEventId.FailFast,
//// message,
//// stackTrace);
//// }
//// }
//// catch (Exception ex)
//// {
//// logger.LogEvent(TraceEventType.Critical,
//// FailFastEventLogCategory,
//// (uint)EventLogEventId.FailFastException,
//// ex.ToString());
//// if (Fx.IsFatal(ex))
//// {
//// throw;
//// }
//// }
//// }
////}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsPaging
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for PagingOperations.
/// </summary>
public static partial class PagingOperationsExtensions
{
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetSinglePages(this IPagingOperations operations)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetSinglePagesAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSinglePagesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetMultiplePages(this IPagingOperations operations, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions))
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesAsync(clientRequestId, pagingGetMultiplePagesOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesAsync(this IPagingOperations operations, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithHttpMessagesAsync(clientRequestId, pagingGetMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetOdataMultiplePages(this IPagingOperations operations, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions))
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetOdataMultiplePagesAsync(clientRequestId, pagingGetOdataMultiplePagesOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetOdataMultiplePagesAsync(this IPagingOperations operations, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOdataMultiplePagesWithHttpMessagesAsync(clientRequestId, pagingGetOdataMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='clientRequestId'>
/// </param>
public static IPage<Product> GetMultiplePagesWithOffset(this IPagingOperations operations, PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string))
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesWithOffsetAsync(pagingGetMultiplePagesWithOffsetOptions, clientRequestId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesWithOffsetAsync(this IPagingOperations operations, PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithOffsetWithHttpMessagesAsync(pagingGetMultiplePagesWithOffsetOptions, clientRequestId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetMultiplePagesRetryFirst(this IPagingOperations operations)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesRetryFirstAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetryFirstWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetMultiplePagesRetrySecond(this IPagingOperations operations)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesRetrySecondAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetrySecondWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetSinglePagesFailure(this IPagingOperations operations)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetSinglePagesFailureAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSinglePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetMultiplePagesFailure(this IPagingOperations operations)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFailureAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetMultiplePagesFailureUri(this IPagingOperations operations)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFailureUriAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureUriWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetSinglePagesNext(this IPagingOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetSinglePagesNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSinglePagesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetMultiplePagesNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions))
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesNextAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetOdataMultiplePagesNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions))
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetOdataMultiplePagesNextAsync(nextPageLink, clientRequestId, pagingGetOdataMultiplePagesOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetOdataMultiplePagesNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOdataMultiplePagesNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetOdataMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetNextOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetMultiplePagesWithOffsetNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions))
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesWithOffsetNextAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesWithOffsetNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithOffsetNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetMultiplePagesRetryFirstNext(this IPagingOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesRetryFirstNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetMultiplePagesRetrySecondNext(this IPagingOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which
/// the 2nd call fails first with 500. The client should retry and finish all
/// 10 pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesRetrySecondNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetSinglePagesFailureNext(this IPagingOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetSinglePagesFailureNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSinglePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetMultiplePagesFailureNext(this IPagingOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFailureNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetMultiplePagesFailureUriNext(this IPagingOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFailureUriNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureUriNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using Baseline;
using LamarCodeGeneration;
using LamarCodeGeneration.Frames;
using LamarCodeGeneration.Model;
using Marten.Internal.CodeGeneration;
using Marten.Services;
using Marten.Util;
using Npgsql;
using NpgsqlTypes;
using Weasel.Core;
using Weasel.Postgresql;
namespace Marten.Schema.Arguments
{
// Public for code generation, just let it go.
public class UpsertArgument
{
protected static readonly MethodInfo writeMethod =
typeof(NpgsqlBinaryImporter).GetMethods().FirstOrDefault(x => x.Name == "Write" && x.GetParameters().Length == 2 && x.GetParameters()[0].ParameterType.IsGenericParameter && x.GetParameters()[1].ParameterType == typeof(NpgsqlTypes.NpgsqlDbType));
private MemberInfo[] _members;
private string _postgresType;
public string Arg { get; set; }
public string PostgresType
{
get => _postgresType;
set
{
if (value == null)
{
throw new ArgumentNullException();
}
_postgresType = value.Contains("(")
? value.Split('(')[0].Trim()
: value;
}
}
public string Column { get; set; }
public MemberInfo[] Members
{
get => _members;
set
{
_members = value;
if (value != null)
{
DbType = PostgresqlProvider.Instance.ToParameterType(value.Last().GetMemberType());
if (_members.Length == 1)
{
DotNetType = _members.Last().GetRawMemberType();
}
else
{
var rawType = _members.LastOrDefault().GetRawMemberType();
if (!rawType.IsClass && !rawType.IsNullable())
{
DotNetType = typeof(Nullable<>).MakeGenericType(rawType);
}
else
{
DotNetType = rawType;
}
}
}
}
}
public Type DotNetType { get; private set; }
public NpgsqlDbType DbType { get; set; }
public string ArgumentDeclaration()
{
return $"{Arg} {PostgresType}";
}
public virtual void GenerateCodeToModifyDocument(GeneratedMethod method, GeneratedType type, int i,
Argument parameters,
DocumentMapping mapping, StoreOptions options)
{
// Nothing
}
public virtual void GenerateCodeToSetDbParameterValue(GeneratedMethod method, GeneratedType type, int i, Argument parameters,
DocumentMapping mapping, StoreOptions options)
{
var memberPath = _members.Select(x => x.Name).Join("?.");
if (DotNetType.IsEnum || (DotNetType.IsNullable() && DotNetType.GetGenericArguments()[0].IsEnum))
{
writeEnumerationValues(method, i, parameters, options, memberPath);
}
else
{
var rawMemberType = _members.Last().GetRawMemberType();
var dbTypeString = rawMemberType.IsArray
? $"{Constant.ForEnum(NpgsqlDbType.Array).Usage} | {Constant.ForEnum(PostgresqlProvider.Instance.ToParameterType(rawMemberType.GetElementType())).Usage}"
: Constant.ForEnum(DbType).Usage;
method.Frames.Code($"{parameters.Usage}[{i}].{nameof(NpgsqlParameter.NpgsqlDbType)} = {dbTypeString};");
if (rawMemberType.IsClass || rawMemberType.IsNullable() || _members.Length > 1)
{
method.Frames.Code($@"
BLOCK:if (document.{memberPath} != null)
{parameters.Usage}[{i}].{nameof(NpgsqlParameter.Value)} = document.{memberPath};
END
BLOCK:else
{parameters.Usage}[{i}].{nameof(NpgsqlParameter.Value)} = {typeof(DBNull).FullNameInCode()}.{nameof(DBNull.Value)};
END
");
}
else
{
method.Frames.Code($"{parameters.Usage}[{i}].{nameof(NpgsqlParameter.Value)} = document.{memberPath};");
}
}
}
private void writeEnumerationValues(GeneratedMethod method, int i, Argument parameters, StoreOptions options,
string memberPath)
{
if (options.Advanced.DuplicatedFieldEnumStorage == EnumStorage.AsInteger)
{
if (DotNetType.IsNullable())
{
method.Frames.Code($"{parameters.Usage}[{i}].{nameof(NpgsqlParameter.NpgsqlDbType)} = {{0}};",
NpgsqlDbType.Integer);
method.Frames.Code(
$"{parameters.Usage}[{i}].{nameof(NpgsqlParameter.Value)} = document.{memberPath} == null ? (object){typeof(DBNull).FullNameInCode()}.Value : (object)((int)document.{memberPath});");
}
else
{
method.Frames.Code($"{parameters.Usage}[{i}].{nameof(NpgsqlParameter.NpgsqlDbType)} = {{0}};",
NpgsqlDbType.Integer);
method.Frames.Code(
$"{parameters.Usage}[{i}].{nameof(NpgsqlParameter.Value)} = (int)document.{memberPath};");
}
}
else if (DotNetType.IsNullable())
{
method.Frames.Code($"{parameters.Usage}[{i}].{nameof(NpgsqlParameter.NpgsqlDbType)} = {{0}};",
NpgsqlDbType.Varchar);
method.Frames.Code(
$"{parameters.Usage}[{i}].{nameof(NpgsqlParameter.Value)} = (document.{memberPath} ).ToString();");
}
else
{
method.Frames.Code($"{parameters.Usage}[{i}].{nameof(NpgsqlParameter.NpgsqlDbType)} = {{0}};",
NpgsqlDbType.Varchar);
method.Frames.Code(
$"{parameters.Usage}[{i}].{nameof(NpgsqlParameter.Value)} = document.{memberPath}.ToString();");
}
}
public virtual void GenerateBulkWriterCode(GeneratedType type, GeneratedMethod load, DocumentMapping mapping)
{
var rawMemberType = _members.Last().GetRawMemberType();
var dbTypeString = rawMemberType.IsArray
? $"{Constant.ForEnum(NpgsqlDbType.Array).Usage} | {Constant.ForEnum(PostgresqlProvider.Instance.ToParameterType(rawMemberType.GetElementType())).Usage}"
: Constant.ForEnum(DbType).Usage;
var memberPath = _members.Select(x => x.Name).Join("?.");
if (DotNetType.IsNullable() && DotNetType.GetGenericArguments()[0] == typeof(Guid))
{
var accessor = $"GetNullableGuid(document.{memberPath})";
load.Frames.Code($"writer.Write({accessor}, {{0}});", NpgsqlDbType.Uuid);
}
else if (DotNetType.IsEnum || (DotNetType.IsNullable() && DotNetType.GetGenericArguments()[0].IsEnum))
{
var isDeep = _members.Length > 0;
var memberType = _members.Last().GetMemberType();
var isNullable = memberType.IsNullable();
var enumType = isNullable ? memberType.GetGenericArguments()[0] : memberType;
var accessor = memberPath;
if (DbType == NpgsqlDbType.Integer)
{
if (isNullable || isDeep)
{
accessor =
$"{nameof(BulkLoader<string, int>.GetEnumIntValue)}<{enumType.FullNameInCode()}>(document.{memberPath})";
}
load.Frames.Code($"writer.Write({accessor}, {{0}});", NpgsqlDbType.Integer);
}
else
{
if (isNullable || isDeep)
{
accessor =
$"GetEnumStringValue<{enumType.FullNameInCode()}>(document.{memberPath})";
}
load.Frames.Code($"writer.Write({accessor}, {{0}});", NpgsqlDbType.Varchar);
}
}
else
{
load.Frames.Code($"writer.Write(document.{memberPath}, {dbTypeString});");
}
}
public virtual void GenerateBulkWriterCodeAsync(GeneratedType type, GeneratedMethod load, DocumentMapping mapping)
{
var rawMemberType = _members.Last().GetRawMemberType();
var dbTypeString = rawMemberType.IsArray
? $"{Constant.ForEnum(NpgsqlDbType.Array).Usage} | {Constant.ForEnum(PostgresqlProvider.Instance.ToParameterType(rawMemberType.GetElementType())).Usage}"
: Constant.ForEnum(DbType).Usage;
var memberPath = _members.Select(x => x.Name).Join("?.");
if (DotNetType.IsNullable() && DotNetType.GetGenericArguments()[0] == typeof(Guid))
{
var accessor = $"GetNullableGuid(document.{memberPath})";
load.Frames.CodeAsync($"await writer.WriteAsync({accessor}, {{0}}, {{1}});", NpgsqlDbType.Uuid, Use.Type<CancellationToken>());
}
else if (DotNetType.IsEnum || (DotNetType.IsNullable() && DotNetType.GetGenericArguments()[0].IsEnum))
{
var isDeep = _members.Length > 0;
var memberType = _members.Last().GetMemberType();
var isNullable = memberType.IsNullable();
var enumType = isNullable ? memberType.GetGenericArguments()[0] : memberType;
var accessor = memberPath;
if (DbType == NpgsqlDbType.Integer)
{
if (isNullable || isDeep)
{
accessor =
$"{nameof(BulkLoader<string, int>.GetEnumIntValue)}<{enumType.FullNameInCode()}>(document.{memberPath})";
}
load.Frames.CodeAsync($"await writer.WriteAsync({accessor}, {{0}}, {{1}});", NpgsqlDbType.Integer, Use.Type<CancellationToken>());
}
else
{
if (isNullable || isDeep)
{
accessor =
$"GetEnumStringValue<{enumType.FullNameInCode()}>(document.{memberPath})";
}
else
{
accessor = $"document.{memberPath}.ToString()";
}
load.Frames.CodeAsync($"await writer.WriteAsync({accessor}, {{0}}, {{1}});", NpgsqlDbType.Varchar, Use.Type<CancellationToken>());
}
}
else
{
load.Frames.CodeAsync($"await writer.WriteAsync(document.{memberPath}, {dbTypeString}, {{0}});", Use.Type<CancellationToken>());
}
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// 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.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.9. Common superclass for EntityManagment PDUs, including aggregate state, isGroupOf, TransferControLRequest, and isPartOf
/// </summary>
[Serializable]
[XmlRoot]
public partial class EntityManagementFamilyPdu : Pdu, IEquatable<EntityManagementFamilyPdu>
{
/// <summary>
/// Initializes a new instance of the <see cref="EntityManagementFamilyPdu"/> class.
/// </summary>
public EntityManagementFamilyPdu()
{
ProtocolFamily = (byte)7;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(EntityManagementFamilyPdu left, EntityManagementFamilyPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(EntityManagementFamilyPdu left, EntityManagementFamilyPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
return marshalSize;
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public virtual void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<EntityManagementFamilyPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("</EntityManagementFamilyPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as EntityManagementFamilyPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(EntityManagementFamilyPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
return result;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SAEON.Observations.Data
{
/// <summary>
/// Strongly-typed collection for the SchemaColumnType class.
/// </summary>
[Serializable]
public partial class SchemaColumnTypeCollection : ActiveList<SchemaColumnType, SchemaColumnTypeCollection>
{
public SchemaColumnTypeCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SchemaColumnTypeCollection</returns>
public SchemaColumnTypeCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
SchemaColumnType o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the SchemaColumnType table.
/// </summary>
[Serializable]
public partial class SchemaColumnType : ActiveRecord<SchemaColumnType>, IActiveRecord
{
#region .ctors and Default Settings
public SchemaColumnType()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public SchemaColumnType(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public SchemaColumnType(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public SchemaColumnType(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("SchemaColumnType", TableType.Table, DataService.GetInstance("ObservationsDB"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "ID";
colvarId.DataType = DbType.Guid;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = false;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = true;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
colvarId.DefaultSetting = @"(newid())";
colvarId.ForeignKeyTableName = "";
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarName = new TableSchema.TableColumn(schema);
colvarName.ColumnName = "Name";
colvarName.DataType = DbType.AnsiString;
colvarName.MaxLength = 50;
colvarName.AutoIncrement = false;
colvarName.IsNullable = false;
colvarName.IsPrimaryKey = false;
colvarName.IsForeignKey = false;
colvarName.IsReadOnly = false;
colvarName.DefaultSetting = @"";
colvarName.ForeignKeyTableName = "";
schema.Columns.Add(colvarName);
TableSchema.TableColumn colvarDescription = new TableSchema.TableColumn(schema);
colvarDescription.ColumnName = "Description";
colvarDescription.DataType = DbType.AnsiString;
colvarDescription.MaxLength = 250;
colvarDescription.AutoIncrement = false;
colvarDescription.IsNullable = false;
colvarDescription.IsPrimaryKey = false;
colvarDescription.IsForeignKey = false;
colvarDescription.IsReadOnly = false;
colvarDescription.DefaultSetting = @"";
colvarDescription.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescription);
TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema);
colvarUserId.ColumnName = "UserId";
colvarUserId.DataType = DbType.Guid;
colvarUserId.MaxLength = 0;
colvarUserId.AutoIncrement = false;
colvarUserId.IsNullable = false;
colvarUserId.IsPrimaryKey = false;
colvarUserId.IsForeignKey = true;
colvarUserId.IsReadOnly = false;
colvarUserId.DefaultSetting = @"";
colvarUserId.ForeignKeyTableName = "aspnet_Users";
schema.Columns.Add(colvarUserId);
TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema);
colvarAddedAt.ColumnName = "AddedAt";
colvarAddedAt.DataType = DbType.DateTime;
colvarAddedAt.MaxLength = 0;
colvarAddedAt.AutoIncrement = false;
colvarAddedAt.IsNullable = true;
colvarAddedAt.IsPrimaryKey = false;
colvarAddedAt.IsForeignKey = false;
colvarAddedAt.IsReadOnly = false;
colvarAddedAt.DefaultSetting = @"(getdate())";
colvarAddedAt.ForeignKeyTableName = "";
schema.Columns.Add(colvarAddedAt);
TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema);
colvarUpdatedAt.ColumnName = "UpdatedAt";
colvarUpdatedAt.DataType = DbType.DateTime;
colvarUpdatedAt.MaxLength = 0;
colvarUpdatedAt.AutoIncrement = false;
colvarUpdatedAt.IsNullable = true;
colvarUpdatedAt.IsPrimaryKey = false;
colvarUpdatedAt.IsForeignKey = false;
colvarUpdatedAt.IsReadOnly = false;
colvarUpdatedAt.DefaultSetting = @"(getdate())";
colvarUpdatedAt.ForeignKeyTableName = "";
schema.Columns.Add(colvarUpdatedAt);
TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema);
colvarRowVersion.ColumnName = "RowVersion";
colvarRowVersion.DataType = DbType.Binary;
colvarRowVersion.MaxLength = 0;
colvarRowVersion.AutoIncrement = false;
colvarRowVersion.IsNullable = false;
colvarRowVersion.IsPrimaryKey = false;
colvarRowVersion.IsForeignKey = false;
colvarRowVersion.IsReadOnly = true;
colvarRowVersion.DefaultSetting = @"";
colvarRowVersion.ForeignKeyTableName = "";
schema.Columns.Add(colvarRowVersion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["ObservationsDB"].AddSchema("SchemaColumnType",schema);
}
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public Guid Id
{
get { return GetColumnValue<Guid>(Columns.Id); }
set { SetColumnValue(Columns.Id, value); }
}
[XmlAttribute("Name")]
[Bindable(true)]
public string Name
{
get { return GetColumnValue<string>(Columns.Name); }
set { SetColumnValue(Columns.Name, value); }
}
[XmlAttribute("Description")]
[Bindable(true)]
public string Description
{
get { return GetColumnValue<string>(Columns.Description); }
set { SetColumnValue(Columns.Description, value); }
}
[XmlAttribute("UserId")]
[Bindable(true)]
public Guid UserId
{
get { return GetColumnValue<Guid>(Columns.UserId); }
set { SetColumnValue(Columns.UserId, value); }
}
[XmlAttribute("AddedAt")]
[Bindable(true)]
public DateTime? AddedAt
{
get { return GetColumnValue<DateTime?>(Columns.AddedAt); }
set { SetColumnValue(Columns.AddedAt, value); }
}
[XmlAttribute("UpdatedAt")]
[Bindable(true)]
public DateTime? UpdatedAt
{
get { return GetColumnValue<DateTime?>(Columns.UpdatedAt); }
set { SetColumnValue(Columns.UpdatedAt, value); }
}
[XmlAttribute("RowVersion")]
[Bindable(true)]
public byte[] RowVersion
{
get { return GetColumnValue<byte[]>(Columns.RowVersion); }
set { SetColumnValue(Columns.RowVersion, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
public SAEON.Observations.Data.SchemaColumnCollection SchemaColumnRecords()
{
return new SAEON.Observations.Data.SchemaColumnCollection().Where(SchemaColumn.Columns.SchemaColumnTypeID, Id).Load();
}
#endregion
#region ForeignKey Properties
private SAEON.Observations.Data.AspnetUser _AspnetUser = null;
/// <summary>
/// Returns a AspnetUser ActiveRecord object related to this SchemaColumnType
///
/// </summary>
public SAEON.Observations.Data.AspnetUser AspnetUser
{
// get { return SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId); }
get { return _AspnetUser ?? (_AspnetUser = SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId)); }
set { SetColumnValue("UserId", value.UserId); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(Guid varId,string varName,string varDescription,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion)
{
SchemaColumnType item = new SchemaColumnType();
item.Id = varId;
item.Name = varName;
item.Description = varDescription;
item.UserId = varUserId;
item.AddedAt = varAddedAt;
item.UpdatedAt = varUpdatedAt;
item.RowVersion = varRowVersion;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(Guid varId,string varName,string varDescription,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion)
{
SchemaColumnType item = new SchemaColumnType();
item.Id = varId;
item.Name = varName;
item.Description = varDescription;
item.UserId = varUserId;
item.AddedAt = varAddedAt;
item.UpdatedAt = varUpdatedAt;
item.RowVersion = varRowVersion;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NameColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn DescriptionColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn UserIdColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn AddedAtColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn UpdatedAtColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn RowVersionColumn
{
get { return Schema.Columns[6]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"ID";
public static string Name = @"Name";
public static string Description = @"Description";
public static string UserId = @"UserId";
public static string AddedAt = @"AddedAt";
public static string UpdatedAt = @"UpdatedAt";
public static string RowVersion = @"RowVersion";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
// Struct sizes needed for some custom marshaling.
internal static readonly int s_controlDataSize = Marshal.SizeOf<Interop.Winsock.ControlData>();
internal static readonly int s_controlDataIPv6Size = Marshal.SizeOf<Interop.Winsock.ControlDataIPv6>();
internal static readonly int s_wsaMsgSize = Marshal.SizeOf<Interop.Winsock.WSAMsg>();
// Buffer,Offset,Count property variables.
private WSABuffer _wsaBuffer;
private IntPtr _ptrSingleBuffer;
// BufferList property variables.
private WSABuffer[] _wsaBufferArray;
private bool _bufferListChanged;
// Internal buffers for WSARecvMsg
private byte[] _wsaMessageBuffer;
private GCHandle _wsaMessageBufferGCHandle;
private IntPtr _ptrWSAMessageBuffer;
private byte[] _controlBuffer;
private GCHandle _controlBufferGCHandle;
private IntPtr _ptrControlBuffer;
private WSABuffer[] _wsaRecvMsgWSABufferArray;
private GCHandle _wsaRecvMsgWSABufferArrayGCHandle;
private IntPtr _ptrWSARecvMsgWSABufferArray;
// Internal buffer for AcceptEx when Buffer not supplied.
private IntPtr _ptrAcceptBuffer;
// Internal SocketAddress buffer
private GCHandle _socketAddressGCHandle;
private Internals.SocketAddress _pinnedSocketAddress;
private IntPtr _ptrSocketAddressBuffer;
private IntPtr _ptrSocketAddressBufferSize;
// SendPacketsElements property variables.
private SendPacketsElement[] _sendPacketsElementsInternal;
private Interop.Winsock.TransmitPacketsElement[] _sendPacketsDescriptor;
private int _sendPacketsElementsFileCount;
private int _sendPacketsElementsBufferCount;
// Internal variables for SendPackets
private FileStream[] _sendPacketsFileStreams;
private SafeHandle[] _sendPacketsFileHandles;
private IntPtr _ptrSendPacketsDescriptor;
// Overlapped object related variables.
private SafeNativeOverlapped _ptrNativeOverlapped;
private PreAllocatedOverlapped _preAllocatedOverlapped;
private object[] _objectsToPin;
private enum PinState
{
None = 0,
NoBuffer,
SingleAcceptBuffer,
SingleBuffer,
MultipleBuffer,
SendPackets
}
private PinState _pinState;
private byte[] _pinnedAcceptBuffer;
private byte[] _pinnedSingleBuffer;
private int _pinnedSingleBufferOffset;
private int _pinnedSingleBufferCount;
internal int? SendPacketsDescriptorCount
{
get
{
return _sendPacketsDescriptor == null ? null : (int?)_sendPacketsDescriptor.Length;
}
}
private void InitializeInternals()
{
// Zero tells TransmitPackets to select a default send size.
_sendPacketsSendSize = 0;
}
private void FreeInternals(bool calledFromFinalizer)
{
// Free native overlapped data.
FreeOverlapped(calledFromFinalizer);
}
private void SetupSingleBuffer()
{
CheckPinSingleBuffer(true);
}
private void SetupMultipleBuffers()
{
_bufferListChanged = true;
CheckPinMultipleBuffers();
}
private void SetupSendPacketsElements()
{
_sendPacketsElementsInternal = null;
}
private void InnerComplete()
{
CompleteIOCPOperation();
}
private unsafe void PrepareIOCPOperation()
{
Debug.Assert(_currentSocket != null, "_currentSocket is null");
Debug.Assert(_currentSocket.SafeHandle != null, "_currentSocket.SafeHandle is null");
Debug.Assert(!_currentSocket.SafeHandle.IsInvalid, "_currentSocket.SafeHandle is invalid");
ThreadPoolBoundHandle boundHandle = _currentSocket.SafeHandle.GetOrAllocateThreadPoolBoundHandle();
NativeOverlapped* overlapped = null;
if (_preAllocatedOverlapped != null)
{
overlapped = boundHandle.AllocateNativeOverlapped(_preAllocatedOverlapped);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
"::boundHandle#" + LoggingHash.HashString(boundHandle) +
"::AllocateNativeOverlapped(m_PreAllocatedOverlapped=" +
LoggingHash.HashString(_preAllocatedOverlapped) +
"). Returned = " + ((IntPtr)overlapped).ToString("x"));
}
}
else
{
overlapped = boundHandle.AllocateNativeOverlapped(CompletionPortCallback, this, null);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
"::boundHandle#" + LoggingHash.HashString(boundHandle) +
"::AllocateNativeOverlapped(pinData=null)" +
"). Returned = " + ((IntPtr)overlapped).ToString("x"));
}
}
Debug.Assert(overlapped != null, "NativeOverlapped is null.");
_ptrNativeOverlapped = new SafeNativeOverlapped(_currentSocket.SafeHandle, overlapped);
}
private void CompleteIOCPOperation()
{
// TODO #4900: Optimization to remove callbacks if the operations are completed synchronously:
// Use SetFileCompletionNotificationModes(FILE_SKIP_COMPLETION_PORT_ON_SUCCESS).
// If SetFileCompletionNotificationModes(FILE_SKIP_COMPLETION_PORT_ON_SUCCESS) is not set on this handle
// it is guaranteed that the IOCP operation will be completed in the callback even if Socket.Success was
// returned by the Win32 API.
// Required to allow another IOCP operation for the same handle.
if (_ptrNativeOverlapped != null)
{
_ptrNativeOverlapped.Dispose();
_ptrNativeOverlapped = null;
}
}
private void InnerStartOperationAccept(bool userSuppliedBuffer)
{
if (!userSuppliedBuffer)
{
CheckPinSingleBuffer(false);
}
}
internal unsafe SocketError DoOperationAccept(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, out int bytesTransferred)
{
PrepareIOCPOperation();
SocketError socketError = SocketError.Success;
if (!socket.AcceptEx(
handle,
acceptHandle,
(_ptrSingleBuffer != IntPtr.Zero) ? _ptrSingleBuffer : _ptrAcceptBuffer,
(_ptrSingleBuffer != IntPtr.Zero) ? Count - _acceptAddressBufferCount : 0,
_acceptAddressBufferCount / 2,
_acceptAddressBufferCount / 2,
out bytesTransferred,
_ptrNativeOverlapped))
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
private void InnerStartOperationConnect()
{
// ConnectEx uses a sockaddr buffer containing he remote address to which to connect.
// It can also optionally take a single buffer of data to send after the connection is complete.
//
// The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack.
// The optional buffer is pinned using the Overlapped.UnsafePack method that takes a single object to pin.
PinSocketAddressBuffer();
CheckPinNoBuffer();
}
internal unsafe SocketError DoOperationConnect(Socket socket, SafeCloseSocket handle, out int bytesTransferred)
{
PrepareIOCPOperation();
SocketError socketError = SocketError.Success;
if (!socket.ConnectEx(
handle,
_ptrSocketAddressBuffer,
_socketAddress.Size,
_ptrSingleBuffer,
Count,
out bytesTransferred,
_ptrNativeOverlapped))
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
private void InnerStartOperationDisconnect()
{
CheckPinNoBuffer();
}
internal SocketError DoOperationDisconnect(Socket socket, SafeCloseSocket handle)
{
PrepareIOCPOperation();
SocketError socketError = SocketError.Success;
if (!socket.DisconnectEx(
handle,
_ptrNativeOverlapped,
(int)(DisconnectReuseSocket ? TransmitFileOptions.ReuseSocket : 0),
0))
{
socketError = (SocketError)Marshal.GetLastWin32Error();
}
return socketError;
}
private void InnerStartOperationReceive()
{
// WWSARecv uses a WSABuffer array describing buffers of data to send.
//
// Single and multiple buffers are handled differently so as to optimize
// performance for the more common single buffer case.
//
// For a single buffer:
// The Overlapped.UnsafePack method is used that takes a single object to pin.
// A single WSABuffer that pre-exists in SocketAsyncEventArgs is used.
//
// For multiple buffers:
// The Overlapped.UnsafePack method is used that takes an array of objects to pin.
// An array to reference the multiple buffer is allocated.
// An array of WSABuffer descriptors is allocated.
}
internal unsafe SocketError DoOperationReceive(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred)
{
PrepareIOCPOperation();
flags = _socketFlags;
SocketError socketError;
if (_buffer != null)
{
// Single buffer case.
socketError = Interop.Winsock.WSARecv(
handle,
ref _wsaBuffer,
1,
out bytesTransferred,
ref flags,
_ptrNativeOverlapped,
IntPtr.Zero);
}
else
{
// Multi buffer case.
socketError = Interop.Winsock.WSARecv(
handle,
_wsaBufferArray,
_wsaBufferArray.Length,
out bytesTransferred,
ref flags,
_ptrNativeOverlapped,
IntPtr.Zero);
}
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
private void InnerStartOperationReceiveFrom()
{
// WSARecvFrom uses e a WSABuffer array describing buffers in which to
// receive data and from which to send data respectively. Single and multiple buffers
// are handled differently so as to optimize performance for the more common single buffer case.
//
// For a single buffer:
// The Overlapped.UnsafePack method is used that takes a single object to pin.
// A single WSABuffer that pre-exists in SocketAsyncEventArgs is used.
//
// For multiple buffers:
// The Overlapped.UnsafePack method is used that takes an array of objects to pin.
// An array to reference the multiple buffer is allocated.
// An array of WSABuffer descriptors is allocated.
//
// WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received.
// The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack.
PinSocketAddressBuffer();
}
internal unsafe SocketError DoOperationReceiveFrom(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred)
{
PrepareIOCPOperation();
flags = _socketFlags;
SocketError socketError;
if (_buffer != null)
{
socketError = Interop.Winsock.WSARecvFrom(
handle,
ref _wsaBuffer,
1,
out bytesTransferred,
ref flags,
_ptrSocketAddressBuffer,
_ptrSocketAddressBufferSize,
_ptrNativeOverlapped,
IntPtr.Zero);
}
else
{
socketError = Interop.Winsock.WSARecvFrom(
handle,
_wsaBufferArray,
_wsaBufferArray.Length,
out bytesTransferred,
ref flags,
_ptrSocketAddressBuffer,
_ptrSocketAddressBufferSize,
_ptrNativeOverlapped,
IntPtr.Zero);
}
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
private void InnerStartOperationReceiveMessageFrom()
{
// WSARecvMsg uses a WSAMsg descriptor.
// The WSAMsg buffer is pinned with a GCHandle to avoid complicating the use of Overlapped.
// WSAMsg contains a pointer to a sockaddr.
// The sockaddr is pinned with a GCHandle to avoid complicating the use of Overlapped.
// WSAMsg contains a pointer to a WSABuffer array describing data buffers.
// WSAMsg also contains a single WSABuffer describing a control buffer.
PinSocketAddressBuffer();
// Create and pin a WSAMessageBuffer if none already.
if (_wsaMessageBuffer == null)
{
_wsaMessageBuffer = new byte[s_wsaMsgSize];
_wsaMessageBufferGCHandle = GCHandle.Alloc(_wsaMessageBuffer, GCHandleType.Pinned);
_ptrWSAMessageBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);
}
// Create and pin an appropriately sized control buffer if none already
IPAddress ipAddress = (_socketAddress.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null);
bool ipv4 = (_currentSocket.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode
bool ipv6 = _currentSocket.AddressFamily == AddressFamily.InterNetworkV6;
if (ipv4 && (_controlBuffer == null || _controlBuffer.Length != s_controlDataSize))
{
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
}
_controlBuffer = new byte[s_controlDataSize];
}
else if (ipv6 && (_controlBuffer == null || _controlBuffer.Length != s_controlDataIPv6Size))
{
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
}
_controlBuffer = new byte[s_controlDataIPv6Size];
}
if (!_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle = GCHandle.Alloc(_controlBuffer, GCHandleType.Pinned);
_ptrControlBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_controlBuffer, 0);
}
// If single buffer we need a pinned 1 element WSABuffer.
if (_buffer != null)
{
if (_wsaRecvMsgWSABufferArray == null)
{
_wsaRecvMsgWSABufferArray = new WSABuffer[1];
}
_wsaRecvMsgWSABufferArray[0].Pointer = _ptrSingleBuffer;
_wsaRecvMsgWSABufferArray[0].Length = _count;
_wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaRecvMsgWSABufferArray, GCHandleType.Pinned);
_ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaRecvMsgWSABufferArray, 0);
}
else
{
// Just pin the multi-buffer WSABuffer.
_wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaBufferArray, GCHandleType.Pinned);
_ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaBufferArray, 0);
}
// Fill in WSAMessageBuffer.
unsafe
{
Interop.Winsock.WSAMsg* pMessage = (Interop.Winsock.WSAMsg*)_ptrWSAMessageBuffer; ;
pMessage->socketAddress = _ptrSocketAddressBuffer;
pMessage->addressLength = (uint)_socketAddress.Size;
pMessage->buffers = _ptrWSARecvMsgWSABufferArray;
if (_buffer != null)
{
pMessage->count = (uint)1;
}
else
{
pMessage->count = (uint)_wsaBufferArray.Length;
}
if (_controlBuffer != null)
{
pMessage->controlBuffer.Pointer = _ptrControlBuffer;
pMessage->controlBuffer.Length = _controlBuffer.Length;
}
pMessage->flags = _socketFlags;
}
}
internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeCloseSocket handle, out int bytesTransferred)
{
PrepareIOCPOperation();
SocketError socketError = socket.WSARecvMsg(
handle,
_ptrWSAMessageBuffer,
out bytesTransferred,
_ptrNativeOverlapped,
IntPtr.Zero);
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
private void InnerStartOperationSend()
{
// WSASend uses a WSABuffer array describing buffers of data to send.
//
// Single and multiple buffers are handled differently so as to optimize
// performance for the more common single buffer case.
//
// For a single buffer:
// The Overlapped.UnsafePack method is used that takes a single object to pin.
// A single WSABuffer that pre-exists in SocketAsyncEventArgs is used.
//
// For multiple buffers:
// The Overlapped.UnsafePack method is used that takes an array of objects to pin.
// An array to reference the multiple buffer is allocated.
// An array of WSABuffer descriptors is allocated.
}
internal unsafe SocketError DoOperationSend(SafeCloseSocket handle, out int bytesTransferred)
{
PrepareIOCPOperation();
SocketError socketError;
if (_buffer != null)
{
// Single buffer case.
socketError = Interop.Winsock.WSASend(
handle,
ref _wsaBuffer,
1,
out bytesTransferred,
_socketFlags,
_ptrNativeOverlapped,
IntPtr.Zero);
}
else
{
// Multi buffer case.
socketError = Interop.Winsock.WSASend(
handle,
_wsaBufferArray,
_wsaBufferArray.Length,
out bytesTransferred,
_socketFlags,
_ptrNativeOverlapped,
IntPtr.Zero);
}
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
private void InnerStartOperationSendPackets()
{
// Prevent mutithreaded manipulation of the list.
if (_sendPacketsElements != null)
{
_sendPacketsElementsInternal = (SendPacketsElement[])_sendPacketsElements.Clone();
}
// TransmitPackets uses an array of TRANSMIT_PACKET_ELEMENT structs as
// descriptors for buffers and files to be sent. It also takes a send size
// and some flags. The TRANSMIT_PACKET_ELEMENT for a file contains a native file handle.
// This function basically opens the files to get the file handles, pins down any buffers
// specified and builds the native TRANSMIT_PACKET_ELEMENT array that will be passed
// to TransmitPackets.
// Scan the elements to count files and buffers.
_sendPacketsElementsFileCount = 0;
_sendPacketsElementsBufferCount = 0;
Debug.Assert(_sendPacketsElementsInternal != null);
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null)
{
if (spe._filePath != null)
{
_sendPacketsElementsFileCount++;
}
if (spe._buffer != null && spe._count > 0)
{
_sendPacketsElementsBufferCount++;
}
}
}
// Attempt to open the files if any were given.
if (_sendPacketsElementsFileCount > 0)
{
// Create arrays for streams and handles.
_sendPacketsFileStreams = new FileStream[_sendPacketsElementsFileCount];
_sendPacketsFileHandles = new SafeHandle[_sendPacketsElementsFileCount];
// Loop through the elements attempting to open each files and get its handle.
int index = 0;
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null && spe._filePath != null)
{
Exception fileStreamException = null;
try
{
// Create a FileStream to open the file.
_sendPacketsFileStreams[index] =
new FileStream(spe._filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (Exception ex)
{
// Save the exception to throw after closing any previous successful file opens.
fileStreamException = ex;
}
if (fileStreamException != null)
{
// Got an exception opening a file - do some cleanup then throw.
for (int i = 0; i < _sendPacketsElementsFileCount; i++)
{
// Drop handles.
_sendPacketsFileHandles[i] = null;
// Close any open streams.
if (_sendPacketsFileStreams[i] != null)
{
_sendPacketsFileStreams[i].Dispose();
_sendPacketsFileStreams[i] = null;
}
}
throw fileStreamException;
}
// Get the file handle from the stream.
_sendPacketsFileHandles[index] = _sendPacketsFileStreams[index].SafeFileHandle;
index++;
}
}
}
CheckPinSendPackets();
}
internal SocketError DoOperationSendPackets(Socket socket, SafeCloseSocket handle)
{
PrepareIOCPOperation();
bool result = socket.TransmitPackets(
handle,
_ptrSendPacketsDescriptor,
_sendPacketsDescriptor.Length,
_sendPacketsSendSize,
_ptrNativeOverlapped);
return result ? SocketError.Success : SocketPal.GetLastSocketError();
}
private void InnerStartOperationSendTo()
{
// WSASendTo uses a WSABuffer array describing buffers in which to
// receive data and from which to send data respectively. Single and multiple buffers
// are handled differently so as to optimize performance for the more common single buffer case.
//
// For a single buffer:
// The Overlapped.UnsafePack method is used that takes a single object to pin.
// A single WSABuffer that pre-exists in SocketAsyncEventArgs is used.
//
// For multiple buffers:
// The Overlapped.UnsafePack method is used that takes an array of objects to pin.
// An array to reference the multiple buffer is allocated.
// An array of WSABuffer descriptors is allocated.
//
// WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received.
// The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack.
PinSocketAddressBuffer();
}
internal SocketError DoOperationSendTo(SafeCloseSocket handle, out int bytesTransferred)
{
PrepareIOCPOperation();
SocketError socketError;
if (_buffer != null)
{
// Single buffer case.
socketError = Interop.Winsock.WSASendTo(
handle,
ref _wsaBuffer,
1,
out bytesTransferred,
_socketFlags,
_ptrSocketAddressBuffer,
_socketAddress.Size,
_ptrNativeOverlapped,
IntPtr.Zero);
}
else
{
socketError = Interop.Winsock.WSASendTo(
handle,
_wsaBufferArray,
_wsaBufferArray.Length,
out bytesTransferred,
_socketFlags,
_ptrSocketAddressBuffer,
_socketAddress.Size,
_ptrNativeOverlapped,
IntPtr.Zero);
}
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
// Ensures Overlapped object exists for operations that need no data buffer.
private void CheckPinNoBuffer()
{
// PreAllocatedOverlapped will be reused.
if (_pinState == PinState.None)
{
SetupOverlappedSingle(true);
}
}
// Maintains pinned state of single buffer.
private void CheckPinSingleBuffer(bool pinUsersBuffer)
{
if (pinUsersBuffer)
{
// Using app supplied buffer.
if (_buffer == null)
{
// No user buffer is set so unpin any existing single buffer pinning.
if (_pinState == PinState.SingleBuffer)
{
FreeOverlapped(false);
}
}
else
{
if (_pinState == PinState.SingleBuffer && _pinnedSingleBuffer == _buffer)
{
// This buffer is already pinned - update if offset or count has changed.
if (_offset != _pinnedSingleBufferOffset)
{
_pinnedSingleBufferOffset = _offset;
_ptrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, _offset);
_wsaBuffer.Pointer = _ptrSingleBuffer;
}
if (_count != _pinnedSingleBufferCount)
{
_pinnedSingleBufferCount = _count;
_wsaBuffer.Length = _count;
}
}
else
{
FreeOverlapped(false);
SetupOverlappedSingle(true);
}
}
}
else
{
// Using internal accept buffer.
if (!(_pinState == PinState.SingleAcceptBuffer) || !(_pinnedSingleBuffer == _acceptBuffer))
{
// Not already pinned - so pin it.
FreeOverlapped(false);
SetupOverlappedSingle(false);
}
}
}
// Ensures Overlapped object exists with appropriate multiple buffers pinned.
private void CheckPinMultipleBuffers()
{
if (_bufferList == null)
{
// No buffer list is set so unpin any existing multiple buffer pinning.
if (_pinState == PinState.MultipleBuffer)
{
FreeOverlapped(false);
}
}
else
{
if (!(_pinState == PinState.MultipleBuffer) || _bufferListChanged)
{
// Need to setup a new Overlapped.
_bufferListChanged = false;
FreeOverlapped(false);
try
{
SetupOverlappedMultiple();
}
catch (Exception)
{
FreeOverlapped(false);
throw;
}
}
}
}
// Ensures Overlapped object exists with appropriate buffers pinned.
private void CheckPinSendPackets()
{
if (_pinState != PinState.None)
{
FreeOverlapped(false);
}
SetupOverlappedSendPackets();
}
// Ensures appropriate SocketAddress buffer is pinned.
private void PinSocketAddressBuffer()
{
// Check if already pinned.
if (_pinnedSocketAddress == _socketAddress)
{
return;
}
// Unpin any existing.
if (_socketAddressGCHandle.IsAllocated)
{
_socketAddressGCHandle.Free();
}
// Pin down the new one.
_socketAddressGCHandle = GCHandle.Alloc(_socketAddress.Buffer, GCHandleType.Pinned);
_socketAddress.CopyAddressSizeIntoBuffer();
_ptrSocketAddressBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, 0);
_ptrSocketAddressBufferSize = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, _socketAddress.GetAddressSizeOffset());
_pinnedSocketAddress = _socketAddress;
}
// Cleans up any existing Overlapped object and related state variables.
private void FreeOverlapped(bool checkForShutdown)
{
if (!checkForShutdown || !Environment.HasShutdownStarted)
{
// Free the overlapped object.
if (_ptrNativeOverlapped != null && !_ptrNativeOverlapped.IsInvalid)
{
_ptrNativeOverlapped.Dispose();
_ptrNativeOverlapped = null;
}
// Free the preallocated overlapped object. This in turn will unpin
// any pinned buffers.
if (_preAllocatedOverlapped != null)
{
_preAllocatedOverlapped.Dispose();
_preAllocatedOverlapped = null;
_pinState = PinState.None;
_pinnedAcceptBuffer = null;
_pinnedSingleBuffer = null;
_pinnedSingleBufferOffset = 0;
_pinnedSingleBufferCount = 0;
}
// Free any allocated GCHandles.
if (_socketAddressGCHandle.IsAllocated)
{
_socketAddressGCHandle.Free();
_pinnedSocketAddress = null;
}
if (_wsaMessageBufferGCHandle.IsAllocated)
{
_wsaMessageBufferGCHandle.Free();
_ptrWSAMessageBuffer = IntPtr.Zero;
}
if (_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated)
{
_wsaRecvMsgWSABufferArrayGCHandle.Free();
_ptrWSARecvMsgWSABufferArray = IntPtr.Zero;
}
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
_ptrControlBuffer = IntPtr.Zero;
}
}
}
// Sets up an Overlapped object with either _buffer or _acceptBuffer pinned.
unsafe private void SetupOverlappedSingle(bool pinSingleBuffer)
{
// Pin buffer, get native pointers, and fill in WSABuffer descriptor.
if (pinSingleBuffer)
{
if (_buffer != null)
{
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _buffer);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
"::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=true, non-null buffer: " +
LoggingHash.HashString(_preAllocatedOverlapped));
}
_pinnedSingleBuffer = _buffer;
_pinnedSingleBufferOffset = _offset;
_pinnedSingleBufferCount = _count;
_ptrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, _offset);
_ptrAcceptBuffer = IntPtr.Zero;
_wsaBuffer.Pointer = _ptrSingleBuffer;
_wsaBuffer.Length = _count;
_pinState = PinState.SingleBuffer;
}
else
{
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, null);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
"::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=true, null buffer: " +
LoggingHash.HashString(_preAllocatedOverlapped));
}
_pinnedSingleBuffer = null;
_pinnedSingleBufferOffset = 0;
_pinnedSingleBufferCount = 0;
_ptrSingleBuffer = IntPtr.Zero;
_ptrAcceptBuffer = IntPtr.Zero;
_wsaBuffer.Pointer = _ptrSingleBuffer;
_wsaBuffer.Length = _count;
_pinState = PinState.NoBuffer;
}
}
else
{
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _acceptBuffer);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
"::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=false: " +
LoggingHash.HashString(_preAllocatedOverlapped));
}
_pinnedAcceptBuffer = _acceptBuffer;
_ptrAcceptBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_acceptBuffer, 0);
_ptrSingleBuffer = IntPtr.Zero;
_pinState = PinState.SingleAcceptBuffer;
}
}
// Sets up an Overlapped object with multiple buffers pinned.
unsafe private void SetupOverlappedMultiple()
{
ArraySegment<byte>[] tempList = new ArraySegment<byte>[_bufferList.Count];
_bufferList.CopyTo(tempList, 0);
// Number of things to pin is number of buffers.
// Ensure we have properly sized object array.
if (_objectsToPin == null || (_objectsToPin.Length != tempList.Length))
{
_objectsToPin = new object[tempList.Length];
}
// Fill in object array.
for (int i = 0; i < (tempList.Length); i++)
{
_objectsToPin[i] = tempList[i].Array;
}
if (_wsaBufferArray == null || _wsaBufferArray.Length != tempList.Length)
{
_wsaBufferArray = new WSABuffer[tempList.Length];
}
// Pin buffers and fill in WSABuffer descriptor pointers and lengths.
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedMultiple: new PreAllocatedOverlapped." +
LoggingHash.HashString(_preAllocatedOverlapped));
}
for (int i = 0; i < tempList.Length; i++)
{
ArraySegment<byte> localCopy = tempList[i];
RangeValidationHelpers.ValidateSegment(localCopy);
_wsaBufferArray[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array, localCopy.Offset);
_wsaBufferArray[i].Length = localCopy.Count;
}
_pinState = PinState.MultipleBuffer;
}
// Sets up an Overlapped object for SendPacketsAsync.
unsafe private void SetupOverlappedSendPackets()
{
int index;
// Alloc native descriptor.
_sendPacketsDescriptor =
new Interop.Winsock.TransmitPacketsElement[_sendPacketsElementsFileCount + _sendPacketsElementsBufferCount];
// Number of things to pin is number of buffers + 1 (native descriptor).
// Ensure we have properly sized object array.
if (_objectsToPin == null || (_objectsToPin.Length != _sendPacketsElementsBufferCount + 1))
{
_objectsToPin = new object[_sendPacketsElementsBufferCount + 1];
}
// Fill in objects to pin array. Native descriptor buffer first and then user specified buffers.
_objectsToPin[0] = _sendPacketsDescriptor;
index = 1;
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null && spe._buffer != null && spe._count > 0)
{
_objectsToPin[index] = spe._buffer;
index++;
}
}
// Pin buffers.
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSendPackets: new PreAllocatedOverlapped: " +
LoggingHash.HashString(_preAllocatedOverlapped));
}
// Get pointer to native descriptor.
_ptrSendPacketsDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(_sendPacketsDescriptor, 0);
// Fill in native descriptor.
int descriptorIndex = 0;
int fileIndex = 0;
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null)
{
if (spe._buffer != null && spe._count > 0)
{
// This element is a buffer.
_sendPacketsDescriptor[descriptorIndex].buffer = Marshal.UnsafeAddrOfPinnedArrayElement(spe._buffer, spe._offset);
_sendPacketsDescriptor[descriptorIndex].length = (uint)spe._count;
_sendPacketsDescriptor[descriptorIndex].flags = (Interop.Winsock.TransmitPacketsElementFlags)spe._flags;
descriptorIndex++;
}
else if (spe._filePath != null)
{
// This element is a file.
_sendPacketsDescriptor[descriptorIndex].fileHandle = _sendPacketsFileHandles[fileIndex].DangerousGetHandle();
_sendPacketsDescriptor[descriptorIndex].fileOffset = spe._offset;
_sendPacketsDescriptor[descriptorIndex].length = (uint)spe._count;
_sendPacketsDescriptor[descriptorIndex].flags = (Interop.Winsock.TransmitPacketsElementFlags)spe._flags;
fileIndex++;
descriptorIndex++;
}
}
}
_pinState = PinState.SendPackets;
}
internal void LogBuffer(int size)
{
switch (_pinState)
{
case PinState.SingleAcceptBuffer:
SocketsEventSource.Dump(_acceptBuffer, 0, size);
break;
case PinState.SingleBuffer:
SocketsEventSource.Dump(_buffer, _offset, size);
break;
case PinState.MultipleBuffer:
foreach (WSABuffer wsaBuffer in _wsaBufferArray)
{
SocketsEventSource.Dump(wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size));
if ((size -= wsaBuffer.Length) <= 0)
{
break;
}
}
break;
default:
break;
}
}
internal void LogSendPacketsBuffers(int size)
{
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null)
{
if (spe._buffer != null && spe._count > 0)
{
// This element is a buffer.
SocketsEventSource.Dump(spe._buffer, spe._offset, Math.Min(spe._count, size));
}
else if (spe._filePath != null)
{
// This element is a file.
SocketsEventSource.Log.NotLoggedFile(spe._filePath, LoggingHash.HashInt(_currentSocket), _completedOperation);
}
}
}
}
private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress)
{
SocketError socketError;
IntPtr localAddr;
int localAddrLength;
IntPtr remoteAddr;
try
{
_currentSocket.GetAcceptExSockaddrs(
_ptrSingleBuffer != IntPtr.Zero ? _ptrSingleBuffer : _ptrAcceptBuffer,
_count != 0 ? _count - _acceptAddressBufferCount : 0,
_acceptAddressBufferCount / 2,
_acceptAddressBufferCount / 2,
out localAddr,
out localAddrLength,
out remoteAddr,
out remoteSocketAddress.InternalSize
);
Marshal.Copy(remoteAddr, remoteSocketAddress.Buffer, 0, remoteSocketAddress.Size);
// Set the socket context.
IntPtr handle = _currentSocket.SafeHandle.DangerousGetHandle();
socketError = Interop.Winsock.setsockopt(
_acceptSocket.SafeHandle,
SocketOptionLevel.Socket,
SocketOptionName.UpdateAcceptContext,
ref handle,
Marshal.SizeOf(handle));
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
}
catch (ObjectDisposedException)
{
socketError = SocketError.OperationAborted;
}
return socketError;
}
private SocketError FinishOperationConnect()
{
SocketError socketError;
// Update the socket context.
try
{
socketError = Interop.Winsock.setsockopt(
_currentSocket.SafeHandle,
SocketOptionLevel.Socket,
SocketOptionName.UpdateConnectContext,
null,
0);
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
}
catch (ObjectDisposedException)
{
socketError = SocketError.OperationAborted;
}
return socketError;
}
private unsafe int GetSocketAddressSize()
{
return *(int*)_ptrSocketAddressBufferSize;
}
private unsafe void FinishOperationReceiveMessageFrom()
{
IPAddress address = null;
Interop.Winsock.WSAMsg* PtrMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);
if (_controlBuffer.Length == s_controlDataSize)
{
// IPv4.
Interop.Winsock.ControlData controlData = Marshal.PtrToStructure<Interop.Winsock.ControlData>(PtrMessage->controlBuffer.Pointer);
if (controlData.length != UIntPtr.Zero)
{
address = new IPAddress((long)controlData.address);
}
_receiveMessageFromPacketInfo = new IPPacketInformation(((address != null) ? address : IPAddress.None), (int)controlData.index);
}
else if (_controlBuffer.Length == s_controlDataIPv6Size)
{
// IPv6.
Interop.Winsock.ControlDataIPv6 controlData = Marshal.PtrToStructure<Interop.Winsock.ControlDataIPv6>(PtrMessage->controlBuffer.Pointer);
if (controlData.length != UIntPtr.Zero)
{
address = new IPAddress(controlData.address);
}
_receiveMessageFromPacketInfo = new IPPacketInformation(((address != null) ? address : IPAddress.IPv6None), (int)controlData.index);
}
else
{
// Other.
_receiveMessageFromPacketInfo = new IPPacketInformation();
}
}
private void FinishOperationSendPackets()
{
// Close the files if open.
if (_sendPacketsFileStreams != null)
{
for (int i = 0; i < _sendPacketsElementsFileCount; i++)
{
// Drop handles.
_sendPacketsFileHandles[i] = null;
// Close any open streams.
if (_sendPacketsFileStreams[i] != null)
{
_sendPacketsFileStreams[i].Dispose();
_sendPacketsFileStreams[i] = null;
}
}
}
_sendPacketsFileStreams = null;
_sendPacketsFileHandles = null;
}
private unsafe void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
#if DEBUG
GlobalLog.SetThreadSource(ThreadKinds.CompletionPort);
using (GlobalLog.SetThreadKind(ThreadKinds.System))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter(
"CompletionPortCallback",
"errorCode: " + errorCode + ", numBytes: " + numBytes +
", overlapped#" + ((IntPtr)nativeOverlapped).ToString("x"));
}
#endif
SocketFlags socketFlags = SocketFlags.None;
SocketError socketError = (SocketError)errorCode;
// This is the same NativeOverlapped* as we already have a SafeHandle for, re-use the original.
Debug.Assert((IntPtr)nativeOverlapped == _ptrNativeOverlapped.DangerousGetHandle(), "Handle mismatch");
if (socketError == SocketError.Success)
{
FinishOperationSuccess(socketError, (int)numBytes, socketFlags);
}
else
{
if (socketError != SocketError.OperationAborted)
{
if (_currentSocket.CleanedUp)
{
socketError = SocketError.OperationAborted;
}
else
{
try
{
// The Async IO completed with a failure.
// here we need to call WSAGetOverlappedResult() just so Marshal.GetLastWin32Error() will return the correct error.
bool success = Interop.Winsock.WSAGetOverlappedResult(
_currentSocket.SafeHandle,
_ptrNativeOverlapped,
out numBytes,
false,
out socketFlags);
socketError = SocketPal.GetLastSocketError();
}
catch
{
// _currentSocket.CleanedUp check above does not always work since this code is subject to race conditions.
socketError = SocketError.OperationAborted;
}
}
}
FinishOperationAsyncFailure(socketError, (int)numBytes, socketFlags);
}
#if DEBUG
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("CompletionPortCallback");
}
}
#endif
}
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
using System;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
// flibit Added This!!!
#pragma warning disable 3021
namespace OpenTK
{
/// <summary>Represents a 4D vector using four double-precision floating-point numbers.</summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector4d : IEquatable<Vector4d>
{
#region Fields
/// <summary>
/// The X component of the Vector4d.
/// </summary>
public double X;
/// <summary>
/// The Y component of the Vector4d.
/// </summary>
public double Y;
/// <summary>
/// The Z component of the Vector4d.
/// </summary>
public double Z;
/// <summary>
/// The W component of the Vector4d.
/// </summary>
public double W;
/// <summary>
/// Defines a unit-length Vector4d that points towards the X-axis.
/// </summary>
public static Vector4d UnitX = new Vector4d(1, 0, 0, 0);
/// <summary>
/// Defines a unit-length Vector4d that points towards the Y-axis.
/// </summary>
public static Vector4d UnitY = new Vector4d(0, 1, 0, 0);
/// <summary>
/// Defines a unit-length Vector4d that points towards the Z-axis.
/// </summary>
public static Vector4d UnitZ = new Vector4d(0, 0, 1, 0);
/// <summary>
/// Defines a unit-length Vector4d that points towards the W-axis.
/// </summary>
public static Vector4d UnitW = new Vector4d(0, 0, 0, 1);
/// <summary>
/// Defines a zero-length Vector4d.
/// </summary>
public static Vector4d Zero = new Vector4d(0, 0, 0, 0);
/// <summary>
/// Defines an instance with all components set to 1.
/// </summary>
public static readonly Vector4d One = new Vector4d(1, 1, 1, 1);
/// <summary>
/// Defines the size of the Vector4d struct in bytes.
/// </summary>
public static readonly int SizeInBytes = Marshal.SizeOf(new Vector4d());
#endregion
#region Constructors
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector4d(double value)
{
X = value;
Y = value;
Z = value;
W = value;
}
/// <summary>
/// Constructs a new Vector4d.
/// </summary>
/// <param name="x">The x component of the Vector4d.</param>
/// <param name="y">The y component of the Vector4d.</param>
/// <param name="z">The z component of the Vector4d.</param>
/// <param name="w">The w component of the Vector4d.</param>
public Vector4d(double x, double y, double z, double w)
{
X = x;
Y = y;
Z = z;
W = w;
}
/// <summary>
/// Constructs a new Vector4d from the given Vector2d.
/// </summary>
/// <param name="v">The Vector2d to copy components from.</param>
public Vector4d(Vector2d v)
{
X = v.X;
Y = v.Y;
Z = 0.0f;
W = 0.0f;
}
/// <summary>
/// Constructs a new Vector4d from the given Vector3d.
/// The w component is initialized to 0.
/// </summary>
/// <param name="v">The Vector3d to copy components from.</param>
/// <remarks><seealso cref="Vector4d(Vector3d, double)"/></remarks>
public Vector4d(Vector3d v)
{
X = v.X;
Y = v.Y;
Z = v.Z;
W = 0.0f;
}
/// <summary>
/// Constructs a new Vector4d from the specified Vector3d and w component.
/// </summary>
/// <param name="v">The Vector3d to copy components from.</param>
/// <param name="w">The w component of the new Vector4.</param>
public Vector4d(Vector3d v, double w)
{
X = v.X;
Y = v.Y;
Z = v.Z;
W = w;
}
/// <summary>
/// Constructs a new Vector4d from the given Vector4d.
/// </summary>
/// <param name="v">The Vector4d to copy components from.</param>
public Vector4d(Vector4d v)
{
X = v.X;
Y = v.Y;
Z = v.Z;
W = v.W;
}
#endregion
#region Public Members
#region Instance
#region public void Add()
/// <summary>Add the Vector passed as parameter to this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
[Obsolete("Use static Add() method instead.")]
public void Add(Vector4d right)
{
this.X += right.X;
this.Y += right.Y;
this.Z += right.Z;
this.W += right.W;
}
/// <summary>Add the Vector passed as parameter to this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
[CLSCompliant(false)]
[Obsolete("Use static Add() method instead.")]
public void Add(ref Vector4d right)
{
this.X += right.X;
this.Y += right.Y;
this.Z += right.Z;
this.W += right.W;
}
#endregion public void Add()
#region public void Sub()
/// <summary>Subtract the Vector passed as parameter from this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
[Obsolete("Use static Subtract() method instead.")]
public void Sub(Vector4d right)
{
this.X -= right.X;
this.Y -= right.Y;
this.Z -= right.Z;
this.W -= right.W;
}
/// <summary>Subtract the Vector passed as parameter from this instance.</summary>
/// <param name="right">Right operand. This parameter is only read from.</param>
[CLSCompliant(false)]
[Obsolete("Use static Subtract() method instead.")]
public void Sub(ref Vector4d right)
{
this.X -= right.X;
this.Y -= right.Y;
this.Z -= right.Z;
this.W -= right.W;
}
#endregion public void Sub()
#region public void Mult()
/// <summary>Multiply this instance by a scalar.</summary>
/// <param name="f">Scalar operand.</param>
[Obsolete("Use static Multiply() method instead.")]
public void Mult(double f)
{
this.X *= f;
this.Y *= f;
this.Z *= f;
this.W *= f;
}
#endregion public void Mult()
#region public void Div()
/// <summary>Divide this instance by a scalar.</summary>
/// <param name="f">Scalar operand.</param>
[Obsolete("Use static Divide() method instead.")]
public void Div(double f)
{
double mult = 1.0 / f;
this.X *= mult;
this.Y *= mult;
this.Z *= mult;
this.W *= mult;
}
#endregion public void Div()
#region public double Length
/// <summary>
/// Gets the length (magnitude) of the vector.
/// </summary>
/// <see cref="LengthFast"/>
/// <seealso cref="LengthSquared"/>
public double Length
{
get
{
return System.Math.Sqrt(X * X + Y * Y + Z * Z + W * W);
}
}
#endregion
#region public double LengthFast
/// <summary>
/// Gets an approximation of the vector length (magnitude).
/// </summary>
/// <remarks>
/// This property uses an approximation of the square root function to calculate vector magnitude, with
/// an upper error bound of 0.001.
/// </remarks>
/// <see cref="Length"/>
/// <seealso cref="LengthSquared"/>
public double LengthFast
{
get
{
return 1.0 / MathHelper.InverseSqrtFast(X * X + Y * Y + Z * Z + W * W);
}
}
#endregion
#region public double LengthSquared
/// <summary>
/// Gets the square of the vector length (magnitude).
/// </summary>
/// <remarks>
/// This property avoids the costly square root operation required by the Length property. This makes it more suitable
/// for comparisons.
/// </remarks>
/// <see cref="Length"/>
public double LengthSquared
{
get
{
return X * X + Y * Y + Z * Z + W * W;
}
}
#endregion
#region public void Normalize()
/// <summary>
/// Scales the Vector4d to unit length.
/// </summary>
public void Normalize()
{
double scale = 1.0 / this.Length;
X *= scale;
Y *= scale;
Z *= scale;
W *= scale;
}
#endregion
#region public void NormalizeFast()
/// <summary>
/// Scales the Vector4d to approximately unit length.
/// </summary>
public void NormalizeFast()
{
double scale = MathHelper.InverseSqrtFast(X * X + Y * Y + Z * Z + W * W);
X *= scale;
Y *= scale;
Z *= scale;
W *= scale;
}
#endregion
#region public void Scale()
/// <summary>
/// Scales the current Vector4d by the given amounts.
/// </summary>
/// <param name="sx">The scale of the X component.</param>
/// <param name="sy">The scale of the Y component.</param>
/// <param name="sz">The scale of the Z component.</param>
/// <param name="sw">The scale of the Z component.</param>
[Obsolete("Use static Multiply() method instead.")]
public void Scale(double sx, double sy, double sz, double sw)
{
this.X = X * sx;
this.Y = Y * sy;
this.Z = Z * sz;
this.W = W * sw;
}
/// <summary>Scales this instance by the given parameter.</summary>
/// <param name="scale">The scaling of the individual components.</param>
[Obsolete("Use static Multiply() method instead.")]
public void Scale(Vector4d scale)
{
this.X *= scale.X;
this.Y *= scale.Y;
this.Z *= scale.Z;
this.W *= scale.W;
}
/// <summary>Scales this instance by the given parameter.</summary>
/// <param name="scale">The scaling of the individual components.</param>
[CLSCompliant(false)]
[Obsolete("Use static Multiply() method instead.")]
public void Scale(ref Vector4d scale)
{
this.X *= scale.X;
this.Y *= scale.Y;
this.Z *= scale.Z;
this.W *= scale.W;
}
#endregion public void Scale()
#endregion
#region Static
#region Obsolete
#region Sub
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>Result of subtraction</returns>
[Obsolete("Use static Subtract() method instead.")]
public static Vector4d Sub(Vector4d a, Vector4d b)
{
a.X -= b.X;
a.Y -= b.Y;
a.Z -= b.Z;
a.W -= b.W;
return a;
}
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">Result of subtraction</param>
[Obsolete("Use static Subtract() method instead.")]
public static void Sub(ref Vector4d a, ref Vector4d b, out Vector4d result)
{
result.X = a.X - b.X;
result.Y = a.Y - b.Y;
result.Z = a.Z - b.Z;
result.W = a.W - b.W;
}
#endregion
#region Mult
/// <summary>
/// Multiply a vector and a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <returns>Result of the multiplication</returns>
[Obsolete("Use static Multiply() method instead.")]
public static Vector4d Mult(Vector4d a, double f)
{
a.X *= f;
a.Y *= f;
a.Z *= f;
a.W *= f;
return a;
}
/// <summary>
/// Multiply a vector and a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <param name="result">Result of the multiplication</param>
[Obsolete("Use static Multiply() method instead.")]
public static void Mult(ref Vector4d a, double f, out Vector4d result)
{
result.X = a.X * f;
result.Y = a.Y * f;
result.Z = a.Z * f;
result.W = a.W * f;
}
#endregion
#region Div
/// <summary>
/// Divide a vector by a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <returns>Result of the division</returns>
[Obsolete("Use static Divide() method instead.")]
public static Vector4d Div(Vector4d a, double f)
{
double mult = 1.0 / f;
a.X *= mult;
a.Y *= mult;
a.Z *= mult;
a.W *= mult;
return a;
}
/// <summary>
/// Divide a vector by a scalar
/// </summary>
/// <param name="a">Vector operand</param>
/// <param name="f">Scalar operand</param>
/// <param name="result">Result of the division</param>
[Obsolete("Use static Divide() method instead.")]
public static void Div(ref Vector4d a, double f, out Vector4d result)
{
double mult = 1.0 / f;
result.X = a.X * mult;
result.Y = a.Y * mult;
result.Z = a.Z * mult;
result.W = a.W * mult;
}
#endregion
#endregion
#region Add
/// <summary>
/// Adds two vectors.
/// </summary>
/// <param name="a">Left operand.</param>
/// <param name="b">Right operand.</param>
/// <returns>Result of operation.</returns>
public static Vector4d Add(Vector4d a, Vector4d b)
{
Add(ref a, ref b, out a);
return a;
}
/// <summary>
/// Adds two vectors.
/// </summary>
/// <param name="a">Left operand.</param>
/// <param name="b">Right operand.</param>
/// <param name="result">Result of operation.</param>
public static void Add(ref Vector4d a, ref Vector4d b, out Vector4d result)
{
result = new Vector4d(a.X + b.X, a.Y + b.Y, a.Z + b.Z, a.W + b.W);
}
#endregion
#region Subtract
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>Result of subtraction</returns>
public static Vector4d Subtract(Vector4d a, Vector4d b)
{
Subtract(ref a, ref b, out a);
return a;
}
/// <summary>
/// Subtract one Vector from another
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">Result of subtraction</param>
public static void Subtract(ref Vector4d a, ref Vector4d b, out Vector4d result)
{
result = new Vector4d(a.X - b.X, a.Y - b.Y, a.Z - b.Z, a.W - b.W);
}
#endregion
#region Multiply
/// <summary>
/// Multiplies a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector4d Multiply(Vector4d vector, double scale)
{
Multiply(ref vector, scale, out vector);
return vector;
}
/// <summary>
/// Multiplies a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Multiply(ref Vector4d vector, double scale, out Vector4d result)
{
result = new Vector4d(vector.X * scale, vector.Y * scale, vector.Z * scale, vector.W * scale);
}
/// <summary>
/// Multiplies a vector by the components a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector4d Multiply(Vector4d vector, Vector4d scale)
{
Multiply(ref vector, ref scale, out vector);
return vector;
}
/// <summary>
/// Multiplies a vector by the components of a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Multiply(ref Vector4d vector, ref Vector4d scale, out Vector4d result)
{
result = new Vector4d(vector.X * scale.X, vector.Y * scale.Y, vector.Z * scale.Z, vector.W * scale.W);
}
#endregion
#region Divide
/// <summary>
/// Divides a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector4d Divide(Vector4d vector, double scale)
{
Divide(ref vector, scale, out vector);
return vector;
}
/// <summary>
/// Divides a vector by a scalar.
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Divide(ref Vector4d vector, double scale, out Vector4d result)
{
Multiply(ref vector, 1 / scale, out result);
}
/// <summary>
/// Divides a vector by the components of a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <returns>Result of the operation.</returns>
public static Vector4d Divide(Vector4d vector, Vector4d scale)
{
Divide(ref vector, ref scale, out vector);
return vector;
}
/// <summary>
/// Divide a vector by the components of a vector (scale).
/// </summary>
/// <param name="vector">Left operand.</param>
/// <param name="scale">Right operand.</param>
/// <param name="result">Result of the operation.</param>
public static void Divide(ref Vector4d vector, ref Vector4d scale, out Vector4d result)
{
result = new Vector4d(vector.X / scale.X, vector.Y / scale.Y, vector.Z / scale.Z, vector.W / scale.W);
}
#endregion
#region Min
/// <summary>
/// Calculate the component-wise minimum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>The component-wise minimum</returns>
public static Vector4d Min(Vector4d a, Vector4d b)
{
a.X = a.X < b.X ? a.X : b.X;
a.Y = a.Y < b.Y ? a.Y : b.Y;
a.Z = a.Z < b.Z ? a.Z : b.Z;
a.W = a.W < b.W ? a.W : b.W;
return a;
}
/// <summary>
/// Calculate the component-wise minimum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">The component-wise minimum</param>
public static void Min(ref Vector4d a, ref Vector4d b, out Vector4d result)
{
result.X = a.X < b.X ? a.X : b.X;
result.Y = a.Y < b.Y ? a.Y : b.Y;
result.Z = a.Z < b.Z ? a.Z : b.Z;
result.W = a.W < b.W ? a.W : b.W;
}
#endregion
#region Max
/// <summary>
/// Calculate the component-wise maximum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <returns>The component-wise maximum</returns>
public static Vector4d Max(Vector4d a, Vector4d b)
{
a.X = a.X > b.X ? a.X : b.X;
a.Y = a.Y > b.Y ? a.Y : b.Y;
a.Z = a.Z > b.Z ? a.Z : b.Z;
a.W = a.W > b.W ? a.W : b.W;
return a;
}
/// <summary>
/// Calculate the component-wise maximum of two vectors
/// </summary>
/// <param name="a">First operand</param>
/// <param name="b">Second operand</param>
/// <param name="result">The component-wise maximum</param>
public static void Max(ref Vector4d a, ref Vector4d b, out Vector4d result)
{
result.X = a.X > b.X ? a.X : b.X;
result.Y = a.Y > b.Y ? a.Y : b.Y;
result.Z = a.Z > b.Z ? a.Z : b.Z;
result.W = a.W > b.W ? a.W : b.W;
}
#endregion
#region Clamp
/// <summary>
/// Clamp a vector to the given minimum and maximum vectors
/// </summary>
/// <param name="vec">Input vector</param>
/// <param name="min">Minimum vector</param>
/// <param name="max">Maximum vector</param>
/// <returns>The clamped vector</returns>
public static Vector4d Clamp(Vector4d vec, Vector4d min, Vector4d max)
{
vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X;
vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y;
vec.Z = vec.X < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z;
vec.W = vec.Y < min.W ? min.W : vec.W > max.W ? max.W : vec.W;
return vec;
}
/// <summary>
/// Clamp a vector to the given minimum and maximum vectors
/// </summary>
/// <param name="vec">Input vector</param>
/// <param name="min">Minimum vector</param>
/// <param name="max">Maximum vector</param>
/// <param name="result">The clamped vector</param>
public static void Clamp(ref Vector4d vec, ref Vector4d min, ref Vector4d max, out Vector4d result)
{
result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X;
result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y;
result.Z = vec.X < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z;
result.W = vec.Y < min.W ? min.W : vec.W > max.W ? max.W : vec.W;
}
#endregion
#region Normalize
/// <summary>
/// Scale a vector to unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <returns>The normalized vector</returns>
public static Vector4d Normalize(Vector4d vec)
{
double scale = 1.0 / vec.Length;
vec.X *= scale;
vec.Y *= scale;
vec.Z *= scale;
vec.W *= scale;
return vec;
}
/// <summary>
/// Scale a vector to unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <param name="result">The normalized vector</param>
public static void Normalize(ref Vector4d vec, out Vector4d result)
{
double scale = 1.0 / vec.Length;
result.X = vec.X * scale;
result.Y = vec.Y * scale;
result.Z = vec.Z * scale;
result.W = vec.W * scale;
}
#endregion
#region NormalizeFast
/// <summary>
/// Scale a vector to approximately unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <returns>The normalized vector</returns>
public static Vector4d NormalizeFast(Vector4d vec)
{
double scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z + vec.W * vec.W);
vec.X *= scale;
vec.Y *= scale;
vec.Z *= scale;
vec.W *= scale;
return vec;
}
/// <summary>
/// Scale a vector to approximately unit length
/// </summary>
/// <param name="vec">The input vector</param>
/// <param name="result">The normalized vector</param>
public static void NormalizeFast(ref Vector4d vec, out Vector4d result)
{
double scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z + vec.W * vec.W);
result.X = vec.X * scale;
result.Y = vec.Y * scale;
result.Z = vec.Z * scale;
result.W = vec.W * scale;
}
#endregion
#region Dot
/// <summary>
/// Calculate the dot product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <returns>The dot product of the two inputs</returns>
public static double Dot(Vector4d left, Vector4d right)
{
return left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W;
}
/// <summary>
/// Calculate the dot product of two vectors
/// </summary>
/// <param name="left">First operand</param>
/// <param name="right">Second operand</param>
/// <param name="result">The dot product of the two inputs</param>
public static void Dot(ref Vector4d left, ref Vector4d right, out double result)
{
result = left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W;
}
#endregion
#region Lerp
/// <summary>
/// Returns a new Vector that is the linear blend of the 2 given Vectors
/// </summary>
/// <param name="a">First input vector</param>
/// <param name="b">Second input vector</param>
/// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param>
/// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns>
public static Vector4d Lerp(Vector4d a, Vector4d b, double blend)
{
a.X = blend * (b.X - a.X) + a.X;
a.Y = blend * (b.Y - a.Y) + a.Y;
a.Z = blend * (b.Z - a.Z) + a.Z;
a.W = blend * (b.W - a.W) + a.W;
return a;
}
/// <summary>
/// Returns a new Vector that is the linear blend of the 2 given Vectors
/// </summary>
/// <param name="a">First input vector</param>
/// <param name="b">Second input vector</param>
/// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param>
/// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param>
public static void Lerp(ref Vector4d a, ref Vector4d b, double blend, out Vector4d result)
{
result.X = blend * (b.X - a.X) + a.X;
result.Y = blend * (b.Y - a.Y) + a.Y;
result.Z = blend * (b.Z - a.Z) + a.Z;
result.W = blend * (b.W - a.W) + a.W;
}
#endregion
#region Barycentric
/// <summary>
/// Interpolate 3 Vectors using Barycentric coordinates
/// </summary>
/// <param name="a">First input Vector</param>
/// <param name="b">Second input Vector</param>
/// <param name="c">Third input Vector</param>
/// <param name="u">First Barycentric Coordinate</param>
/// <param name="v">Second Barycentric Coordinate</param>
/// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns>
public static Vector4d BaryCentric(Vector4d a, Vector4d b, Vector4d c, double u, double v)
{
return a + u * (b - a) + v * (c - a);
}
/// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary>
/// <param name="a">First input Vector.</param>
/// <param name="b">Second input Vector.</param>
/// <param name="c">Third input Vector.</param>
/// <param name="u">First Barycentric Coordinate.</param>
/// <param name="v">Second Barycentric Coordinate.</param>
/// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param>
public static void BaryCentric(ref Vector4d a, ref Vector4d b, ref Vector4d c, double u, double v, out Vector4d result)
{
result = a; // copy
Vector4d temp = b; // copy
Subtract(ref temp, ref a, out temp);
Multiply(ref temp, u, out temp);
Add(ref result, ref temp, out result);
temp = c; // copy
Subtract(ref temp, ref a, out temp);
Multiply(ref temp, v, out temp);
Add(ref result, ref temp, out result);
}
#endregion
#region Transform
/// <summary>Transform a Vector by the given Matrix</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <returns>The transformed vector</returns>
public static Vector4d Transform(Vector4d vec, Matrix4d mat)
{
Vector4d result;
Transform(ref vec, ref mat, out result);
return result;
}
/// <summary>Transform a Vector by the given Matrix</summary>
/// <param name="vec">The vector to transform</param>
/// <param name="mat">The desired transformation</param>
/// <param name="result">The transformed vector</param>
public static void Transform(ref Vector4d vec, ref Matrix4d mat, out Vector4d result)
{
result = new Vector4d(
vec.X * mat.Row0.X + vec.Y * mat.Row1.X + vec.Z * mat.Row2.X + vec.W * mat.Row3.X,
vec.X * mat.Row0.Y + vec.Y * mat.Row1.Y + vec.Z * mat.Row2.Y + vec.W * mat.Row3.Y,
vec.X * mat.Row0.Z + vec.Y * mat.Row1.Z + vec.Z * mat.Row2.Z + vec.W * mat.Row3.Z,
vec.X * mat.Row0.W + vec.Y * mat.Row1.W + vec.Z * mat.Row2.W + vec.W * mat.Row3.W);
}
/// <summary>
/// Transforms a vector by a quaternion rotation.
/// </summary>
/// <param name="vec">The vector to transform.</param>
/// <param name="quat">The quaternion to rotate the vector by.</param>
/// <returns>The result of the operation.</returns>
public static Vector4d Transform(Vector4d vec, Quaterniond quat)
{
Vector4d result;
Transform(ref vec, ref quat, out result);
return result;
}
/// <summary>
/// Transforms a vector by a quaternion rotation.
/// </summary>
/// <param name="vec">The vector to transform.</param>
/// <param name="quat">The quaternion to rotate the vector by.</param>
/// <param name="result">The result of the operation.</param>
public static void Transform(ref Vector4d vec, ref Quaterniond quat, out Vector4d result)
{
Quaterniond v = new Quaterniond(vec.X, vec.Y, vec.Z, vec.W), i, t;
Quaterniond.Invert(ref quat, out i);
Quaterniond.Multiply(ref quat, ref v, out t);
Quaterniond.Multiply(ref t, ref i, out v);
result = new Vector4d(v.X, v.Y, v.Z, v.W);
}
#endregion
#endregion
#region Swizzle
/// <summary>
/// Gets or sets an OpenTK.Vector2d with the X and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2d Xy { get { return new Vector2d(X, Y); } set { X = value.X; Y = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3d with the X, Y and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector3d Xyz { get { return new Vector3d(X, Y, Z); } set { X = value.X; Y = value.Y; Z = value.Z; } }
#endregion
#region Operators
/// <summary>
/// Adds two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>The result of the calculation.</returns>
public static Vector4d operator +(Vector4d left, Vector4d right)
{
left.X += right.X;
left.Y += right.Y;
left.Z += right.Z;
left.W += right.W;
return left;
}
/// <summary>
/// Subtracts two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>The result of the calculation.</returns>
public static Vector4d operator -(Vector4d left, Vector4d right)
{
left.X -= right.X;
left.Y -= right.Y;
left.Z -= right.Z;
left.W -= right.W;
return left;
}
/// <summary>
/// Negates an instance.
/// </summary>
/// <param name="vec">The instance.</param>
/// <returns>The result of the calculation.</returns>
public static Vector4d operator -(Vector4d vec)
{
vec.X = -vec.X;
vec.Y = -vec.Y;
vec.Z = -vec.Z;
vec.W = -vec.W;
return vec;
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="vec">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <returns>The result of the calculation.</returns>
public static Vector4d operator *(Vector4d vec, double scale)
{
vec.X *= scale;
vec.Y *= scale;
vec.Z *= scale;
vec.W *= scale;
return vec;
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="scale">The scalar.</param>
/// <param name="vec">The instance.</param>
/// <returns>The result of the calculation.</returns>
public static Vector4d operator *(double scale, Vector4d vec)
{
vec.X *= scale;
vec.Y *= scale;
vec.Z *= scale;
vec.W *= scale;
return vec;
}
/// <summary>
/// Divides an instance by a scalar.
/// </summary>
/// <param name="vec">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <returns>The result of the calculation.</returns>
public static Vector4d operator /(Vector4d vec, double scale)
{
double mult = 1 / scale;
vec.X *= mult;
vec.Y *= mult;
vec.Z *= mult;
vec.W *= mult;
return vec;
}
/// <summary>
/// Compares two instances for equality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left equals right; false otherwise.</returns>
public static bool operator ==(Vector4d left, Vector4d right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two instances for inequality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left does not equa lright; false otherwise.</returns>
public static bool operator !=(Vector4d left, Vector4d right)
{
return !left.Equals(right);
}
/// <summary>
/// Returns a pointer to the first element of the specified instance.
/// </summary>
/// <param name="v">The instance.</param>
/// <returns>A pointer to the first element of v.</returns>
[CLSCompliant(false)]
unsafe public static explicit operator double*(Vector4d v)
{
return &v.X;
}
/// <summary>
/// Returns a pointer to the first element of the specified instance.
/// </summary>
/// <param name="v">The instance.</param>
/// <returns>A pointer to the first element of v.</returns>
public static explicit operator IntPtr(Vector4d v)
{
unsafe
{
return (IntPtr)(&v.X);
}
}
/// <summary>Converts OpenTK.Vector4 to OpenTK.Vector4d.</summary>
/// <param name="v4">The Vector4 to convert.</param>
/// <returns>The resulting Vector4d.</returns>
public static explicit operator Vector4d(Vector4 v4)
{
return new Vector4d(v4.X, v4.Y, v4.Z, v4.W);
}
/// <summary>Converts OpenTK.Vector4d to OpenTK.Vector4.</summary>
/// <param name="v4d">The Vector4d to convert.</param>
/// <returns>The resulting Vector4.</returns>
public static explicit operator Vector4(Vector4d v4d)
{
return new Vector4((float)v4d.X, (float)v4d.Y, (float)v4d.Z, (float)v4d.W);
}
#endregion
#region Overrides
#region public override string ToString()
/// <summary>
/// Returns a System.String that represents the current Vector4d.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("({0}, {1}, {2}, {3})", X, Y, Z, W);
}
#endregion
#region public override int GetHashCode()
/// <summary>
/// Returns the hashcode for this instance.
/// </summary>
/// <returns>A System.Int32 containing the unique hashcode for this instance.</returns>
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode();
}
#endregion
#region public override bool Equals(object obj)
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">The object to compare to.</param>
/// <returns>True if the instances are equal; false otherwise.</returns>
public override bool Equals(object obj)
{
if (!(obj is Vector4d))
return false;
return this.Equals((Vector4d)obj);
}
#endregion
#endregion
#endregion
#region IEquatable<Vector4d> Members
/// <summary>Indicates whether the current vector is equal to another vector.</summary>
/// <param name="other">A vector to compare with this vector.</param>
/// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns>
public bool Equals(Vector4d other)
{
return
X == other.X &&
Y == other.Y &&
Z == other.Z &&
W == other.W;
}
#endregion
}
}
// flibit Added This!!!
#pragma warning restore 3021
| |
//------------------------------------------------------------------------------
// <copyright file="ButtonBase.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Runtime.Serialization.Formatters;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Drawing.Imaging;
using System;
using System.Security.Permissions;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms.ButtonInternal;
using System.Windows.Forms.Layout;
using System.ComponentModel;
using Microsoft.Win32;
using System.Globalization;
using System.Runtime.Versioning;
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase"]/*' />
/// <devdoc>
/// <para>
/// Implements the basic functionality required by a button control.
/// </para>
/// </devdoc>
[
ComVisible(true),
ClassInterface(ClassInterfaceType.AutoDispatch),
Designer("System.Windows.Forms.Design.ButtonBaseDesigner, " + AssemblyRef.SystemDesign)
]
public abstract class ButtonBase : Control {
private FlatStyle flatStyle = System.Windows.Forms.FlatStyle.Standard;
private ContentAlignment imageAlign = ContentAlignment.MiddleCenter;
private ContentAlignment textAlign = ContentAlignment.MiddleCenter;
private TextImageRelation textImageRelation = TextImageRelation.Overlay;
private ImageList.Indexer imageIndex = new ImageList.Indexer();
private FlatButtonAppearance flatAppearance;
private ImageList imageList;
private Image image;
private const int FlagMouseOver = 0x0001;
private const int FlagMouseDown = 0x0002;
private const int FlagMousePressed = 0x0004;
private const int FlagInButtonUp = 0x0008;
private const int FlagCurrentlyAnimating = 0x0010;
private const int FlagAutoEllipsis = 0x0020;
private const int FlagIsDefault = 0x0040;
private const int FlagUseMnemonic = 0x0080;
private const int FlagShowToolTip = 0x0100;
private int state = 0;
private ToolTip textToolTip;
//this allows the user to disable visual styles for the button so that it inherits its background color
private bool enableVisualStyleBackground = true;
private bool isEnableVisualStyleBackgroundSet = false;
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.ButtonBase"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Windows.Forms.ButtonBase'/> class.
///
/// </para>
/// </devdoc>
protected ButtonBase() {
// If Button doesn't want double-clicks, we should introduce a StandardDoubleClick style.
// Checkboxes probably want double-click's (#26120), and RadioButtons certainly do
// (useful e.g. on a Wizard).
SetStyle( ControlStyles.SupportsTransparentBackColor |
ControlStyles.Opaque |
ControlStyles.ResizeRedraw |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.CacheText | // We gain about 2% in painting by avoiding extra GetWindowText calls
ControlStyles.StandardClick,
true);
// this class overrides GetPreferredSizeCore, let Control automatically cache the result
SetState2(STATE2_USEPREFERREDSIZECACHE, true);
SetStyle(ControlStyles.UserMouse |
ControlStyles.UserPaint, OwnerDraw);
SetFlag(FlagUseMnemonic, true);
SetFlag(FlagShowToolTip, false);
}
/// <devdoc>
/// <para> This property controls the activation handling of bleedover for the text that
/// extends beyond the width of the button. </para>
/// </devdoc>
[
SRCategory(SR.CatBehavior),
DefaultValue(false),
Browsable(true),
EditorBrowsable(EditorBrowsableState.Always),
SRDescription(SR.ButtonAutoEllipsisDescr)
]
public bool AutoEllipsis {
get {
return GetFlag(FlagAutoEllipsis);
}
set {
if (AutoEllipsis != value) {
SetFlag(FlagAutoEllipsis, value);
if (value) {
if (textToolTip == null) {
textToolTip = new ToolTip();
}
}
Invalidate();
}
}
}
/// <devdoc>
/// Indicates whether the control is automatically resized to fit its contents
/// </devdoc>
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always),
DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override bool AutoSize {
get {
return base.AutoSize;
}
set {
base.AutoSize = value;
//don't show ellipsis if the control is autosized
if (value) {
AutoEllipsis = false;
}
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.AutoSizeChanged"]/*' />
[SRCategory(SR.CatPropertyChanged), SRDescription(SR.ControlOnAutoSizeChangedDescr)]
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
new public event EventHandler AutoSizeChanged
{
add
{
base.AutoSizeChanged += value;
}
remove
{
base.AutoSizeChanged -= value;
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.BackColor"]/*' />
/// <devdoc>
/// The background color of this control. This is an ambient property and
/// will always return a non-null value.
/// </devdoc>
[
SRCategory(SR.CatAppearance),
SRDescription(SR.ControlBackColorDescr)
]
public override Color BackColor {
get {
return base.BackColor;
}
set {
if (DesignMode) {
if (value != Color.Empty) {
PropertyDescriptor pd = TypeDescriptor.GetProperties(this)["UseVisualStyleBackColor"];
Debug.Assert(pd != null);
if (pd != null) {
pd.SetValue(this, false);
}
}
}
else {
UseVisualStyleBackColor = false;
}
base.BackColor = value;
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.DefaultSize"]/*' />
/// <devdoc>
/// Deriving classes can override this to configure a default size for their control.
/// This is more efficient than setting the size in the control's constructor.
/// </devdoc>
protected override Size DefaultSize {
get {
return new Size(75, 23);
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.CreateParams"]/*' />
protected override CreateParams CreateParams {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
CreateParams cp = base.CreateParams;
if (!OwnerDraw) {
cp.ExStyle &= ~NativeMethods.WS_EX_RIGHT; // WS_EX_RIGHT overrides the BS_XXXX alignment styles
cp.Style |= NativeMethods.BS_MULTILINE;
if (IsDefault) {
cp.Style |= NativeMethods.BS_DEFPUSHBUTTON;
}
ContentAlignment align = RtlTranslateContent(TextAlign);
if ((int)(align & WindowsFormsUtils.AnyLeftAlign) != 0) {
cp.Style |= NativeMethods.BS_LEFT;
}
else if ((int)(align & WindowsFormsUtils.AnyRightAlign) != 0) {
cp.Style |= NativeMethods.BS_RIGHT;
}
else {
cp.Style |= NativeMethods.BS_CENTER;
}
if ((int)(align & WindowsFormsUtils.AnyTopAlign) != 0) {
cp.Style |= NativeMethods.BS_TOP;
}
else if ((int)(align & WindowsFormsUtils.AnyBottomAlign) != 0) {
cp.Style |= NativeMethods.BS_BOTTOM;
}
else {
cp.Style |= NativeMethods.BS_VCENTER;
}
}
return cp;
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.DefaultImeMode"]/*' />
protected override ImeMode DefaultImeMode {
get {
return ImeMode.Disable;
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.IsDefault"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected internal bool IsDefault {
get {
return GetFlag(FlagIsDefault);
}
set {
if (GetFlag(FlagIsDefault) != value) {
SetFlag(FlagIsDefault, value);
if (IsHandleCreated) {
if (OwnerDraw) {
Invalidate();
}
else {
UpdateStyles();
}
}
}
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.FlatStyle"]/*' />
/// <devdoc>
/// <para>
/// Gets or
/// sets
/// the flat style appearance of the button control.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatAppearance),
DefaultValue(FlatStyle.Standard),
Localizable(true),
SRDescription(SR.ButtonFlatStyleDescr)
]
public FlatStyle FlatStyle {
get {
return flatStyle;
}
set {
if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System)){
throw new InvalidEnumArgumentException("value", (int)value, typeof(FlatStyle));
}
flatStyle = value;
LayoutTransaction.DoLayoutIf(AutoSize,ParentInternal, this, PropertyNames.FlatStyle);
Invalidate();
UpdateOwnerDraw();
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.FlatAppearance"]/*' />
/// <devdoc>
/// </devdoc>
[
Browsable(true),
SRCategory(SR.CatAppearance),
SRDescription(SR.ButtonFlatAppearance),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
]
public FlatButtonAppearance FlatAppearance {
get {
if (flatAppearance == null) {
flatAppearance = new FlatButtonAppearance(this);
}
return flatAppearance;
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.Image"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the image
/// that is displayed on a button control.
/// </para>
/// </devdoc>
[
SRDescription(SR.ButtonImageDescr),
Localizable(true),
SRCategory(SR.CatAppearance)
]
public Image Image {
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
get {
if (image == null && imageList != null) {
int actualIndex = imageIndex.ActualIndex;
// Pre-whidbey we used to use ImageIndex rather than ImageIndexer.ActualIndex.
// ImageIndex clamps to the length of the image list. We need to replicate
// this logic here for backwards compatibility. (VSWhidbey #95780)
// Per [....] we do not bake this into ImageIndexer because different controls
// treat this scenario differently.
if(actualIndex >= imageList.Images.Count) {
actualIndex = imageList.Images.Count - 1;
}
if (actualIndex >= 0) {
return imageList.Images[actualIndex];
}
Debug.Assert(image == null, "We expect to be returning null.");
}
return image;
}
set {
if (Image != value) {
StopAnimate();
image = value;
if (image != null) {
ImageIndex = -1;
ImageList = null;
}
LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.Image);
Animate();
Invalidate();
}
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.ImageAlign"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the alignment of the image on the button control.
/// </para>
/// </devdoc>
[
DefaultValue(ContentAlignment.MiddleCenter),
Localizable(true),
SRDescription(SR.ButtonImageAlignDescr),
SRCategory(SR.CatAppearance)
]
public ContentAlignment ImageAlign {
get {
return imageAlign;
}
set {
if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) {
throw new InvalidEnumArgumentException("value", (int)value, typeof(ContentAlignment));
}
if(value != imageAlign) {
imageAlign = value;
LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.ImageAlign);
Invalidate();
}
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.ImageIndex"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the image list index value of the image
/// displayed on the button control.
/// </para>
/// </devdoc>
[
TypeConverterAttribute(typeof(ImageIndexConverter)),
Editor("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
Localizable(true),
DefaultValue(-1),
RefreshProperties(RefreshProperties.Repaint),
SRDescription(SR.ButtonImageIndexDescr),
SRCategory(SR.CatAppearance)
]
public int ImageIndex {
get {
if (imageIndex.Index != -1 && imageList != null && imageIndex.Index >= imageList.Images.Count) {
return imageList.Images.Count - 1;
}
return imageIndex.Index;
}
set {
if (value < -1) {
throw new ArgumentOutOfRangeException("ImageIndex", SR.GetString(SR.InvalidLowBoundArgumentEx, "ImageIndex", (value).ToString(CultureInfo.CurrentCulture), (-1).ToString(CultureInfo.CurrentCulture)));
}
if (imageIndex.Index != value) {
if (value != -1) {
// Image.set calls ImageIndex = -1
image = null;
}
// If they were previously using keys - this should clear out the image key field.
imageIndex.Index = value;
Invalidate();
}
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.ImageKey"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the image list index key of the image
/// displayed on the button control. Note - setting this unsets the ImageIndex
/// </para>
/// </devdoc>
[
TypeConverterAttribute(typeof(ImageKeyConverter)),
Editor("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
Localizable(true),
DefaultValue(""),
RefreshProperties(RefreshProperties.Repaint),
SRDescription(SR.ButtonImageIndexDescr),
SRCategory(SR.CatAppearance)
]
public string ImageKey {
get {
return imageIndex.Key;
}
set {
if (imageIndex.Key != value) {
if (value != null) {
// Image.set calls ImageIndex = -1
image = null;
}
// If they were previously using indexes - this should clear out the image index field.
imageIndex.Key = value;
Invalidate();
}
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.ImageList"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the <see cref='System.Windows.Forms.ImageList'/> that contains the <see cref='System.Drawing.Image'/> displayed on a button control.
/// </para>
/// </devdoc>
[
DefaultValue(null),
SRDescription(SR.ButtonImageListDescr),
RefreshProperties(RefreshProperties.Repaint),
SRCategory(SR.CatAppearance)
]
public ImageList ImageList {
get {
return imageList;
}
set {
if (imageList != value) {
EventHandler recreateHandler = new EventHandler(ImageListRecreateHandle);
EventHandler disposedHandler = new EventHandler(DetachImageList);
// Detach old event handlers
//
if (imageList != null) {
imageList.RecreateHandle -= recreateHandler;
imageList.Disposed -= disposedHandler;
}
// Make sure we don't have an Image as well as an ImageList
//
if (value != null) {
image = null; // Image.set calls ImageList = null
}
imageList = value;
imageIndex.ImageList = value;
// Wire up new event handlers
//
if (value != null) {
value.RecreateHandle += recreateHandler;
value.Disposed += disposedHandler;
}
Invalidate();
}
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.ImeMode"]/*' />
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public ImeMode ImeMode {
get {
return base.ImeMode;
}
set {
base.ImeMode = value;
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.ImeModeChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler ImeModeChanged {
add {
base.ImeModeChanged += value;
}
remove {
base.ImeModeChanged -= value;
}
}
/// <devdoc>
/// Specifies whether the control is willing to process mnemonics when hosted in an container ActiveX (Ax Sourcing).
/// </devdoc>
internal override bool IsMnemonicsListenerAxSourced
{
get{
return true;
}
}
/// <devdoc>
/// <para>
/// The area of the button encompassing any changes between the button's
/// resting appearance and its appearance when the mouse is over it.
/// </para>
/// <para>
/// Consider overriding this property if you override any painting methods,
/// or your button may not paint correctly or may have flicker. Returning
/// ClientRectangle is safe for correct painting but may still cause flicker.
/// </para>
/// </devdoc>
internal virtual Rectangle OverChangeRectangle {
get {
if (FlatStyle == FlatStyle.Standard) {
// this Rectangle will cause no Invalidation
// can't use Rectangle.Empty because it will cause Invalidate(ClientRectangle)
return new Rectangle(-1, -1, 1, 1);
}
else {
return ClientRectangle;
}
}
}
internal bool OwnerDraw {
get {
return FlatStyle != FlatStyle.System;
}
}
/// <devdoc>
/// <para>
/// The area of the button encompassing any changes between the button's
/// appearance when the mouse is over it but not pressed and when it is pressed.
/// </para>
/// <para>
/// Consider overriding this property if you override any painting methods,
/// or your button may not paint correctly or may have flicker. Returning
/// ClientRectangle is safe for correct painting but may still cause flicker.
/// </para>
/// </devdoc>
internal virtual Rectangle DownChangeRectangle {
get {
return ClientRectangle;
}
}
internal bool MouseIsPressed {
get {
return GetFlag(FlagMousePressed);
}
}
// a "smart" version of mouseDown for Appearance.Button CheckBoxes & RadioButtons
// for these, instead of being based on the actual mouse state, it's based on the appropriate button state
internal bool MouseIsDown {
get {
return GetFlag(FlagMouseDown);
}
}
// a "smart" version of mouseOver for Appearance.Button CheckBoxes & RadioButtons
// for these, instead of being based on the actual mouse state, it's based on the appropriate button state
internal bool MouseIsOver {
get {
return GetFlag(FlagMouseOver);
}
}
/// <devdoc>
/// Indicates whether the tooltip should be shown
/// </devdoc>
internal bool ShowToolTip {
get {
return GetFlag(FlagShowToolTip);
}
set {
SetFlag(FlagShowToolTip, value);
}
}
[
Editor("System.ComponentModel.Design.MultilineStringEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
SettingsBindable(true)
]
public override string Text {
get {
return base.Text;
}
set {
base.Text = value;
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.TextAlign"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the alignment of the text on the button control.
/// </para>
/// </devdoc>
[
DefaultValue(ContentAlignment.MiddleCenter),
Localizable(true),
SRDescription(SR.ButtonTextAlignDescr),
SRCategory(SR.CatAppearance)
]
public virtual ContentAlignment TextAlign {
get {
return textAlign;
}
set {
if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) {
throw new InvalidEnumArgumentException("value", (int)value, typeof(ContentAlignment));
}
if(value != textAlign) {
textAlign = value;
LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.TextAlign);
if (OwnerDraw) {
Invalidate();
}
else {
UpdateStyles();
}
}
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.TextImageRelation"]/*' />
[DefaultValue(TextImageRelation.Overlay),
Localizable(true),
SRDescription(SR.ButtonTextImageRelationDescr),
SRCategory(SR.CatAppearance)]
public TextImageRelation TextImageRelation {
get {
return textImageRelation;
}
set {
if (!WindowsFormsUtils.EnumValidator.IsValidTextImageRelation(value)) {
throw new InvalidEnumArgumentException("value", (int)value, typeof(TextImageRelation));
}
if(value != TextImageRelation) {
textImageRelation = value;
LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.TextImageRelation);
Invalidate();
}
}
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether an ampersand (&) included in the text of
/// the control.</para>
/// </devdoc>
[
SRDescription(SR.ButtonUseMnemonicDescr),
DefaultValue(true),
SRCategory(SR.CatAppearance)
]
public bool UseMnemonic {
get {
return GetFlag(FlagUseMnemonic);
}
set {
SetFlag(FlagUseMnemonic, value);
LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.Text);
Invalidate();
}
}
private void Animate() {
Animate(!DesignMode && Visible && Enabled && ParentInternal != null);
}
private void StopAnimate() {
Animate(false);
}
private void Animate(bool animate) {
if (animate != GetFlag(FlagCurrentlyAnimating)) {
if (animate) {
if (this.image != null) {
ImageAnimator.Animate(this.image, new EventHandler(this.OnFrameChanged));
SetFlag(FlagCurrentlyAnimating, animate);
}
}
else {
if (this.image != null) {
ImageAnimator.StopAnimate(this.image, new EventHandler(this.OnFrameChanged));
SetFlag(FlagCurrentlyAnimating, animate);
}
}
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.CreateAccessibilityInstance"]/*' />
protected override AccessibleObject CreateAccessibilityInstance() {
return new ButtonBaseAccessibleObject(this);
}
private void DetachImageList(object sender, EventArgs e) {
ImageList = null;
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.Dispose"]/*' />
/// <devdoc>
/// </devdoc>
/// <internalonly/>
protected override void Dispose(bool disposing) {
if (disposing) {
StopAnimate();
if (imageList != null) {
imageList.Disposed -= new EventHandler(this.DetachImageList);
}
//Dipose the tooltip if one present..
if (textToolTip != null) {
textToolTip.Dispose();
textToolTip = null;
}
}
base.Dispose(disposing);
}
private bool GetFlag(int flag) {
return ((state & flag) == flag);
}
private void ImageListRecreateHandle(object sender, EventArgs e) {
if (IsHandleCreated) {
Invalidate();
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnGotFocus"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.ButtonBase.OnGotFocus'/> event.
/// </para>
/// </devdoc>
protected override void OnGotFocus(EventArgs e) {
base.OnGotFocus(e);
Invalidate();
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnLostFocus"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.ButtonBase.OnLostFocus'/> event.
/// </para>
/// </devdoc>
protected override void OnLostFocus(EventArgs e) {
base.OnLostFocus(e);
// Hitting tab while holding down the space key. See ASURT 38669.
SetFlag(FlagMouseDown, false);
CaptureInternal = false;
Invalidate();
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnMouseEnter"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.Control.OnMouseEnter'/> event.
/// </para>
/// </devdoc>
protected override void OnMouseEnter(EventArgs eventargs) {
Debug.Assert(Enabled, "ButtonBase.OnMouseEnter should not be called if the button is disabled");
SetFlag(FlagMouseOver, true);
Invalidate();
if (!DesignMode && AutoEllipsis && ShowToolTip && textToolTip != null) {
// SECREVIEW: VSWhidbey 531915 - ToolTip should show in internet zone
IntSecurity.AllWindows.Assert();
try {
textToolTip.Show(WindowsFormsUtils.TextWithoutMnemonics(Text), this);
}
finally {
System.Security.CodeAccessPermission.RevertAssert();
}
}
// call base last, so if it invokes any listeners that disable the button, we
// don't have to recheck
base.OnMouseEnter(eventargs);
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnMouseLeave"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.Control.OnMouseLeave'/> event.
/// </para>
/// </devdoc>
protected override void OnMouseLeave(EventArgs eventargs) {
SetFlag(FlagMouseOver, false);
if (textToolTip != null) {
// SECREVIEW: VSWhidbey 531915 - ToolTip should show in internet zone
IntSecurity.AllWindows.Assert();
try {
textToolTip.Hide(this);
}
finally {
System.Security.CodeAccessPermission.RevertAssert();
}
}
Invalidate();
// call base last, so if it invokes any listeners that disable the button, we
// don't have to recheck
base.OnMouseLeave(eventargs);
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnMouseMove"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.Control.OnMouseMove'/> event.
/// </para>
/// </devdoc>
protected override void OnMouseMove(MouseEventArgs mevent) {
Debug.Assert(Enabled, "ButtonBase.OnMouseMove should not be called if the button is disabled");
if (mevent.Button != MouseButtons.None && GetFlag(FlagMousePressed)) {
Rectangle r = ClientRectangle;
if (!r.Contains(mevent.X, mevent.Y)) {
if (GetFlag(FlagMouseDown)) {
SetFlag(FlagMouseDown, false);
Invalidate(DownChangeRectangle);
}
}
else {
if (!GetFlag(FlagMouseDown)) {
SetFlag(FlagMouseDown, true);
Invalidate(DownChangeRectangle);
}
}
}
// call base last, so if it invokes any listeners that disable the button, we
// don't have to recheck
base.OnMouseMove(mevent);
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnMouseDown"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.Control.OnMouseDown'/> event.
/// </para>
/// </devdoc>
protected override void OnMouseDown(MouseEventArgs mevent) {
Debug.Assert(Enabled, "ButtonBase.OnMouseDown should not be called if the button is disabled");
if (mevent.Button == MouseButtons.Left) {
SetFlag(FlagMouseDown, true);
SetFlag(FlagMousePressed, true);
Invalidate(DownChangeRectangle);
}
// call base last, so if it invokes any listeners that disable the button, we
// don't have to recheck
base.OnMouseDown(mevent);
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnMouseUp"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.ButtonBase.OnMouseUp'/> event.
///
/// </para>
/// </devdoc>
protected override void OnMouseUp(MouseEventArgs mevent) {
base.OnMouseUp(mevent);
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.ResetFlagsandPaint"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Used for quick re-painting of the button after the pressed state.
/// </para>
/// </devdoc>
protected void ResetFlagsandPaint() {
SetFlag(FlagMousePressed, false);
SetFlag(FlagMouseDown, false);
Invalidate(DownChangeRectangle);
Update();
}
/// <devdoc>
/// Central paint dispatcher to one of the three styles of painting.
/// </devdoc>
private void PaintControl(PaintEventArgs pevent) {
Debug.Assert(GetStyle(ControlStyles.UserPaint), "Shouldn't be in PaintControl when control is not UserPaint style");
Adapter.Paint(pevent);
}
public override Size GetPreferredSize( Size proposedSize ) {
// TableLayoutPanel passes width = 1 to get the minimum autosize width, since Buttons word-break text
// that width would be the size of the widest caracter in the text. We need to make the proposed size
// unbounded.
// This is the same as what Label does.
if( proposedSize.Width == 1 ) {
proposedSize.Width = 0;
}
if( proposedSize.Height == 1 ) {
proposedSize.Height = 0;
}
return base.GetPreferredSize( proposedSize );
}
internal override Size GetPreferredSizeCore(Size proposedConstraints) {
Size prefSize = Adapter.GetPreferredSizeCore(proposedConstraints);
return LayoutUtils.UnionSizes(prefSize + Padding.Size, MinimumSize);
}
private ButtonBaseAdapter _adapter = null;
private FlatStyle _cachedAdapterType;
internal ButtonBaseAdapter Adapter {
get {
if(_adapter == null || FlatStyle != _cachedAdapterType) {
switch (FlatStyle) {
case FlatStyle.Standard:
_adapter = CreateStandardAdapter();
break;
case FlatStyle.Popup:
_adapter = CreatePopupAdapter();
break;
case FlatStyle.Flat:
_adapter = CreateFlatAdapter();;
break;
default:
Debug.Fail("Unsupported FlatStyle: '" + FlatStyle + '"');
break;
}
_cachedAdapterType = FlatStyle;
}
return _adapter;
}
}
internal virtual ButtonBaseAdapter CreateFlatAdapter() {
Debug.Fail("Derived classes need to provide a meaningful implementation.");
return null;
}
internal virtual ButtonBaseAdapter CreatePopupAdapter() {
Debug.Fail("Derived classes need to provide a meaningful implementation.");
return null;
}
internal virtual ButtonBaseAdapter CreateStandardAdapter() {
Debug.Fail("Derived classes need to provide a meaningful implementation.");
return null;
}
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
internal virtual StringFormat CreateStringFormat() {
if( Adapter == null ) {
Debug.Fail("Adapter not expected to be null at this point");
return new StringFormat();
}
return Adapter.CreateStringFormat();
}
internal virtual TextFormatFlags CreateTextFormatFlags() {
if( Adapter == null ) {
Debug.Fail( "Adapter not expected to be null at this point" );
return TextFormatFlags.Default;
}
return Adapter.CreateTextFormatFlags();
}
private void OnFrameChanged(object o, EventArgs e) {
if (Disposing || IsDisposed) {
return;
}
if (IsHandleCreated && InvokeRequired) {
BeginInvoke(new EventHandler(this.OnFrameChanged), new object[]{o,e});
return;
}
Invalidate();
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnEnabledChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void OnEnabledChanged(EventArgs e) {
base.OnEnabledChanged(e);
Animate();
if (!Enabled) {
// disabled button is always "up"
SetFlag(FlagMouseDown, false);
SetFlag(FlagMouseOver, false);
Invalidate();
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnTextChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void OnTextChanged(EventArgs e) {
using(LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.Text)) {
base.OnTextChanged(e);
Invalidate();
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnKeyDown"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.ButtonBase.OnKeyDown'/> event.
///
/// </para>
/// </devdoc>
protected override void OnKeyDown(KeyEventArgs kevent) {
Debug.Assert(Enabled, "ButtonBase.OnKeyDown should not be called if the button is disabled");
if (kevent.KeyData == Keys.Space) {
if (!GetFlag(FlagMouseDown)) {
SetFlag(FlagMouseDown, true);
// It looks like none of the "SPACE" key downs generate the BM_SETSTATE.
// This causes to not draw the focus rectangle inside the button and also
// not paint the button as "un-depressed".
//
if(!OwnerDraw) {
SendMessage(NativeMethods.BM_SETSTATE, 1, 0);
}
Invalidate(DownChangeRectangle);
}
kevent.Handled = true;
}
// call base last, so if it invokes any listeners that disable the button, we
// don't have to recheck
base.OnKeyDown(kevent);
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnKeyUp"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.ButtonBase.OnKeyUp'/> event.
///
/// </para>
/// </devdoc>
protected override void OnKeyUp(KeyEventArgs kevent) {
if (GetFlag(FlagMouseDown) && !ValidationCancelled) {
if (OwnerDraw) {
ResetFlagsandPaint();
}
else {
SetFlag(FlagMousePressed, false);
SetFlag(FlagMouseDown, false);
SendMessage(NativeMethods.BM_SETSTATE, 0, 0);
}
// VSWhidbey 498398: Breaking change: specifically filter out Keys.Enter and Keys.Space as the only
// two keystrokes to execute OnClick.
if (kevent.KeyCode == Keys.Enter || kevent.KeyCode == Keys.Space) {
OnClick(EventArgs.Empty);
}
kevent.Handled = true;
}
// call base last, so if it invokes any listeners that disable the button, we
// don't have to recheck
base.OnKeyUp(kevent);
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnPaint"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.ButtonBase.OnPaint'/> event.
///
/// </para>
/// </devdoc>
protected override void OnPaint(PaintEventArgs pevent) {
if( AutoEllipsis ){
Size preferredSize = PreferredSize;
ShowToolTip = (this.ClientRectangle.Width < preferredSize.Width || this.ClientRectangle.Height < preferredSize.Height);
}
else {
ShowToolTip = false;
}
if (GetStyle(ControlStyles.UserPaint)) {
Animate();
ImageAnimator.UpdateFrames(this.Image);
PaintControl(pevent);
}
base.OnPaint(pevent);
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnParentChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void OnParentChanged(EventArgs e) {
base.OnParentChanged(e);
Animate();
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.OnVisibleChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void OnVisibleChanged(EventArgs e) {
base.OnVisibleChanged(e);
Animate();
}
private void ResetImage() {
Image = null;
}
private void SetFlag(int flag, bool value) {
bool oldValue = ((state & flag) != 0);
if (value) {
state |= flag;
}
else {
state &= ~flag;
}
if (OwnerDraw && (flag & FlagMouseDown) != 0 && value != oldValue) {
AccessibilityNotifyClients(AccessibleEvents.StateChange, -1);
}
}
private bool ShouldSerializeImage() {
return image != null;
}
private void UpdateOwnerDraw() {
if (OwnerDraw != GetStyle(ControlStyles.UserPaint)) {
SetStyle(ControlStyles.UserMouse | ControlStyles.UserPaint, OwnerDraw);
RecreateHandle();
}
}
/// <devdoc>
/// Determines whether to use compatible text rendering engine (GDI+) or not (GDI).
/// </devdoc>
[
DefaultValue(false),
SRCategory(SR.CatBehavior),
SRDescription(SR.UseCompatibleTextRenderingDescr)
]
public bool UseCompatibleTextRendering {
get{
return base.UseCompatibleTextRenderingInt;
}
set{
base.UseCompatibleTextRenderingInt = value;
}
}
/// <devdoc>
/// Determines whether the control supports rendering text using GDI+ and GDI.
/// This is provided for container controls to iterate through its children to set UseCompatibleTextRendering to the same
/// value if the child control supports it.
/// </devdoc>
internal override bool SupportsUseCompatibleTextRendering {
get {
return true;
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.UseVisualStyleBackColor"]/*' />
/// <internalonly/>
[
SRCategory(SR.CatAppearance),
SRDescription(SR.ButtonUseVisualStyleBackColorDescr)
]
public bool UseVisualStyleBackColor {
get {
if (isEnableVisualStyleBackgroundSet || ((RawBackColor.IsEmpty) && (BackColor == SystemColors.Control)))
{
return enableVisualStyleBackground;
}
else
{
return false;
}
}
set {
isEnableVisualStyleBackgroundSet = true;
enableVisualStyleBackground = value;
this.Invalidate();
}
}
private void ResetUseVisualStyleBackColor() {
isEnableVisualStyleBackgroundSet = false;
enableVisualStyleBackground = true;
this.Invalidate();
}
private bool ShouldSerializeUseVisualStyleBackColor() {
return isEnableVisualStyleBackgroundSet;
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBase.WndProc"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m) {
switch (m.Msg) {
// NDPWhidbey 28043 -- we don't respect this because the code below eats BM_SETSTATE.
// so we just invoke the click.
//
case NativeMethods.BM_CLICK:
if (this is IButtonControl) {
((IButtonControl)this).PerformClick();
}
else {
OnClick(EventArgs.Empty);
}
return;
}
if (OwnerDraw) {
switch (m.Msg) {
case NativeMethods.BM_SETSTATE:
// Ignore BM_SETSTATE -- Windows gets confused and paints
// things, even though we are ownerdraw. See ASURT 38669.
break;
case NativeMethods.WM_KILLFOCUS:
case NativeMethods.WM_CANCELMODE:
case NativeMethods.WM_CAPTURECHANGED:
if (!GetFlag(FlagInButtonUp) && GetFlag(FlagMousePressed)) {
SetFlag(FlagMousePressed, false);
if (GetFlag(FlagMouseDown)) {
SetFlag(FlagMouseDown, false);
Invalidate(DownChangeRectangle);
}
}
base.WndProc(ref m);
break;
case NativeMethods.WM_LBUTTONUP:
case NativeMethods.WM_MBUTTONUP:
case NativeMethods.WM_RBUTTONUP:
try {
SetFlag(FlagInButtonUp, true);
base.WndProc(ref m);
}
finally {
SetFlag(FlagInButtonUp, false);
}
break;
default:
base.WndProc(ref m);
break;
}
}
else {
switch (m.Msg) {
case NativeMethods.WM_REFLECT + NativeMethods.WM_COMMAND:
if (NativeMethods.Util.HIWORD(m.WParam) == NativeMethods.BN_CLICKED && !ValidationCancelled) {
OnClick(EventArgs.Empty);
}
break;
default:
base.WndProc(ref m);
break;
}
}
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBaseAccessibleObject"]/*' />
/// <internalonly/>
[System.Runtime.InteropServices.ComVisible(true)]
public class ButtonBaseAccessibleObject : ControlAccessibleObject {
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBaseAccessibleObject.ButtonBaseAccessibleObject"]/*' />
public ButtonBaseAccessibleObject(Control owner) : base(owner) {
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBaseAccessibleObject.DoDefaultAction"]/*' />
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override void DoDefaultAction() {
((ButtonBase)Owner).OnClick(EventArgs.Empty);
}
/// <include file='doc\ButtonBase.uex' path='docs/doc[@for="ButtonBaseAccessibleObject.State"]/*' />
public override AccessibleStates State {
get {
AccessibleStates state = base.State;
ButtonBase owner = (ButtonBase) Owner;
if (owner.OwnerDraw && owner.MouseIsDown) {
state |= AccessibleStates.Pressed;
}
return state;
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="HashCodeCombiner.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* HashCodeCombiner class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web.Util {
using System.Text;
using System.IO;
using System.Globalization;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Web.Security.Cryptography;
/*
* Class used to combine several hashcodes into a single hashcode
*/
internal class HashCodeCombiner {
private long _combinedHash;
internal HashCodeCombiner() {
// Start with a seed (obtained from String.GetHashCode implementation)
_combinedHash = 5381;
}
internal HashCodeCombiner(long initialCombinedHash) {
_combinedHash = initialCombinedHash;
}
internal static int CombineHashCodes(int h1, int h2) {
return ((h1 << 5) + h1) ^ h2;
}
internal static int CombineHashCodes(int h1, int h2, int h3) {
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4) {
return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4));
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) {
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5);
}
internal static string GetDirectoryHash(VirtualPath virtualDir) {
HashCodeCombiner hashCodeCombiner = new HashCodeCombiner();
hashCodeCombiner.AddDirectory(virtualDir.MapPathInternal());
return hashCodeCombiner.CombinedHashString;
}
internal void AddArray(string[] a) {
if (a != null) {
int n = a.Length;
for (int i = 0; i < n; i++) {
AddObject(a[i]);
}
}
}
internal void AddInt(int n) {
_combinedHash = ((_combinedHash << 5) + _combinedHash) ^ n;
Debug.Trace("HashCodeCombiner", "Adding " + n.ToString("x") + " --> " + _combinedHash.ToString("x"));
}
internal void AddObject(int n) {
AddInt(n);
}
internal void AddObject(byte b) {
AddInt(b.GetHashCode());
}
internal void AddObject(long l) {
AddInt(l.GetHashCode());
}
internal void AddObject(bool b) {
AddInt(b.GetHashCode());
}
internal void AddObject(string s) {
if (s != null)
AddInt(StringUtil.GetStringHashCode(s));
}
internal void AddObject(Type t) {
if (t != null)
AddObject(System.Web.UI.Util.GetAssemblyQualifiedTypeName(t));
}
internal void AddObject(object o) {
if (o != null)
AddInt(o.GetHashCode());
}
internal void AddCaseInsensitiveString(string s) {
if (s != null)
AddInt((StringComparer.InvariantCultureIgnoreCase).GetHashCode(s));
}
internal void AddDateTime(DateTime dt) {
Debug.Trace("HashCodeCombiner", "Ticks: " + dt.Ticks.ToString("x", CultureInfo.InvariantCulture));
Debug.Trace("HashCodeCombiner", "Hashcode: " + dt.GetHashCode().ToString("x", CultureInfo.InvariantCulture));
AddInt(dt.GetHashCode());
}
private void AddFileSize(long fileSize) {
Debug.Trace("HashCodeCombiner", "file size: " + fileSize.ToString("x", CultureInfo.InvariantCulture));
Debug.Trace("HashCodeCombiner", "Hashcode: " + fileSize.GetHashCode().ToString("x", CultureInfo.InvariantCulture));
AddInt(fileSize.GetHashCode());
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This call site is trusted.")]
private void AddFileVersionInfo(FileVersionInfo fileVersionInfo) {
Debug.Trace("HashCodeCombiner", "FileMajorPart: " + fileVersionInfo.FileMajorPart.GetHashCode().ToString("x", CultureInfo.InvariantCulture));
Debug.Trace("HashCodeCombiner", "FileMinorPart: " + fileVersionInfo.FileMinorPart.GetHashCode().ToString("x", CultureInfo.InvariantCulture));
Debug.Trace("HashCodeCombiner", "FileBuildPart: " + fileVersionInfo.FileBuildPart.GetHashCode().ToString("x", CultureInfo.InvariantCulture));
Debug.Trace("HashCodeCombiner", "FilePrivatePart: " + fileVersionInfo.FilePrivatePart.GetHashCode().ToString("x", CultureInfo.InvariantCulture));
AddInt(fileVersionInfo.FileMajorPart.GetHashCode());
AddInt(fileVersionInfo.FileMinorPart.GetHashCode());
AddInt(fileVersionInfo.FileBuildPart.GetHashCode());
AddInt(fileVersionInfo.FilePrivatePart.GetHashCode());
}
private void AddFileContentHashKey(string fileContentHashKey) {
AddInt(fileContentHashKey.GetHashCode());
}
internal void AddFileContentHash(string fileName) {
// Convert file content to hash bytes
byte[] fileContentBytes = File.ReadAllBytes(fileName);
byte[] fileContentHashBytes = CryptoUtil.ComputeSHA256Hash(fileContentBytes);
// Convert byte[] to hex string representation
StringBuilder sbFileContentHashBytes = new StringBuilder();
for (int index = 0; index < fileContentHashBytes.Length; index++) {
sbFileContentHashBytes.Append(fileContentHashBytes[index].ToString("X2", CultureInfo.InvariantCulture));
}
AddFileContentHashKey(sbFileContentHashBytes.ToString());
}
internal void AddFile(string fileName) {
Debug.Trace("HashCodeCombiner", "AddFile: " + fileName);
if (!FileUtil.FileExists(fileName)) {
// Review: Should we change the dependency model to take directory into account?
if (FileUtil.DirectoryExists(fileName)) {
// Add as a directory dependency if it's a directory.
AddDirectory(fileName);
return;
}
Debug.Trace("HashCodeCombiner", "Could not find target " + fileName);
return;
}
AddExistingFile(fileName);
}
// Same as AddFile, but only called for a file which is known to exist
private void AddExistingFile(string fileName) {
Debug.Trace("HashCodeCombiner", "AddExistingFile: " + fileName);
AddInt(StringUtil.GetStringHashCode(fileName));
FileInfo file = new FileInfo(fileName);
if (!AppSettings.PortableCompilationOutput) {
AddDateTime(file.CreationTimeUtc);
}
AddDateTime(file.LastWriteTimeUtc);
AddFileSize(file.Length);
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This call site is trusted.")]
internal void AddExistingFileVersion(string fileName) {
Debug.Trace("HashCodeCombiner", "AddExistingFileVersion: " + fileName);
AddInt(StringUtil.GetStringHashCode(fileName));
FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(fileName);
AddFileVersionInfo(fileVersionInfo);
}
internal void AddDirectory(string directoryName) {
DirectoryInfo directory = new DirectoryInfo(directoryName);
if (!directory.Exists) {
return;
}
AddObject(directoryName);
// Go through all the files in the directory
foreach (FileData fileData in FileEnumerator.Create(directoryName)) {
if (fileData.IsDirectory)
AddDirectory(fileData.FullName);
else
AddExistingFile(fileData.FullName);
}
if (!AppSettings.PortableCompilationOutput) {
AddDateTime(directory.CreationTimeUtc);
AddDateTime(directory.LastWriteTimeUtc);
}
}
// Same as AddDirectory, but only look at files that don't have a culture
internal void AddResourcesDirectory(string directoryName) {
DirectoryInfo directory = new DirectoryInfo(directoryName);
if (!directory.Exists) {
return;
}
AddObject(directoryName);
// Go through all the files in the directory
foreach (FileData fileData in FileEnumerator.Create(directoryName)) {
if (fileData.IsDirectory)
AddResourcesDirectory(fileData.FullName);
else {
// Ignore the file if it has a culture, since only neutral files
// need to re-trigger compilation (VSWhidbey 359029)
string fullPath = fileData.FullName;
if (System.Web.UI.Util.GetCultureName(fullPath) == null) {
AddExistingFile(fullPath);
}
}
}
if (!AppSettings.PortableCompilationOutput) {
AddDateTime(directory.CreationTimeUtc);
}
}
internal long CombinedHash { get { return _combinedHash; } }
internal int CombinedHash32 { get { return _combinedHash.GetHashCode(); } }
internal string CombinedHashString {
get {
return _combinedHash.ToString("x", CultureInfo.InvariantCulture);
}
}
}
}
| |
using DirtyMagic.Exceptions;
using DirtyMagic.Processes;
using DirtyMagic.WinAPI;
using DirtyMagic.WinAPI.Structures;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace DirtyMagic
{
public static class ProcessHelpers
{
/// <summary>
/// Use this as alternative to builtin Process.GetProcesses() in
/// order not to deal with exceptions
/// </summary>
/// <returns></returns>
public static IEnumerable<RemoteProcess> EnumerateProcesses()
{
const uint arraySize = 1024u;
var arrayBytesSize = arraySize * sizeof(uint);
var processIds = new int[arraySize];
if (!Psapi.EnumProcesses(processIds, arrayBytesSize, out var bytesCopied))
yield break;
if (bytesCopied == 0)
yield break;
if ((bytesCopied & 3) != 0)
yield break;
var numIdsCopied = bytesCopied >> 2;
for (var i = 0; i < numIdsCopied; ++i)
{
var id = processIds[i];
var handle = Kernel32.OpenProcess(ProcessAccess.QueryInformation, false, id);
if (handle == IntPtr.Zero)
continue;
Kernel32.CloseHandle(handle);
Process process = null;
try
{
process = Process.GetProcessById(id);
if (process == null)
continue;
}
catch (Exception)
{
continue;
}
yield return new RemoteProcess(process);
}
}
public static RemoteProcess FindProcessById(int processId)
{
Process process;
try
{
process = Process.GetProcessById(processId);
}
catch (Exception)
{
return null;
}
if (!Kernel32.Is32BitProcess(process.Handle))
throw new MagicException("Can't operate with x64 processes");
return new RemoteProcess(process);
}
#region String parameters methods
public static IEnumerable<RemoteProcess> FindProcessesByInternalName(string name)
=> FindProcessesByInternalName(new Regex(Regex.Escape(name), RegexOptions.IgnoreCase));
public static IEnumerable<RemoteProcess> FindProcessesByProductName(string name)
=> FindProcessesByProductName(new Regex(Regex.Escape(name), RegexOptions.IgnoreCase));
public static IEnumerable<RemoteProcess> FindProcessesByName(string name)
=> FindProcessesByName(new Regex(Regex.Escape(name), RegexOptions.IgnoreCase));
public static RemoteProcess FindProcessByName(string name)
=> FindProcessByName(new Regex(Regex.Escape(name), RegexOptions.IgnoreCase));
public static RemoteProcess FindProcessByInternalName(string name)
=> FindProcessByInternalName(new Regex(Regex.Escape(name), RegexOptions.IgnoreCase));
public static RemoteProcess FindProcessByProductName(string name)
=> FindProcessByProductName(new Regex(Regex.Escape(name), RegexOptions.IgnoreCase));
public static RemoteProcess SelectProcess(string name)
=> SelectProcess(new Regex(Regex.Escape(name), RegexOptions.IgnoreCase));
#endregion
public static IEnumerable<RemoteProcess> FindProcessesByInternalName(Regex pattern)
{
return EnumerateProcesses().Where(process =>
{
try
{
return process.IsValid && Kernel32.Is32BitProcess(process.Handle) &&
process.MainModule.FileVersionInfo.InternalName != null &&
pattern.IsMatch(process.MainModule.FileVersionInfo.InternalName);
}
catch (Win32Exception)
{
return false;
}
});
}
public static IEnumerable<RemoteProcess> FindProcessesByProductName(Regex pattern)
{
return EnumerateProcesses().Where(process =>
{
return process.IsValid && Kernel32.Is32BitProcess(process.Handle) &&
process.MainModule.FileVersionInfo.ProductName != null &&
pattern.IsMatch(process.MainModule.FileVersionInfo.ProductName);
});
}
public static IEnumerable<RemoteProcess> FindProcessesByName(Regex pattern)
{
return EnumerateProcesses().Where(process =>
{
return process.IsValid && Kernel32.Is32BitProcess(process.Handle) &&
pattern.IsMatch(process.Name);
});
}
public static RemoteProcess FindProcessByName(Regex pattern)
=> FindProcessesByName(pattern).FirstOrDefault();
public static RemoteProcess FindProcessByInternalName(Regex pattern)
=> FindProcessesByInternalName(pattern).FirstOrDefault();
public static RemoteProcess FindProcessByProductName(Regex pattern)
=> FindProcessesByProductName(pattern).FirstOrDefault();
public static RemoteProcess SelectProcess(Regex pattern)
{
for (; ; )
{
var processList = FindProcessesByInternalName(pattern).ToList();
if (processList.Count == 0)
throw new ProcessSelectorException("No processes found");
try
{
if (processList.Count == 1)
return processList[0];
Console.WriteLine("Select process:");
for (var i = 0; i < processList.Count; ++i)
{
var debugging = false;
Kernel32.CheckRemoteDebuggerPresent(processList[i].Handle, ref debugging);
Console.WriteLine("[{0}] {1} PID: {2} {3}",
i,
processList[i].GetVersionInfo(),
processList[i].Id,
debugging ? "(Already debugging)" : "");
}
Console.WriteLine();
Console.Write("> ");
var index = Convert.ToInt32(Console.ReadLine());
return processList[index];
}
catch (Exception ex)
{
if (processList.Count == 1)
throw new ProcessSelectorException(ex.Message);
}
}
}
private const string SE_DEBUG_NAME = "SeDebugPrivilege";
/// <summary>
/// Sets debug privileges for running program.
/// </summary>
/// <returns>Internal name of a process</returns>
public static bool SetDebugPrivileges()
{
if (!Advapi32.OpenProcessToken(Kernel32.GetCurrentProcess(), TokenObject.TOKEN_ADJUST_PRIVILEGES | TokenObject.TOKEN_QUERY, out var hToken))
return false;
if (!Advapi32.LookupPrivilegeValue(null, SE_DEBUG_NAME, out var luidSEDebugNameValue))
{
Kernel32.CloseHandle(hToken);
return false;
}
TOKEN_PRIVILEGES tkpPrivileges;
tkpPrivileges.PrivilegeCount = 1;
tkpPrivileges.Luid = luidSEDebugNameValue;
tkpPrivileges.Attributes = PrivilegeAttributes.SE_PRIVILEGE_ENABLED;
if (!Advapi32.AdjustTokenPrivileges(hToken, false, ref tkpPrivileges, 0, IntPtr.Zero, IntPtr.Zero))
{
Kernel32.CloseHandle(hToken);
return false;
}
return Kernel32.CloseHandle(hToken);
}
public enum ProcessStartFlags
{
None = 0,
Suspended = 1,
NoWindow = 2,
}
public class ProcessStartResult
{
public IntPtr ProcessHandle;
public IntPtr MainThreadHandle;
public int ProcessId;
public int MainThreadId;
}
public static ProcessStartResult StartProcess(string filePath, string arguments = "",
ProcessStartFlags startFlags = ProcessStartFlags.None)
{
if (!File.Exists(filePath))
throw new MagicException($"No such file '{filePath}'");
var sInfo = new STARTUPINFO();
var pSec = new SECURITY_ATTRIBUTES();
var tSec = new SECURITY_ATTRIBUTES();
pSec.nLength = Marshal.SizeOf(pSec);
tSec.nLength = Marshal.SizeOf(tSec);
var flags = CreateProcessFlags.DETACHED_PROCESS;
if (startFlags.HasFlag(ProcessStartFlags.NoWindow))
flags |= CreateProcessFlags.CREATE_NO_WINDOW;
if (startFlags.HasFlag(ProcessStartFlags.Suspended))
flags |= CreateProcessFlags.CREATE_SUSPENDED;
if (!Kernel32.CreateProcess(filePath, arguments,
ref pSec, ref tSec, false, flags,
IntPtr.Zero, null, ref sInfo, out var pInfo))
throw new MagicException("Failed to start process");
return new ProcessStartResult()
{
ProcessId = pInfo.dwProcessId,
ProcessHandle = pInfo.hProcess,
MainThreadId = pInfo.dwThreadId,
MainThreadHandle = pInfo.hThread
};
}
}
}
| |
/*
* Xlib.cs - Native method interface for Xlib.
*
* Copyright (C) 2002, 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace Xsharp
{
using System;
using System.Runtime.InteropServices;
using Xsharp.Events;
using Xsharp.Types;
using OpenSystem.Platform;
using OpenSystem.Platform.X11;
internal sealed unsafe class Xlib
{
// Declare Xlib types that may be different sizes on different platforms.
//
// Declaring these as enumerated types is a C# trick to get a new
// integer type of the correct size that is guaranteed to be marshalled
// to Xlib in the same way as the underlying integer type.
public enum Xint : int { Zero }
public enum Xuint : uint { Zero }
public enum Xlong : int { Zero }
public enum Xulong : uint { Zero }
// Declare display-related external functions.
[DllImport("X11")]
extern public static XStatus XInitThreads();
[DllImport("X11")]
extern public static IntPtr XOpenDisplay(String display_name);
[DllImport("X11")]
extern public static int XCloseDisplay(IntPtr display);
[DllImport("X11")]
extern public static String XDisplayName(String str);
[DllImport("X11")]
extern public static int XScreenCount(IntPtr display);
[DllImport("X11")]
extern public static IntPtr XScreenOfDisplay(IntPtr display, int scr);
[DllImport("X11")]
extern public static int XDefaultScreen(IntPtr display);
[DllImport("X11")]
extern public static String XDisplayString(IntPtr display);
[DllImport("X11")]
extern public static int XFlush(IntPtr display);
[DllImport("X11")]
extern public static int XSync(IntPtr display, XBool discard);
[DllImport("X11")]
extern public static int XBell(IntPtr display, int percent);
[DllImport("X11")]
extern public static int XMaxRequestSize(IntPtr display);
[DllImport("X11")]
extern public static IntPtr XSynchronize(IntPtr display, XBool onoff);
[DllImport("X11")]
extern public static int XDisplayHeight
(IntPtr display, int screen_number);
[DllImport("X11")]
extern public static int XDisplayHeightMM
(IntPtr display, int screen_number);
[DllImport("X11")]
extern public static int XDisplayWidth
(IntPtr display, int screen_number);
[DllImport("X11")]
extern public static int XDisplayWidthMM
(IntPtr display, int screen_number);
// Declare screen-related external functions.
[DllImport("X11")]
extern public static XWindow XRootWindowOfScreen(IntPtr screen);
[DllImport("X11")]
extern public static XPixel XBlackPixelOfScreen(IntPtr screen);
[DllImport("X11")]
extern public static XPixel XWhitePixelOfScreen(IntPtr screen);
[DllImport("X11")]
extern public static XColormap XDefaultColormapOfScreen(IntPtr screen);
[DllImport("X11")]
extern public static int XDefaultDepthOfScreen(IntPtr screen);
[DllImport("X11")]
extern public static int XWidthOfScreen(IntPtr screen);
[DllImport("X11")]
extern public static int XHeightOfScreen(IntPtr screen);
[DllImport("X11")]
extern public static IntPtr XDefaultVisualOfScreen(IntPtr screen);
// Declare window-related external functions.
[DllImport("X11")]
extern public static XWindow XCreateWindow
(IntPtr display, XWindow parent, int x, int y,
uint width, uint height, uint border_width,
int depth, int c_class, IntPtr visual,
uint value_mask, ref XSetWindowAttributes values);
[DllImport("X11")]
extern public static XWindow XCreateWindow
(IntPtr display, XWindow parent, int x, int y,
uint width, uint height, uint border_width,
int depth, int c_class, IntPtr visual,
uint value_mask, IntPtr values); // for values == null.
[DllImport("X11")]
extern public static int XDestroyWindow(IntPtr display, XWindow w);
[DllImport("X11")]
extern public static int XMoveWindow
(IntPtr display, XWindow w, int x, int y);
[DllImport("X11")]
extern public static int XResizeWindow
(IntPtr display, XWindow w, uint width, uint height);
[DllImport("X11")]
extern public static int XMoveResizeWindow
(IntPtr display, XWindow w, int x, int y,
uint width, uint height);
[DllImport("X11")]
extern public static int XConfigureWindow
(IntPtr display, XWindow w, uint value_mask,
ref XWindowChanges changes);
[DllImport("X11")]
extern public static int XMapWindow(IntPtr display, XWindow w);
[DllImport("X11")]
extern public static int XMapRaised(IntPtr display, XWindow w);
[DllImport("X11")]
extern public static int XUnmapWindow(IntPtr display, XWindow w);
[DllImport("X11")]
extern public static XStatus XWithdrawWindow
(IntPtr display, XWindow w, int screen_number);
[DllImport("X11")]
extern public static XStatus XIconifyWindow
(IntPtr display, XWindow w, int screen_number);
[DllImport("X11")]
extern public static int XReparentWindow
(IntPtr display, XWindow w, XWindow parent, int x, int y);
[DllImport("X11")]
extern public static XCursor XCreateFontCursor
(IntPtr display, uint shape);
[DllImport("X11")]
extern public static int XDefineCursor
(IntPtr display, XWindow w, XCursor cursor);
[DllImport("X11")]
extern public static int XUndefineCursor(IntPtr display, XWindow w);
[DllImport("X11")]
extern public static XCursor XCreatePixmapCursor
(IntPtr display, XPixmap source, XPixmap mask,
ref XColor foreground, ref XColor background,
uint x, uint y);
[DllImport("X11")]
extern public static int XSetWindowBackground
(IntPtr display, XWindow w, XPixel background_pixel);
[DllImport("X11")]
extern public static int XSetWindowBackgroundPixmap
(IntPtr display, XWindow w, XPixmap background_pixmap);
[DllImport("X11")]
extern public static int XClearArea
(IntPtr display, XWindow w, int x, int y,
uint width, uint height, XBool exposures);
[DllImport("X11")]
extern public static XStatus XGetGeometry
(IntPtr display, XDrawable d, out XWindow root_return,
out Xint x_return, out Xint y_return,
out Xuint width_return, out Xuint height_return,
out Xuint border_width_return, out Xuint depth_return);
[DllImport("X11")]
extern public static int XGrabKeyboard
(IntPtr display, XWindow grab_window, XBool owner_events,
int pointer_mode, int keyboard_mode, XTime time);
[DllImport("X11")]
extern public static int XGrabPointer
(IntPtr display, XWindow grab_window, XBool owner_events,
uint event_mask, int pointer_mode, int keyboard_mode,
XWindow confine_to, XCursor cursor, XTime time);
[DllImport("X11")]
extern public static int XGrabButton
(IntPtr display, uint button, uint modifiers,
XWindow grab_window, XBool owner_events,
uint event_mask, int pointer_mode, int keyboard_mode,
XWindow confine_to, XCursor cursor);
[DllImport("X11")]
extern public static int XUngrabKeyboard(IntPtr display, XTime time);
[DllImport("X11")]
extern public static int XUngrabPointer(IntPtr display, XTime time);
[DllImport("X11")]
extern public static int XUngrabButton
(IntPtr display, uint button, uint modifiers,
XWindow grab_window);
[DllImport("X11")]
extern public static int XAllowEvents
(IntPtr display, int event_mode, XTime time);
// Declare pixmap-related external functions.
[DllImport("X11")]
extern public static XPixmap XCreatePixmap
(IntPtr display, XDrawable d, uint width,
uint height, uint depth);
[DllImport("X11")]
extern public static int XFreePixmap
(IntPtr display, XPixmap pixmap);
[DllImport("X11")]
extern public static XPixmap XCreateBitmapFromData
(IntPtr display, XDrawable drawable, byte[] data,
uint width, uint height);
// Declare region-related external functions.
[DllImport("X11")]
extern public static IntPtr XCreateRegion();
[DllImport("X11")]
extern public static int XDestroyRegion(IntPtr r);
[DllImport("X11")]
extern public static int XUnionRegion(IntPtr sra, IntPtr srb,
IntPtr dr_return);
[DllImport("X11")]
extern public static int XUnionRectWithRegion
(ref XRectangle rectangle, IntPtr src, IntPtr dest);
[DllImport("X11")]
extern public static int XIntersectRegion(IntPtr sra, IntPtr srb,
IntPtr dr_return);
[DllImport("X11")]
extern public static int XSubtractRegion(IntPtr sra, IntPtr srb,
IntPtr dr_return);
[DllImport("X11")]
extern public static int XXorRegion(IntPtr sra, IntPtr srb,
IntPtr dr_return);
[DllImport("X11")]
extern public static int XEmptyRegion(IntPtr r);
[DllImport("X11")]
extern public static int XEqualRegion(IntPtr r1, IntPtr r2);
[DllImport("X11")]
extern public static int XOffsetRegion
(IntPtr r, int dx, int dy);
[DllImport("X11")]
extern public static int XShrinkRegion
(IntPtr r, int dx, int dy);
[DllImport("X11")]
extern public static int XPointInRegion
(IntPtr r, int x, int y);
[DllImport("X11")]
extern public static IntPtr XPolygonRegion
(XPoint[] points, int n, int fill_rule);
[DllImport("X11")]
extern public static int XClipBox(IntPtr region, out XRectangle rect);
[DllImport("X11")]
extern public static int XRectInRegion
(IntPtr region, int x, int y,
uint width, uint height);
// Declare event-related external functions.
[DllImport("X11")]
extern public static int XNextEvent(IntPtr display, out XEvent xevent);
[DllImport("X11")]
extern public static int XEventsQueued(IntPtr display, int mode);
[DllImport("X11")]
extern public static int XSelectInput(IntPtr display, XWindow w,
int mode);
[DllImport("X11")]
extern public static XStatus XSendEvent
(IntPtr display, XWindow w, XBool propagate,
int event_mask, ref XEvent event_send);
// Declare GC-related external functions.
[DllImport("X11")]
extern public static IntPtr XCreateGC(IntPtr display,
XDrawable drawable,
uint values_mask,
ref XGCValues values);
[DllImport("X11")]
extern public static int XFreeGC(IntPtr display, IntPtr gc);
[DllImport("X11")]
extern public static int XChangeGC(IntPtr display, IntPtr gc,
uint values_mask,
ref XGCValues values);
[DllImport("X11")]
extern public static int XGetGCValues(IntPtr display, IntPtr gc,
uint values_mask,
out XGCValues values);
[DllImport("X11")]
extern public static int XSetForeground
(IntPtr display, IntPtr gc, XPixel foreground);
[DllImport("X11")]
extern public static int XSetBackground
(IntPtr display, IntPtr gc, XPixel background);
[DllImport("X11")]
extern public static int XSetFunction
(IntPtr display, IntPtr gc, int function);
[DllImport("X11")]
extern public static int XSetSubwindowMode
(IntPtr display, IntPtr gc, int subwindow_mode);
[DllImport("X11")]
extern public static int XSetFillStyle
(IntPtr display, IntPtr gc, int fill_style);
[DllImport("X11")]
extern public static int XSetTile
(IntPtr display, IntPtr gc, XPixmap tile);
[DllImport("X11")]
extern public static int XSetStipple
(IntPtr display, IntPtr gc, XPixmap stipple);
[DllImport("X11")]
extern public static int XSetTSOrigin
(IntPtr display, IntPtr gc, int ts_x_origin,
int ts_y_origin);
[DllImport("X11")]
extern public static int XSetRegion
(IntPtr display, IntPtr gc, IntPtr r);
[DllImport("X11")]
extern public static int XSetClipMask
(IntPtr display, IntPtr gc, XPixmap pixmap);
[DllImport("X11")]
extern public static int XSetClipOrigin
(IntPtr display, IntPtr gc, int x, int y);
[DllImport("X11")]
extern public static int XSetDashes
(IntPtr display, IntPtr gc, int dash_offset,
byte[] dash_list, int n);
[DllImport("X11")]
extern public static int XDrawLine
(IntPtr display, XDrawable drawable, IntPtr gc,
int x1, int y1, int x2, int y2);
[DllImport("X11")]
extern public static int XDrawLines
(IntPtr display, XDrawable drawable, IntPtr gc,
XPoint[] points, int npoints, int mode);
[DllImport("X11")]
extern public static int XDrawPoint
(IntPtr display, XDrawable drawable, IntPtr gc,
int x, int y);
[DllImport("X11")]
extern public static int XDrawPoints
(IntPtr display, XDrawable drawable, IntPtr gc,
XPoint[] points, int npoints, int mode);
[DllImport("X11")]
extern public static int XDrawRectangle
(IntPtr display, XDrawable drawable, IntPtr gc,
int x, int y, int width, int height);
[DllImport("X11")]
extern public static int XDrawRectangles
(IntPtr display, XDrawable drawable, IntPtr gc,
XRectangle[] rectangles, int nrectangles);
[DllImport("X11")]
extern public static int XDrawArc
(IntPtr display, XDrawable drawable, IntPtr gc,
int x, int y, int width, int height,
int angle1, int angle2);
[DllImport("X11")]
extern public static int XFillRectangle
(IntPtr display, XDrawable drawable, IntPtr gc,
int x, int y, int width, int height);
[DllImport("X11")]
extern public static int XFillRectangles
(IntPtr display, XDrawable drawable, IntPtr gc,
XRectangle[] rectangles, int nrectangles);
[DllImport("X11")]
extern public static int XFillPolygon
(IntPtr display, XDrawable drawable, IntPtr gc,
XPoint[] points, int npoints,
int shape, int mode);
[DllImport("X11")]
extern public static int XFillArc
(IntPtr display, XDrawable drawable, IntPtr gc,
int x, int y, int width, int height,
int angle1, int angle2);
[DllImport("X11")]
extern public static int XPutImage
(IntPtr display, XDrawable drawable, IntPtr gc,
IntPtr image, int src_x, int src_y,
int dest_x, int dest_y,
int width, int height);
[DllImport("X11")]
extern public static int XCopyArea
(IntPtr display, XDrawable src, XDrawable dest,
IntPtr gc, int src_x, int src_y,
uint width, uint height,
int dest_x, int dest_y);
// Declare window manager related external functions.
[DllImport("X11")]
extern public static int XStoreName
(IntPtr display, XWindow w, String window_name);
[DllImport("X11")]
extern public static int XSetIconName
(IntPtr display, XWindow w, String window_name);
[DllImport("X11")]
extern public static XStatus XSetWMProtocols
(IntPtr display, XWindow w, XAtom[] protocols, int count);
[DllImport("X11")]
extern public static int XReconfigureWMWindow
(IntPtr display, XWindow w, int screen_number,
uint value_mask, ref XWindowChanges changes);
[DllImport("X11")]
extern public static int XSetTransientForHint
(IntPtr display, XWindow w, XWindow prop_window);
[DllImport("X11")]
extern public static XStatus XGetTransientForHint
(IntPtr display, XWindow w, out XWindow prop_window);
[DllImport("X11")]
extern public static void XSetWMNormalHints
(IntPtr display, XWindow w, ref XSizeHints hints);
[DllImport("X11")]
extern public static void XSetWMHints
(IntPtr display, XWindow w, ref XWMHints hints);
[DllImport("X11")]
extern public static void XSetClassHint
(IntPtr display, XWindow w, ref XClassHint class_hints);
[DllImport("X11")]
extern public static int XKillClient(IntPtr display, XID resource);
// Declare selection-related external functions.
[DllImport("X11")]
extern public static XWindow XGetSelectionOwner
(IntPtr display, XAtom selection);
[DllImport("X11")]
extern public static int XSetSelectionOwner
(IntPtr display, XAtom selection, XWindow owner, XTime time);
[DllImport("X11")]
extern public static int XConvertSelection
(IntPtr display, XAtom selection, XAtom target,
XAtom property, XWindow requestor, XTime time);
// Declare color-related external functions.
[DllImport("X11")]
extern public static int XAllocColor
(IntPtr display, XColormap colormap, ref XColor xcolor);
// Declare key-related and pointer-related external functions.
[DllImport("X11")]
extern public static int XLookupString
(ref XKeyEvent xevent, IntPtr buffer, int bytes_buffer,
ref XKeySym keysym_return, IntPtr status_in_out);
[DllImport("X11")]
extern public static XKeySym XLookupKeysym
(ref XKeyEvent xevent, int index);
[DllImport("X11")]
extern public static int XGetPointerMapping
(IntPtr display, byte[] map_return, int nmap);
// Declare atom-related external functions.
[DllImport("X11")]
extern public static XAtom XInternAtom
(IntPtr display, String name, XBool only_if_exists);
// Declare property-related external functions.
[DllImport("X11")]
extern public static int XChangeProperty
(IntPtr display, XWindow w, XAtom property,
XAtom type, int format, int mode,
byte[] data, int nelements);
[DllImport("X11")]
extern public static int XChangeProperty
(IntPtr display, XWindow w, XAtom property,
XAtom type, int format, int mode,
Xlong[] data, int nelements);
[DllImport("X11")]
extern public static int XDeleteProperty
(IntPtr display, XWindow w, XAtom property);
[DllImport("X11")]
extern public static XStatus XGetWindowProperty
(IntPtr display, XWindow w, XAtom property,
int long_offset, int long_length,
XBool deleteProp, XAtom req_type,
out XAtom actual_type_return,
out Xlib.Xint actual_format_return,
out Xlib.Xulong nitems_return,
out Xlib.Xulong bytes_after_return,
out IntPtr prop_return);
// Text property and string functions.
[DllImport("X11")]
extern public static int XFree(IntPtr ptr);
[DllImport("X11")]
extern public static XStatus XStringListToTextProperty
(ref IntPtr argv, int argc, ref XTextProperty textprop);
[DllImport("X11")]
extern public static XStatus XStringListToTextProperty
(IntPtr[] argv, int argc, ref XTextProperty textprop);
[DllImport("X11")]
extern public static void XSetTextProperty
(IntPtr display, XWindow w, ref XTextProperty textProp,
XAtom property);
[DllImport("X11")]
extern public static int _XGetHostname(IntPtr buf, int maxlen);
// Helper functions from "libXsharpSupport.so".
[DllImport("XsharpSupport")]
extern public static int XSharpSupportPresent();
[DllImport("XsharpSupport")]
extern public static int XNextEventWithTimeout
(IntPtr display, out XEvent xevent, int timeout);
[DllImport("XsharpSupport")]
extern public static int XSharpUseXft();
[DllImport("XsharpSupport")]
extern public static IntPtr XSharpCreateFontXft
(IntPtr display, String family, String fallbacks,
int pointSize, int style);
[DllImport("XsharpSupport")]
extern public static void XSharpFreeFontXft
(IntPtr display, IntPtr fontSet);
[DllImport("XsharpSupport", CharSet=CharSet.Unicode)]
extern public static void XSharpDrawStringXft
(IntPtr display, XDrawable drawable, IntPtr gc,
IntPtr fontSet, int x, int y,
String str, int style, IntPtr clipRegion,
uint colorValue);
[DllImport("XsharpSupport", CharSet=CharSet.Unicode)]
extern public static void XSharpTextExtentsXft
(IntPtr display, IntPtr fontSet, String str,
out XRectangle overall_ink_return,
out XRectangle overall_logical_return);
[DllImport("XsharpSupport", CharSet=CharSet.Unicode)]
extern public static void XSharpFontExtentsXft
(IntPtr fontSet,
out XRectangle max_ink_return,
out XRectangle max_logical_return);
[DllImport("XsharpSupport")]
extern public static IntPtr XSharpCreateFontSet
(IntPtr display, String family, int pointSize, int style);
[DllImport("XsharpSupport")]
extern public static void XSharpFreeFontSet
(IntPtr display, IntPtr fontSet);
[DllImport("XsharpSupport")]
extern public static void XSharpDrawStringSet
(IntPtr display, XDrawable drawable, IntPtr gc,
IntPtr fontSet, int x, int y,
String str, int style);
[DllImport("XsharpSupport")]
extern public static void XSharpTextExtentsSet
(IntPtr display, IntPtr fontSet, String str,
out XRectangle overall_ink_return,
out XRectangle overall_logical_return);
[DllImport("XsharpSupport")]
extern public static void XSharpFontExtentsSet
(IntPtr fontSet,
out XRectangle max_ink_return,
out XRectangle max_logical_return);
[DllImport("XsharpSupport")]
extern public static IntPtr XSharpCreateFontStruct
(IntPtr display, String family, int pointSize, int style);
[DllImport("XsharpSupport")]
extern public static void XSharpFreeFontStruct
(IntPtr display, IntPtr fontSet);
[DllImport("XsharpSupport")]
extern public static void XSharpDrawStringStruct
(IntPtr display, XDrawable drawable, IntPtr gc,
IntPtr fontSet, int x, int y,
[MarshalAs(UnmanagedType.Interface)] String str,
int offset, int count, int style);
[DllImport("XsharpSupport")]
extern public static void XSharpTextExtentsStruct
(IntPtr display, IntPtr fontSet,
[MarshalAs(UnmanagedType.Interface)] String str,
int offset, int count,
out XRectangle overall_ink_return,
out XRectangle overall_logical_return);
[DllImport("XsharpSupport")]
extern public static void XSharpFontExtentsStruct
(IntPtr fontSet,
out XRectangle max_ink_return,
out XRectangle max_logical_return);
[DllImport("XsharpSupport")]
extern public static IntPtr XSharpPCFCreateImage
(byte[] data, uint length);
[DllImport("XsharpSupport")]
extern public static void XSharpPCFDestroyImage(IntPtr fontImage);
[DllImport("XsharpSupport")]
extern public static IntPtr XSharpPCFCreate(IntPtr dpy, IntPtr fontImage);
[DllImport("XsharpSupport")]
extern public static void XSharpPCFDestroy(IntPtr dpy, IntPtr renderer);
[DllImport("XsharpSupport")]
extern public static void XSharpDrawStringPCF
(IntPtr display, XDrawable drawable, IntPtr gc,
IntPtr fontSet, int x, int y,
[MarshalAs(UnmanagedType.Interface)] String str,
int offset, int count, int style);
[DllImport("XsharpSupport")]
extern public static void XSharpTextExtentsPCF
(IntPtr display, IntPtr fontSet,
[MarshalAs(UnmanagedType.Interface)] String str,
int offset, int count,
out XRectangle overall_ink_return,
out XRectangle overall_logical_return);
[DllImport("XsharpSupport")]
extern public static void XSharpFontExtentsPCF
(IntPtr fontSet,
out XRectangle max_ink_return,
out XRectangle max_logical_return);
[DllImport("XsharpSupport")]
extern public static IntPtr XSharpGetResources(IntPtr dpy, XWindow w);
[DllImport("XsharpSupport")]
extern public static void XSharpFreeResources(IntPtr value);
[DllImport("XsharpSupport")]
extern public static int XSharpGetRegionSize(IntPtr region);
[DllImport("XsharpSupport")]
extern public static void XSharpGetRegionRect
(IntPtr region, int index, out XRectangle rect);
[DllImport("XsharpSupport")]
extern public static IntPtr XSharpCreateImageFromDIB
(IntPtr screen, int width, int height,
int stride, int pixelFormat, byte[] data,
int isMask, XPixel[] palette);
[DllImport("XsharpSupport")]
extern public static void XSharpDestroyImage(IntPtr image);
[DllImport("XsharpSupport")]
extern public static void XSharpGetImageSize
(IntPtr image, out int width, out int height);
[DllImport("XsharpSupport")]
extern public static void XSharpSendClose
(IntPtr display, XWindow window);
[DllImport("XsharpSupport")]
extern public static void XSharpSendWakeup
(IntPtr display, XWindow window);
// Helper functions for creating and managing application groups.
[DllImport("Xext")]
extern public static XBool XagQueryVersion
(IntPtr display, out Xint major, out Xint minor);
[DllImport("Xext")]
extern public static XStatus XagCreateEmbeddedApplicationGroup
(IntPtr display, XVisualID root_visual, XColormap default_colormap,
XPixel black_pixel, XPixel white_pixel, out XAppGroup app_group);
[DllImport("Xext")]
extern public static XStatus XagDestroyApplicationGroup
(IntPtr display, XAppGroup app_group);
// Helper functions for managing security tokens.
public enum XSecurityAuthorization : uint { Zero }
[DllImport("Xext")]
extern public static XBool XSecurityQueryExtension
(IntPtr display, out Xint major, out Xint minor);
[DllImport("Xext")]
extern public static Xauth *XSecurityAllocXauth();
[DllImport("Xext")]
extern public static void XSecurityFreeXauth(Xauth *auth);
[DllImport("Xext")]
extern public static Xauth *XSecurityGenerateAuthorization
(IntPtr dpy, Xauth *auth_in, uint valuemask,
ref XSecurityAuthorizationAttributes attributes,
out XSecurityAuthorization auth_id_return);
// Helper functions for double buffer handling.
public enum XdbeSwapAction : byte
{
Undefined = 0,
Background = 1,
Untouched = 2,
Copied = 3
}; // enum XdbeSwapAction
[StructLayout(LayoutKind.Sequential)]
public struct XdbeSwapInfo
{
public XWindow swap_window;
public XdbeSwapAction swap_action;
}; // struct XdbeSwapInfo
[DllImport("Xext")]
extern public static XStatus XdbeQueryExtension
(IntPtr display, out Xint major, out Xint minor);
[DllImport("Xext")]
extern public static XDrawable XdbeAllocateBackBufferName
(IntPtr display, XWindow window, XdbeSwapAction swap_action);
[DllImport("Xext")]
extern public static XStatus XdbeDeallocateBackBufferName
(IntPtr display, XDrawable buffer);
[DllImport("Xext")]
extern public static XStatus XdbeSwapBuffers
(IntPtr display, ref XdbeSwapInfo swap_info, int num_windows);
// Other functions.
[DllImport("X11")]
extern public static IntPtr XListFonts
(IntPtr display, String pattern, int maxnames,
out int actualCountReturn);
[DllImport("X11")]
extern public static int XFreeFontNames(IntPtr list);
// Wrap up the "XListFonts" function and make it friendlier.
public static String[] XListFonts(IntPtr display, String pattern)
{
// Get the full list of fonts. We may have to use multiple
// requests if the maximum is reached on the first request.
int actualCount;
int maxNames = 1000;
IntPtr names;
for(;;)
{
names = XListFonts
(display, pattern, (int)maxNames, out actualCount);
if(names == IntPtr.Zero)
{
return new String [0];
}
if(actualCount < maxNames)
{
break;
}
XFreeFontNames(names);
maxNames *= 2;
}
// Convert the font list into an array of C# strings.
int posn;
int size = IntPtr.Size;
String[] result;
try
{
result = new String [(int)actualCount];
for(posn = 0; posn < actualCount; ++posn)
{
result[posn] = Marshal.PtrToStringAnsi
(Marshal.ReadIntPtr(names, posn * size));
}
}
finally
{
XFreeFontNames(names);
}
return result;
}
} // class Xlib
} // namespace Xsharp
| |
// Authors: Robert M. Scheller, James B. Domingo
using Landis.SpatialModeling;
using Landis.Core;
using Landis.Library.BiomassCohorts;
using Landis.Utilities;
using System;
namespace Landis.Extension.Succession.Biomass
{
/// <summary>
/// Calculations for an individual cohort's biomass.
/// </summary>
public class CohortBiomass
: Landis.Library.BiomassCohorts.ICalculator
{
// Ecoregion where the cohort's site is located
private IEcoregion ecoregion;
// Ratio of actual biomass to maximum biomass for the cohort.
private double B_AP;
// Ratio of potential biomass to maximum biomass for the cohort.
private double B_PM;
// Totaly mortality without annual leaf litter for the cohort
private int M_noLeafLitter;
public static int SubYear;
private double growthReduction;
private double defoliation;
public static double SpinupMortalityFraction;
//public static double CanopyLightExtinction;
//---------------------------------------------------------------------
public int MortalityWithoutLeafLitter
{
get
{
return M_noLeafLitter;
}
}
//---------------------------------------------------------------------
public CohortBiomass()
{
}
//---------------------------------------------------------------------
/// <summary>
/// Computes the change in a cohort's biomass due to Annual Net Primary
/// Productivity (ANPP), age-related mortality (M_AGE), and development-
/// related mortality (M_BIO).
/// </summary>
public int ComputeChange(ICohort cohort,
ActiveSite site)
{
int siteBiomass = SiteVars.TotalBiomass[site];
ecoregion = PlugIn.ModelCore.Ecoregion[site];
// First, calculate age-related mortality.
// Age-related mortality will include woody and standing leaf biomass (=0 for deciduous trees).
double mortalityAge = ComputeAgeMortality(cohort);
double actualANPP = ComputeActualANPP(cohort, site);
// Age mortality is discounted from ANPP to prevent the over-
// estimation of mortality. ANPP cannot be negative.
actualANPP = Math.Max(1, actualANPP - mortalityAge);
SiteVars.AGNPP[site] += actualANPP;
// ---------------------------------------------------------
// Growth-related mortality
double mortalityGrowth = ComputeGrowthMortality(cohort, site);
// Age-related mortality is discounted from growth-related
// mortality to prevent the under-estimation of mortality. Cannot be negative.
mortalityGrowth = Math.Max(0, mortalityGrowth - mortalityAge);
// Also ensure that growth mortality does not exceed actualANPP.
mortalityGrowth = Math.Min(mortalityGrowth, actualANPP);
// Total mortality for the cohort
double totalMortality = mortalityAge + mortalityGrowth;
if (totalMortality > cohort.Biomass)
throw new ApplicationException("Error: Mortality exceeds cohort biomass");
// ---------------------------------------------------------
// Defoliation ranges from 1.0 (total) to none (0.0).
// Defoliation is calculated by an external function, typically an extension
// with a defoliation calculator. The method CohortDefoliation.Compute is a delegate method
// and lives within the defoliating extension.
defoliation = Landis.Library.Biomass.CohortDefoliation.Compute(site, cohort.Species, cohort.Biomass, siteBiomass);
double defoliationLoss = 0.0;
if (defoliation > 0)
{
double standing_nonwood = ComputeFractionANPPleaf(cohort.Species) * actualANPP;
defoliationLoss = standing_nonwood * defoliation;
SiteVars.Defoliation[site] += defoliationLoss;
}
// ---------------------------------------------------------
// RMS: Adding mortality probability; do not include during spinup
if (PlugIn.ModelCore.CurrentTime > 0)
{
if (PlugIn.ModelCore.GenerateUniform() < SpeciesData.MortalityProbability[cohort.Species, ecoregion])
totalMortality = cohort.Biomass;
}
PlugIn.CurrentYearSiteMortality += totalMortality;
int deltaBiomass = (int)(actualANPP - totalMortality - defoliationLoss);
double newBiomass = cohort.Biomass + (double)deltaBiomass;
double totalLitter = UpdateDeadBiomass(cohort, actualANPP, totalMortality, site, newBiomass);
if (PlugIn.CalibrateMode && PlugIn.ModelCore.CurrentTime > 0)
{
PlugIn.ModelCore.UI.WriteLine("Yr={0}. Calculate Delta Biomass...", (PlugIn.ModelCore.CurrentTime + SubYear));
PlugIn.ModelCore.UI.WriteLine("Yr={0}. Spp={1}, Age={2}.", (PlugIn.ModelCore.CurrentTime + SubYear), cohort.Species.Name, cohort.Age);
PlugIn.ModelCore.UI.WriteLine("Yr={0}. ANPPact={1:0.0}, Mtotal={2:0.0}, litter={3:0.00}.", (PlugIn.ModelCore.CurrentTime + SubYear), actualANPP, totalMortality, totalLitter);
PlugIn.ModelCore.UI.WriteLine("Yr={0}. DeltaB={1:0.0}, CohortB={2}, Bsite={3}", (PlugIn.ModelCore.CurrentTime + SubYear), deltaBiomass, cohort.Biomass, (int)siteBiomass);
}
return deltaBiomass;
}
//---------------------------------------------------------------------
/// <summary>
/// Computes M_AGE_ij: the mortality caused by the aging of the cohort.
/// See equation 6 in Scheller and Mladenoff, 2004.
/// </summary>
private double ComputeAgeMortality(ICohort cohort)
{
double max_age = (double)cohort.Species.Longevity;
double d = SpeciesData.MortCurveShapeParm[cohort.Species];
double M_AGE = cohort.Biomass * Math.Exp((double)cohort.Age / max_age * d) / Math.Exp(d);
M_AGE = Math.Min(M_AGE, cohort.Biomass);
if(PlugIn.ModelCore.CurrentTime <= 0 && SpinupMortalityFraction > 0.0)
{
M_AGE += cohort.Biomass * SpinupMortalityFraction;
if(PlugIn.CalibrateMode)
PlugIn.ModelCore.UI.WriteLine("Yr={0}. SpinupMortalityFraction={1:0.0000}, AdditionalMortality={2:0.0}, Spp={3}, Age={4}.", (PlugIn.ModelCore.CurrentTime + SubYear), SpinupMortalityFraction, (cohort.Biomass * SpinupMortalityFraction), cohort.Species.Name, cohort.Age);
}
return Math.Min(M_AGE, cohort.Biomass);
}
//---------------------------------------------------------------------
private double ComputeActualANPP(ICohort cohort, ActiveSite site)
{
int siteBiomass = SiteVars.TotalBiomass[site];
// ---------------------------------------------------------
// Growth reduction ranges from 1.0 (total) to none (0.0).
// Growth reduction is calculated by an disturbance function, typically an extension
// with a dedicated calculator. The method CohortGrowthReduction.Compute is a delegate method
// and lives within the disturbance extension.
growthReduction = CohortGrowthReduction.Compute(cohort, site);
double growthShape = SpeciesData.GrowthCurveShapeParm[cohort.Species];
double cohortBiomass = cohort.Biomass;
double capacityReduction = 1.0;
if(SiteVars.CapacityReduction != null && SiteVars.CapacityReduction[site] > 0)
{
capacityReduction = 1.0 - SiteVars.CapacityReduction[site];
if(PlugIn.CalibrateMode)
PlugIn.ModelCore.UI.WriteLine("Yr={0}. Capacity Remaining={1:0.00}, Spp={2}, Age={3} B={4}.", (PlugIn.ModelCore.CurrentTime + SubYear), capacityReduction, cohort.Species.Name, cohort.Age, cohort.Biomass);
}
double maxBiomass = SpeciesData.B_MAX_Spp[cohort.Species,ecoregion] * capacityReduction;
double maxANPP = SpeciesData.ANPP_MAX_Spp[cohort.Species,ecoregion];
// Potential biomass, equation 3 in Scheller and Mladenoff, 2004
double potentialBiomass = Math.Max(1.0, maxBiomass - siteBiomass + cohortBiomass);
// Species can use new space from mortality immediately
// but not in the case of capacity reduction due to harvesting.
if(capacityReduction >= 1.0)
potentialBiomass = Math.Max(potentialBiomass, SiteVars.PreviousYearMortality[site]);
// Ratio of cohort's actual biomass to potential biomass
B_AP = cohortBiomass / potentialBiomass;
double indexC = CalculateCompetition(site, cohort);
if ((indexC <= 0.0 && cohortBiomass > 0) || indexC > 1.0)
{
PlugIn.ModelCore.UI.WriteLine("Error: Competition Index [{0:0.00}] is <= 0.0 or > 1.0", indexC);
PlugIn.ModelCore.UI.WriteLine("Yr={0}. SPECIES={1}, AGE={2}, B={3}", (PlugIn.ModelCore.CurrentTime + SubYear), cohort.Species.Name, cohort.Age, cohortBiomass);
throw new ApplicationException("Application terminating.");
}
B_PM = indexC;
// PlugIn.ModelCore.Log.WriteLine("indexC={0:0.00}, lightIndexC={1:0.00}, OldSchool={2:0.00}.", indexC, indexLightC, indexOldSchool);
// Actual ANPP: equation (4) from Scheller & Mladenoff, 2004.
double actualANPP = maxANPP * Math.E * Math.Pow(B_AP, growthShape) * Math.Exp(-1 * Math.Pow(B_AP, growthShape)) * B_PM;
// Calculated actual ANPP can not exceed the limit set by the
// maximum ANPP times the ratio of potential to maximum biomass.
// This down regulates actual ANPP by the available growing space.
actualANPP = Math.Min(maxANPP * B_PM, actualANPP);
if (growthReduction > 0)
actualANPP *= (1.0 - growthReduction);
if(PlugIn.CalibrateMode && PlugIn.ModelCore.CurrentTime > 0)
{
PlugIn.ModelCore.UI.WriteLine("Yr={0}. Calculate ANPPactual...", (PlugIn.ModelCore.CurrentTime + SubYear));
PlugIn.ModelCore.UI.WriteLine("Yr={0}. Spp={1}, Age={2}.", (PlugIn.ModelCore.CurrentTime + SubYear), cohort.Species.Name, cohort.Age);
PlugIn.ModelCore.UI.WriteLine("Yr={0}. MaxANPP={1}, MaxB={2:0}, Bsite={3}, Bcohort={4:0.0}.", (PlugIn.ModelCore.CurrentTime + SubYear), maxANPP, maxBiomass, (int)siteBiomass, cohort.Biomass);
PlugIn.ModelCore.UI.WriteLine("Yr={0}. B_PM={1:0.0}, B_AP={2:0.0}, actualANPP={3:0.0}, capacityReduction={4:0.0}.", (PlugIn.ModelCore.CurrentTime + SubYear), B_PM, B_AP, actualANPP, capacityReduction);
}
return actualANPP;
}
//---------------------------------------------------------------------
/// <summary>
/// The mortality caused by development processes,
/// including self-thinning and loss of branches, twigs, etc.
/// See equation 5 in Scheller and Mladenoff, 2004.
/// </summary>
private double ComputeGrowthMortality(ICohort cohort, ActiveSite site)
{
double maxANPP = SpeciesData.ANPP_MAX_Spp[cohort.Species,ecoregion];
double M_BIO = 0.0;
//Michaelis-Menton function:
if (B_AP > 1.0)
M_BIO = maxANPP * B_PM;
else
M_BIO = maxANPP * (2.0 * B_AP) / (1.0 + B_AP) * B_PM;
// Mortality should not exceed the amount of living biomass
M_BIO = Math.Min(cohort.Biomass, M_BIO);
// Calculated actual ANPP can not exceed the limit set by the
// maximum ANPP times the ratio of potential to maximum biomass.
// This down regulates actual ANPP by the available growing space.
M_BIO = Math.Min(maxANPP * B_PM, M_BIO);
if (growthReduction > 0)
M_BIO *= (1.0 - growthReduction);
return M_BIO;
}
//---------------------------------------------------------------------
private double UpdateDeadBiomass(ICohort cohort, double actualANPP, double totalMortality, ActiveSite site, double newBiomass)
{
ISpecies species = cohort.Species;
double leafLongevity = SpeciesData.LeafLongevity[species];
double cohortBiomass = newBiomass; // Mortality is for the current year's biomass.
double leafFraction = ComputeFractionANPPleaf(species);
// First, deposit the a portion of the leaf mass directly onto the forest floor.
// In this way, the actual amount of leaf biomass is added for the year.
double annualLeafANPP = actualANPP * leafFraction;
ForestFloor.AddLitter(annualLeafANPP, species, site);
// --------------------------------------------------------------------------------
// The next section allocates mortality from standing (wood and leaf) biomass, i.e.,
// biomass that has accrued from previous years' growth.
// Subtract annual leaf growth as that was taken care of above.
totalMortality -= annualLeafANPP;
// Assume that standing foliage is equal to this years annualLeafANPP * leaf longevity
// minus this years leaf ANPP. This assumes that actual ANPP has been relatively constant
// over the past 2 or 3 years (if coniferous).
double standing_nonwood = (annualLeafANPP * leafLongevity) - annualLeafANPP;
double standing_wood = Math.Max(0, cohortBiomass - standing_nonwood);
double fractionStandingNonwood = standing_nonwood / cohortBiomass;
// Assume that the remaining mortality is divided proportionally
// between the woody mass and non-woody mass (Niklaus & Enquist,
// 2002). Do not include current years growth.
double mortality_nonwood = Math.Max(0.0, totalMortality * fractionStandingNonwood);
double mortality_wood = Math.Max(0.0, totalMortality - mortality_nonwood);
if (mortality_wood < 0 || mortality_nonwood < 0)
throw new ApplicationException("Error: Woody input is < 0");
// Add mortality to dead biomass pools.
if (mortality_wood > 0)
{
ForestFloor.AddWoody((ushort)mortality_wood, species, site);
}
if (mortality_nonwood > 0)
{
ForestFloor.AddLitter(mortality_nonwood, species, site);
}
// Total mortality not including annual leaf litter
M_noLeafLitter = (int)mortality_wood;
return (annualLeafANPP + mortality_nonwood + mortality_wood);
}
//---------------------------------------------------------------------
/// <summary>
/// Computes the cohort's biomass that is leaf litter
/// or other non-woody components. Assumption is that remainder is woody.
/// </summary>
public static double ComputeStandingLeafBiomass(double ANPPactual, ICohort cohort)
{
double annualLeafFraction = ComputeFractionANPPleaf(cohort.Species);
double annualFoliar = ANPPactual * annualLeafFraction;
double B_nonwoody = annualFoliar * SpeciesData.LeafLongevity[cohort.Species];
// Non-woody cannot be less than 2.5% or greater than leaf fraction of total
// biomass for a cohort.
B_nonwoody = Math.Max(B_nonwoody, cohort.Biomass * 0.025);
B_nonwoody = Math.Min(B_nonwoody, cohort.Biomass * annualLeafFraction);
return B_nonwoody;
}
//---------------------------------------------------------------------
public static double ComputeFractionANPPleaf(ISpecies species)
{
// A portion of growth goes to creating leaves (Niklas and Enquist 2002).
// Approximate for angio and conifer:
// pg. 817, growth (G) ratios for leaf:stem (Table 4) = 0.54 or 35% leaf
double leafFraction = 0.35;
// Approximately 3.5% of aboveground production goes to early leaf
// fall, bud scales, seed production, and herbivores (Crow 1978).
//leafFraction += 0.035;
return leafFraction;
}
//---------------------------------------------------------------------
/// <summary>
/// Computes the percentage of a cohort's standing biomass that is non-woody.
/// This method is designed for external calls that need to
/// estimate the amount of non-wood biomass.
/// </summary>
public Percentage ComputeNonWoodyPercentage(ICohort cohort,
ActiveSite site)
{
double mortalityAge = ComputeAgeMortality(cohort);
double actualANPP = ComputeActualANPP(cohort, site);
// Age mortality is discounted from ANPP to prevent the over-
// estimation of mortality. ANPP cannot be negative.
actualANPP = Math.Max(0, actualANPP - mortalityAge);
return new Percentage(ComputeStandingLeafBiomass(actualANPP, cohort) / cohort.Biomass);
}
//---------------------------------------------------------------------
/// <summary>
/// Computes the initial biomass for a cohort at a site.
/// </summary>
public static int InitialBiomass(ISpecies species,
SiteCohorts cohorts,
ActiveSite site)
{
IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site];
double B_ACT = 0; // Actual biomass - excluding "young" cohorts added in the same timestep
// Copied from Library.BiomassCohorts.Cohorts.cs, but added restriction that age > 1 (required when running 1-year timestep)
foreach (ISpeciesCohorts speciesCohorts in cohorts)
{
foreach (ICohort cohort in speciesCohorts)
{
if ((cohort.Age >= PlugIn.SuccessionTimeStep) && (cohort.Age > 1))
B_ACT += cohort.Biomass;
}
}
double maxBiomass = SpeciesData.B_MAX_Spp[species,ecoregion];
double maxANPP = SpeciesData.ANPP_MAX_Spp[species,ecoregion];
// Initial biomass exponentially declines in response to
// competition.
double initialBiomass = maxANPP * Math.Exp(-1.6 * B_ACT / EcoregionData.B_MAX[ecoregion]);
// Initial biomass cannot be greater than maxANPP
initialBiomass = Math.Min(maxANPP, initialBiomass);
// Initial biomass cannot be less than 2. C. Dymond issue from August 2016
initialBiomass = Math.Max(2.0, initialBiomass);
return (int)initialBiomass;
}
//---------------------------------------------------------------------
// New method for calculating competition limits.
// Iterates through cohorts, assigning each a competitive efficiency
// The SiteVars.Cohorts here already reflects growth of some cohorts within the timestep. Ideally that would not be the case, at least for cohorts of the same age. Otherwise, the order they are listed influences their competion.
// FIXME
private static double CalculateCompetition(ActiveSite site, ICohort cohort)
{
double competitionPower = 0.95;
double CMultiplier = Math.Max(Math.Pow(cohort.Biomass, competitionPower), 1.0);
double CMultTotal = CMultiplier;
// PlugIn.ModelCore.Log.WriteLine("Competition: spp={0}, age={1}, CMultiplier={2:0}, CMultTotal={3:0}.", cohort.Species.Name, cohort.Age, CMultiplier, CMultTotal);
foreach (ISpeciesCohorts speciesCohorts in SiteVars.Cohorts[site])
{
foreach (ICohort xcohort in speciesCohorts)
{
if (xcohort.Age + 1 != cohort.Age || xcohort.Species.Index != cohort.Species.Index)
{
double tempMultiplier = Math.Max(Math.Pow(xcohort.Biomass, competitionPower), 1.0);
CMultTotal += tempMultiplier;
}
}
}
double Cfraction = CMultiplier / CMultTotal;
//PlugIn.ModelCore.Log.WriteLine("Competition: spp={0}, age={1}, CMultiplier={2:0}, CMultTotal={3:0}, CI={4:0.00}.", cohort.Species.Name, cohort.Age, CMultiplier, CMultTotal, Cfraction);
return Cfraction;
}
}
}
| |
using System;
using System.IO;
using Xunit;
using NMagickWand.Enums;
namespace NMagickWand.Tests
{
public class WrapperTests
{
const bool KEEP_FILES = false;
[Fact]
[Trait("area", "wrap")]
public void MakeThumbnail()
{
var file = "test2.jpg";
MagickWandEnvironment.Genesis();
using(var mw = new MagickWand())
{
mw.ReadImage("test.jpg");
mw.ScaleImage(120, 100);
mw.WriteImage(file, true);
Assert.True(File.Exists(file), "scaled image not created");
}
using(var mw = new MagickWand(file))
{
Assert.True(mw.ImageWidth == 120, "width does not match the expected size");
Assert.True(mw.ImageHeight == 100, "height does not match the expected size");
}
File.Delete(file);
MagickWandEnvironment.Terminus();
}
[Fact]
[Trait("area", "wrap")]
public void Resize()
{
var file = "test3.jpg";
MagickWandEnvironment.Genesis();
using(var mw = new MagickWand())
{
mw.ReadImage("test.jpg");
mw.ResizeImage(120, 100, FilterTypes.LanczosFilter, 1);
mw.WriteImage(file, true);
Assert.True(File.Exists(file), "scaled image not created");
}
using(var mw = new MagickWand(file))
{
Assert.True(mw.ImageWidth == 120, "width does not match the expected size");
Assert.True(mw.ImageHeight == 100, "height does not match the expected size");
}
File.Delete(file);
MagickWandEnvironment.Terminus();
}
[Fact]
[Trait("area", "wrap")]
public void TestWrapperAndStringQueryFuncs()
{
MagickWandEnvironment.Genesis();
using(var mi = new MagickWand())
{
mi.ReadImage(TestHelper.TEST_FILE);
var list = mi.GetImageProperties(string.Empty);
Assert.True(list != null, "the list should not be null");
Assert.True(list.Count > 0, "there should be more than 1 profile");
foreach(var item in list)
{
Console.WriteLine($"profile: {item}");
}
}
MagickWandEnvironment.Terminus();
}
[Fact]
[Trait("area", "wrap")]
public void TestNightOptimizations()
{
MagickWandEnvironment.Genesis();
using(var mw = new MagickWand("nighttest.jpg"))
{
using(var mw2 = mw.Clone())
{
mw2.AutoGammaImage();
Write(mw2, "night_AutoGammaImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.AutoLevelImage();
Write(mw2, "night_AutoLevelImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.LinearStretchImage(2, 98);
Write(mw2, "night_LinearStretchImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.NormalizeImage();
Write(mw2, "night_NormalizeImage.jpg");
}
}
MagickWandEnvironment.Terminus();
}
[Fact(Skip="temp")]
[Trait("area", "wrap")]
public void TestBasicWandMethods()
{
MagickWandEnvironment.Genesis();
using(var pw = new PixelWand())
using(var mw = new MagickWand("test.jpg"))
{
pw.Red = 200;
using(var mw2 = mw.Clone())
{
mw2.AdaptiveBlurImage(5, 2);
Write(mw2, "AdaptiveBlurImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.AdaptiveResizeImage(320, 212);
Write(mw2, "adaptiveResizeImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.AdaptiveSharpenImage(20, 12);
Write(mw2, "AdaptiveSharpenImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.AdaptiveThresholdImage(20, 12, 2);
Write(mw2, "AdaptiveThresholdImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.AddNoiseImage(NoiseType.PoissonNoise);
Write(mw2, "AddNoiseImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.AutoGammaImage();
Write(mw2, "AutoGammaImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.AutoLevelImage();
Write(mw2, "AutoLevelImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.AutoOrientImage();
Write(mw2, "AutoOrientImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.BlurImage(10, 2);
Write(mw2, "BlurImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.BorderImage(pw, 10, 10);
Write(mw2, "BorderImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.BrightnessContrastImage(30, 20);
Write(mw2, "BrightnessContrastImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.CharcoalImage(30, 20);
Write(mw2, "CharcoalImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ChopImage(30, 20, 0, 0);
Write(mw2, "ChopImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ClampImage();
Write(mw2, "ClampImage.jpg");
}
/*
using(var mw2 = mw.Clone())
{
mw2.ClipImage();
Write(mw2, "ClipImage.jpg");
}
*/
using(var mw2 = mw.Clone())
{
mw2.ContrastImage(true);
Write(mw2, "ContrastImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ContrastStretchImage(2, 98);
Write(mw2, "ContrastStretchImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.CropImage(30, 20, 0, 0);
Write(mw2, "CropImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.CycleColormapImage(4);
Write(mw2, "CycleColormapImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.DeskewImage(40);
Write(mw2, "DeskewImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.DespeckleImage();
Write(mw2, "DespeckleImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.EdgeImage(2);
Write(mw2, "EdgeImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.EmbossImage(12, 2);
Write(mw2, "EmbossImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.EnhanceImage();
Write(mw2, "EnhanceImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.EqualizeImage();
Write(mw2, "EqualizeImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.EvaluateImage(MagickEvaluateOperator.CosineEvaluateOperator, 4);
Write(mw2, "EvaluateImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ExtentImage(5, 5, 0, 0);
Write(mw2, "ExtentImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.FlipImage();
Write(mw2, "FlipImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.FlopImage();
Write(mw2, "FlopImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.FrameImage(pw, 10, 10, 4, 4);
Write(mw2, "FrameImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.GammaImage(3);
Write(mw2, "GammaImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.GaussianBlurImage(12, 3);
Write(mw2, "GaussianBlurImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ImplodeImage(12);
Write(mw2, "ImplodeImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.LevelImage(2, 2.3, 98);
Write(mw2, "LevelImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.LinearStretchImage(2, 98);
Write(mw2, "LinearStretchImage.jpg");
}
/*
using(var mw2 = mw.Clone())
{
mw2.LiquidRescaleImage(320, 212, 2, 2);
Write(mw2, "LiquidRescaleImage.jpg");
}
*/
using(var mw2 = mw.Clone())
{
mw2.LocalContrastImage(8, 4);
Write(mw2, "LocalContrastImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.MagnifyImage();
Write(mw2, "MagnifyImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.MinifyImage();
Write(mw2, "MinifyImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ModulateImage(2, 3, 4);
Write(mw2, "ModulateImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.MotionBlurImage(12, 3, 45);
Write(mw2, "MotionBlurImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.NegateImage(true);
Write(mw2, "NegateImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.NormalizeImage();
Write(mw2, "NormalizeImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.OilPaintImage(8);
Write(mw2, "OilPaintImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.OptimizeImageTransparency();
Write(mw2, "OptimizeImageTransparency.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.PosterizeImage(64, true);
Write(mw2, "PosterizeImage.jpg");
}
/*
using(var mw2 = mw.Clone())
{
mw2.ProfileImage();
Write(mw2, "ProfileImage.jpg");
}
*/
using(var mw2 = mw.Clone())
{
mw2.QuantizeImage(64, ColorspaceType.sRGBColorspace, 12, true, false);
Write(mw2, "QuantizeImage.jpg");
}
/*
using(var mw2 = mw.Clone())
{
mw2.RaiseImage(320, 212, 4, 4, true);
Write(mw2, "RaiseImage.jpg");
}
*/
using(var mw2 = mw.Clone())
{
mw2.RandomThresholdImage(5, 80);
Write(mw2, "RandomThresholdImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ResampleImage(96, 96, FilterTypes.Lanczos2SharpFilter, 1);
Write(mw2, "ResampleImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ResizeImage(320, 212, FilterTypes.Lanczos2Filter, 2);
Write(mw2, "ResizeImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.RollImage(4, 4);
Write(mw2, "RollImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.RotateImage(pw, 45);
Write(mw2, "RotateImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.RotationalBlurImage(45);
Write(mw2, "RotationalBlurImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.SampleImage(320, 212);
Write(mw2, "SampleImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ScaleImage(320, 212);
Write(mw2, "ScaleImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.SegmentImage(ColorspaceType.sRGBColorspace, false, 5, 2);
Write(mw2, "SegmentImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.SelectiveBlurImage(8, 2, 4);
Write(mw2, "SelectiveBlurImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.SepiaToneImage(52428);
Write(mw2, "SepiaToneImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ShadeImage(true, 8, 8);
Write(mw2, "ShadeImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ShadowImage(8, 4, 0, 0);
Write(mw2, "ShadowImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.SharpenImage(8, 4);
Write(mw2, "SharpenImage.jpg");
}
/*
using(var mw2 = mw.Clone())
{
mw2.ShaveImage(320, 212);
Write(mw2, "ShaveImage.jpg");
}
*/
using(var mw2 = mw.Clone())
{
mw2.ShearImage(pw, 12, 12);
Write(mw2, "ShearImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.SketchImage(12, 4, 45);
Write(mw2, "SketchImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.SolarizeImage(5);
Write(mw2, "SolarizeImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.SpreadImage(5);
Write(mw2, "SpreadImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.SwirlImage(5);
Write(mw2, "SwirlImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ThresholdImage(5);
Write(mw2, "ThresholdImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.ThumbnailImage(320, 212);
Write(mw2, "ThumbnailImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.TintImage(pw, pw);
Write(mw2, "TintImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.TrimImage(8);
Write(mw2, "TrimImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.UnsharpMaskImage(8, 2, 3, 4);
Write(mw2, "UnsharpMaskImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.VignetteImage(8, 90, 3, 4);
Write(mw2, "VignetteImage.jpg");
}
using(var mw2 = mw.Clone())
{
mw2.WaveImage(8, 12);
Write(mw2, "WaveImage.jpg");
}
}
MagickWandEnvironment.Terminus();
}
[Fact]
[Trait("area", "wrap")]
public void StreamTest()
{
MagickWandEnvironment.Genesis();
using(var wand = new MagickWand(TestHelper.TEST_FILE))
using(var ms = new MemoryStream())
{
wand.WriteImage(ms);
var streamfile = "streamtest.jpg";
using(var fs = new FileStream(streamfile, FileMode.CreateNew))
{
ms.CopyTo(fs);
fs.Flush();
}
Assert.True(File.Exists(streamfile));
using(var newWand = new MagickWand(streamfile))
{
Assert.True(wand.ImageHeight == newWand.ImageHeight);
Assert.True(wand.ImageWidth == newWand.ImageWidth);
}
File.Delete(streamfile);
}
MagickWandEnvironment.Terminus();
}
[Fact]
[Trait("area", "wrap")]
public void PixelIteratorTest()
{
MagickWandEnvironment.Genesis();
using(var wand = new MagickWand(TestHelper.TEST_FILE))
using(var pit = new PixelIterator(wand))
{
var yCount = 0;
string[,] imgColors = new string[wand.ImageWidth, wand.ImageHeight];
for(int y = 0; y < wand.ImageHeight; y++)
{
var list = pit.GetNextIteratorRow();
Assert.True(list.Count == wand.ImageWidth, "we should get the same number of pixels as the image width");
for(int x = 0; x < list.Count; x++)
{
imgColors[x,y] = list[x].Color;
}
yCount++;
}
Assert.True(wand.ImageHeight == yCount, "we should have iterated over all rows in the image successfully");
}
MagickWandEnvironment.Terminus();
}
[Fact]
[Trait("area", "wrap")]
public void PixelHtmlColor()
{
MagickWandEnvironment.Genesis();
using(var wand = new MagickWand(TestHelper.TEST_FILE))
using(var pw = wand.GetImagePixelColor(100, 100))
{
Assert.True(string.Equals(pw.HtmlColor, "#5C3A15", StringComparison.OrdinalIgnoreCase));
}
MagickWandEnvironment.Terminus();
}
void Write(MagickWand wand, string file)
{
if(KEEP_FILES)
{
wand.WriteImage("wrapper_out" + Path.DirectorySeparatorChar + file, true);
}
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace WingtipSearchAppWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using UnityEngine;
[ExecuteInEditMode]
[AddComponentMenu("MegaShapes/Track")]
public class MegaTracks : MonoBehaviour
{
public MegaShape shape;
public int curve = 0;
public float start = 0.0f;
public Vector3 rotate = Vector3.zero;
public bool displayspline = true;
public Vector3 linkOff = Vector3.zero;
public Vector3 linkScale = Vector3.one;
public Vector3 linkOff1 = new Vector3(0.0f, 1.0f, 0.0f);
public Vector3 linkPivot = Vector3.zero;
public Vector3 linkRot = Vector3.zero;
public GameObject LinkObj;
public bool RandomOrder = false;
public float LinkSize = 1.0f;
public bool dolateupdate = false;
public bool animate = false;
public float speed = 0.0f;
public Vector3 trackup = Vector3.up;
public bool InvisibleUpdate = false;
public int seed = 0;
public bool rebuild = true;
bool visible = true;
public bool randRot = false;
float lastpos = -1.0f;
Matrix4x4 tm;
Matrix4x4 wtm;
int linkcount = 0;
int remain;
Transform[] linkobjs;
[ContextMenu("Help")]
public void Help()
{
Application.OpenURL("http://www.west-racing.com/mf/?page_id=3538");
}
void Awake()
{
lastpos = -1.0f;
rebuild = true;
Rebuild();
}
void Reset()
{
Rebuild();
}
public void Rebuild()
{
BuildTrack();
}
void Update()
{
if ( animate )
{
if ( Application.isPlaying )
start += speed * Time.deltaTime;
}
if ( visible || InvisibleUpdate )
{
if ( !dolateupdate )
BuildTrack();
}
}
void LateUpdate()
{
if ( visible || InvisibleUpdate )
{
if ( dolateupdate )
BuildTrack();
}
}
void BuildTrack()
{
if ( shape != null && LinkObj != null )
{
if ( rebuild || lastpos != start )
{
rebuild = false;
lastpos = start;
BuildObjectLinks(shape);
}
}
}
void OnBecameVisible()
{
visible = true;
}
void OnBecameInvisible()
{
visible = false;
}
// Taken from chain mesher
void InitLinkObjects(MegaShape path)
{
if ( LinkObj == null )
return;
float len = path.splines[curve].length;
// Assume z axis for now
float linklen = (linkOff1.y - linkOff.y) * linkScale.x * LinkSize;
linkcount = (int)(len / linklen);
for ( int i = linkcount; i < gameObject.transform.childCount; i++ )
{
GameObject go = gameObject.transform.GetChild(i).gameObject;
if ( Application.isEditor )
DestroyImmediate(go);
else
Destroy(go);
}
linkobjs = new Transform[linkcount];
if ( linkcount > gameObject.transform.childCount )
{
for ( int i = 0; i < gameObject.transform.childCount; i++ )
{
GameObject go = gameObject.transform.GetChild(i).gameObject;
#if UNITY_3_5
go.SetActiveRecursively(true);
#else
go.SetActive(true);
#endif
linkobjs[i] = go.transform;
}
int index = gameObject.transform.childCount;
for ( int i = index; i < linkcount; i++ )
{
GameObject go = new GameObject();
go.name = "Link";
GameObject obj = LinkObj;
if ( obj )
{
MeshRenderer mr = (MeshRenderer)obj.GetComponent<MeshRenderer>();
Mesh ms = MegaUtils.GetSharedMesh(obj);
MeshRenderer mr1 = (MeshRenderer)go.AddComponent<MeshRenderer>();
MeshFilter mf1 = (MeshFilter)go.AddComponent<MeshFilter>();
mf1.sharedMesh = ms;
mr1.sharedMaterial = mr.sharedMaterial;
go.transform.parent = gameObject.transform;
linkobjs[i] = go.transform;
}
}
}
else
{
for ( int i = 0; i < linkcount; i++ )
{
GameObject go = gameObject.transform.GetChild(i).gameObject;
#if UNITY_3_5
go.SetActiveRecursively(true);
#else
go.SetActive(true);
#endif
linkobjs[i] = go.transform;
}
}
#if UNITY_5_4 || UNITY_5_5 || UNITY_5_6 || UNITY_2017
Random.InitState(0);
#else
Random.seed = 0;
#endif
for ( int i = 0; i < linkcount; i++ )
{
GameObject obj = LinkObj; //1[oi];
GameObject go = gameObject.transform.GetChild(i).gameObject;
MeshRenderer mr = (MeshRenderer)obj.GetComponent<MeshRenderer>();
Mesh ms = MegaUtils.GetSharedMesh(obj);
MeshRenderer mr1 = (MeshRenderer)go.GetComponent<MeshRenderer>();
MeshFilter mf1 = (MeshFilter)go.GetComponent<MeshFilter>();
mf1.sharedMesh = ms;
mr1.sharedMaterials = mr.sharedMaterials;
}
}
void BuildObjectLinks(MegaShape path)
{
float len = path.splines[curve].length;
if ( LinkSize < 0.1f )
LinkSize = 0.1f;
// Assume z axis for now
float linklen = (linkOff1.y - linkOff.y) * linkScale.x * LinkSize;
int lc = (int)(len / linklen);
if ( lc != linkcount )
InitLinkObjects(path);
Quaternion linkrot1 = Quaternion.identity;
linkrot1 = Quaternion.Euler(rotate);
float spos = start * 0.01f;
Vector3 poff = linkPivot * linkScale.x * LinkSize;
float lastalpha = spos;
Vector3 pos = Vector3.zero;
Matrix4x4 pmat = Matrix4x4.TRS(poff, linkrot1, Vector3.one);
Vector3 lrot = Vector3.zero;
Quaternion frot = Quaternion.identity;
#if UNITY_5_4 || UNITY_5_5 || UNITY_5_6 || UNITY_2017
Random.InitState(seed);
#else
Random.seed = seed;
#endif
for ( int i = 0; i < linkcount; i++ )
{
float alpha = ((float)(i + 1) / (float)linkcount) + spos;
Quaternion lq = GetLinkQuat(alpha, lastalpha, out pos, path);
lastalpha = alpha;
Quaternion lr = Quaternion.Euler(lrot);
frot = lq * linkrot1 * lr;
if ( linkobjs[i] )
{
Matrix4x4 lmat = Matrix4x4.TRS(pos, lq, Vector3.one) * pmat;
linkobjs[i].localPosition = lmat.GetColumn(3);
linkobjs[i].localRotation = frot;
linkobjs[i].localScale = linkScale * LinkSize;
}
if ( randRot )
{
float r = Random.Range(0.0f, 1.0f);
lrot = (int)(r * (int)(360.0f / MegaUtils.LargestValue1(linkRot))) * linkRot;
}
else
lrot += linkRot;
}
}
Quaternion GetLinkQuat(float alpha, float last, out Vector3 ps, MegaShape path)
{
int k = 0;
ps = path.splines[curve].InterpCurve3D(last, shape.normalizedInterp, ref k);
Vector3 ps1 = path.splines[curve].InterpCurve3D(alpha, shape.normalizedInterp, ref k);
Vector3 relativePos = ps1 - ps;
Quaternion rotation = Quaternion.LookRotation(relativePos, trackup);
return rotation;
}
}
| |
/*
* CP1258.cs - Vietnamese (Windows) code page.
*
* Copyright (c) 2002 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
*/
// Generated from "ibm-5354.ucm".
namespace I18N.Other
{
using System;
using I18N.Common;
public class CP1258 : ByteEncoding
{
public CP1258()
: base(1258, ToChars, "Vietnamese (Windows)",
"windows-1258", "windows-1258", "windows-1258",
true, true, true, true, 1258)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
'\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
'\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029',
'\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
'\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041',
'\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D',
'\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059',
'\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065',
'\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
'\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071',
'\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'\u007E', '\u007F', '\u20AC', '\u0081', '\u201A', '\u0192',
'\u201E', '\u2026', '\u2020', '\u2021', '\u02C6', '\u2030',
'\u008A', '\u2039', '\u0152', '\u008D', '\u008E', '\u008F',
'\u0090', '\u2018', '\u2019', '\u201C', '\u201D', '\u2022',
'\u2013', '\u2014', '\u02DC', '\u2122', '\u009A', '\u203A',
'\u0153', '\u009D', '\u009E', '\u0178', '\u00A0', '\u00A1',
'\u00A2', '\u00A3', '\u00A4', '\u00A5', '\u00A6', '\u00A7',
'\u00A8', '\u00A9', '\u00AA', '\u00AB', '\u00AC', '\u00AD',
'\u00AE', '\u00AF', '\u00B0', '\u00B1', '\u00B2', '\u00B3',
'\u00B4', '\u00B5', '\u00B6', '\u00B7', '\u00B8', '\u00B9',
'\u00BA', '\u00BB', '\u00BC', '\u00BD', '\u00BE', '\u00BF',
'\u00C0', '\u00C1', '\u00C2', '\u0102', '\u00C4', '\u00C5',
'\u00C6', '\u00C7', '\u00C8', '\u00C9', '\u00CA', '\u00CB',
'\u0300', '\u00CD', '\u00CE', '\u00CF', '\u0110', '\u00D1',
'\u0309', '\u00D3', '\u00D4', '\u01A0', '\u00D6', '\u00D7',
'\u00D8', '\u00D9', '\u00DA', '\u00DB', '\u00DC', '\u01AF',
'\u0303', '\u00DF', '\u00E0', '\u00E1', '\u00E2', '\u0103',
'\u00E4', '\u00E5', '\u00E6', '\u00E7', '\u00E8', '\u00E9',
'\u00EA', '\u00EB', '\u0301', '\u00ED', '\u00EE', '\u00EF',
'\u0111', '\u00F1', '\u0323', '\u00F3', '\u00F4', '\u01A1',
'\u00F6', '\u00F7', '\u00F8', '\u00F9', '\u00FA', '\u00FB',
'\u00FC', '\u01B0', '\u20AB', '\u00FF',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x0081:
case 0x008A:
case 0x008D:
case 0x008E:
case 0x008F:
case 0x0090:
case 0x009A:
case 0x009D:
case 0x009E:
case 0x00A0:
case 0x00A1:
case 0x00A2:
case 0x00A3:
case 0x00A4:
case 0x00A5:
case 0x00A6:
case 0x00A7:
case 0x00A8:
case 0x00A9:
case 0x00AA:
case 0x00AB:
case 0x00AC:
case 0x00AD:
case 0x00AE:
case 0x00AF:
case 0x00B0:
case 0x00B1:
case 0x00B2:
case 0x00B3:
case 0x00B4:
case 0x00B5:
case 0x00B6:
case 0x00B7:
case 0x00B8:
case 0x00B9:
case 0x00BA:
case 0x00BB:
case 0x00BC:
case 0x00BD:
case 0x00BE:
case 0x00BF:
case 0x00C0:
case 0x00C1:
case 0x00C2:
case 0x00C4:
case 0x00C5:
case 0x00C6:
case 0x00C7:
case 0x00C8:
case 0x00C9:
case 0x00CA:
case 0x00CB:
case 0x00CD:
case 0x00CE:
case 0x00CF:
case 0x00D1:
case 0x00D3:
case 0x00D4:
case 0x00D6:
case 0x00D7:
case 0x00D8:
case 0x00D9:
case 0x00DA:
case 0x00DB:
case 0x00DC:
case 0x00DF:
case 0x00E0:
case 0x00E1:
case 0x00E2:
case 0x00E4:
case 0x00E5:
case 0x00E6:
case 0x00E7:
case 0x00E8:
case 0x00E9:
case 0x00EA:
case 0x00EB:
case 0x00ED:
case 0x00EE:
case 0x00EF:
case 0x00F1:
case 0x00F3:
case 0x00F4:
case 0x00F6:
case 0x00F7:
case 0x00F8:
case 0x00F9:
case 0x00FA:
case 0x00FB:
case 0x00FC:
case 0x00FF:
break;
case 0x0102: ch = 0xC3; break;
case 0x0103: ch = 0xE3; break;
case 0x0110: ch = 0xD0; break;
case 0x0111: ch = 0xF0; break;
case 0x0152: ch = 0x8C; break;
case 0x0153: ch = 0x9C; break;
case 0x0178: ch = 0x9F; break;
case 0x0192: ch = 0x83; break;
case 0x01A0: ch = 0xD5; break;
case 0x01A1: ch = 0xF5; break;
case 0x01AF: ch = 0xDD; break;
case 0x01B0: ch = 0xFD; break;
case 0x02C6: ch = 0x88; break;
case 0x02DC: ch = 0x98; break;
case 0x0300: ch = 0xCC; break;
case 0x0301: ch = 0xEC; break;
case 0x0303: ch = 0xDE; break;
case 0x0309: ch = 0xD2; break;
case 0x0323: ch = 0xF2; break;
case 0x2013: ch = 0x96; break;
case 0x2014: ch = 0x97; break;
case 0x2018: ch = 0x91; break;
case 0x2019: ch = 0x92; break;
case 0x201A: ch = 0x82; break;
case 0x201C: ch = 0x93; break;
case 0x201D: ch = 0x94; break;
case 0x201E: ch = 0x84; break;
case 0x2020: ch = 0x86; break;
case 0x2021: ch = 0x87; break;
case 0x2022: ch = 0x95; break;
case 0x2026: ch = 0x85; break;
case 0x2030: ch = 0x89; break;
case 0x2039: ch = 0x8B; break;
case 0x203A: ch = 0x9B; break;
case 0x20AB: ch = 0xFE; break;
case 0x20AC: ch = 0x80; break;
case 0x2122: ch = 0x99; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x0081:
case 0x008A:
case 0x008D:
case 0x008E:
case 0x008F:
case 0x0090:
case 0x009A:
case 0x009D:
case 0x009E:
case 0x00A0:
case 0x00A1:
case 0x00A2:
case 0x00A3:
case 0x00A4:
case 0x00A5:
case 0x00A6:
case 0x00A7:
case 0x00A8:
case 0x00A9:
case 0x00AA:
case 0x00AB:
case 0x00AC:
case 0x00AD:
case 0x00AE:
case 0x00AF:
case 0x00B0:
case 0x00B1:
case 0x00B2:
case 0x00B3:
case 0x00B4:
case 0x00B5:
case 0x00B6:
case 0x00B7:
case 0x00B8:
case 0x00B9:
case 0x00BA:
case 0x00BB:
case 0x00BC:
case 0x00BD:
case 0x00BE:
case 0x00BF:
case 0x00C0:
case 0x00C1:
case 0x00C2:
case 0x00C4:
case 0x00C5:
case 0x00C6:
case 0x00C7:
case 0x00C8:
case 0x00C9:
case 0x00CA:
case 0x00CB:
case 0x00CD:
case 0x00CE:
case 0x00CF:
case 0x00D1:
case 0x00D3:
case 0x00D4:
case 0x00D6:
case 0x00D7:
case 0x00D8:
case 0x00D9:
case 0x00DA:
case 0x00DB:
case 0x00DC:
case 0x00DF:
case 0x00E0:
case 0x00E1:
case 0x00E2:
case 0x00E4:
case 0x00E5:
case 0x00E6:
case 0x00E7:
case 0x00E8:
case 0x00E9:
case 0x00EA:
case 0x00EB:
case 0x00ED:
case 0x00EE:
case 0x00EF:
case 0x00F1:
case 0x00F3:
case 0x00F4:
case 0x00F6:
case 0x00F7:
case 0x00F8:
case 0x00F9:
case 0x00FA:
case 0x00FB:
case 0x00FC:
case 0x00FF:
break;
case 0x0102: ch = 0xC3; break;
case 0x0103: ch = 0xE3; break;
case 0x0110: ch = 0xD0; break;
case 0x0111: ch = 0xF0; break;
case 0x0152: ch = 0x8C; break;
case 0x0153: ch = 0x9C; break;
case 0x0178: ch = 0x9F; break;
case 0x0192: ch = 0x83; break;
case 0x01A0: ch = 0xD5; break;
case 0x01A1: ch = 0xF5; break;
case 0x01AF: ch = 0xDD; break;
case 0x01B0: ch = 0xFD; break;
case 0x02C6: ch = 0x88; break;
case 0x02DC: ch = 0x98; break;
case 0x0300: ch = 0xCC; break;
case 0x0301: ch = 0xEC; break;
case 0x0303: ch = 0xDE; break;
case 0x0309: ch = 0xD2; break;
case 0x0323: ch = 0xF2; break;
case 0x2013: ch = 0x96; break;
case 0x2014: ch = 0x97; break;
case 0x2018: ch = 0x91; break;
case 0x2019: ch = 0x92; break;
case 0x201A: ch = 0x82; break;
case 0x201C: ch = 0x93; break;
case 0x201D: ch = 0x94; break;
case 0x201E: ch = 0x84; break;
case 0x2020: ch = 0x86; break;
case 0x2021: ch = 0x87; break;
case 0x2022: ch = 0x95; break;
case 0x2026: ch = 0x85; break;
case 0x2030: ch = 0x89; break;
case 0x2039: ch = 0x8B; break;
case 0x203A: ch = 0x9B; break;
case 0x20AB: ch = 0xFE; break;
case 0x20AC: ch = 0x80; break;
case 0x2122: ch = 0x99; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP1258
public class ENCwindows_1258 : CP1258
{
public ENCwindows_1258() : base() {}
}; // class ENCwindows_1258
}; // namespace I18N.Other
| |
// 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.Linq.Expressions;
using Xunit;
namespace System.Linq.Tests
{
public class AverageTests : EnumerableBasedTests
{
[Fact]
public void NullNFloatSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<float?>)null).Average());
}
[Fact]
public void NullNFloatSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<float?>)null).Average(i => i));
}
[Fact]
public void NullNFloatFunc()
{
Expression<Func<float?, float?>> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float?>().AsQueryable().Average(selector));
}
[Fact]
public void MultipleNullableFloatSource()
{
float?[] source = { 5.5f, 0, null, null, null, 15.5f, 40.5f, null, null, -23.5f };
float? expected = 7.6f;
Assert.Equal(expected, source.AsQueryable().Average());
}
[Fact]
public void NullableFloatFromSelector()
{
var source = new []
{
new { name = "Tim", num = (float?)5.5f },
new { name = "John", num = (float?)15.5f },
new { name = "Bob", num = default(float?) }
};
float? expected = 10.5f;
Assert.Equal(expected, source.AsQueryable().Average(e => e.num));
}
[Fact]
public void NullIntSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<int>)null).Average());
}
[Fact]
public void NullIntSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<int>)null).Average(i => i));
}
[Fact]
public void NullIntFunc()
{
Expression<Func <int, int>> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int>().AsQueryable().Average(selector));
}
[Fact]
public void MultipleIntSouce()
{
int[] source = { 5, -10, 15, 40, 28 };
double expected = 15.6;
Assert.Equal(expected, source.AsQueryable().Average());
}
[Fact]
public void MultipleIntFromSelector()
{
var source = new []
{
new { name="Tim", num = 10 },
new { name="John", num = -10 },
new { name="Bob", num = 15 }
};
double expected = 5;
Assert.Equal(expected, source.AsQueryable().Average(e => e.num));
}
[Fact]
public void NullNIntSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<int?>)null).Average());
}
[Fact]
public void NullNIntSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<int?>)null).Average(i => i));
}
[Fact]
public void NullNIntFunc()
{
Expression<Func<int?, int?>> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int?>().AsQueryable().Average(selector));
}
[Fact]
public void MultipleNullableIntSource()
{
int?[] source = { 5, -10, null, null, null, 15, 40, 28, null, null };
double? expected = 15.6;
Assert.Equal(expected, source.AsQueryable().Average());
}
[Fact]
public void NullableIntFromSelector()
{
var source = new []
{
new { name = "Tim", num = (int?)10 },
new { name = "John", num = default(int?) },
new { name = "Bob", num = (int?)10 }
};
double? expected = 10;
Assert.Equal(expected, source.AsQueryable().Average(e => e.num));
}
[Fact]
public void NullLongSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<long>)null).Average());
}
[Fact]
public void NullLongSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<long>)null).Average(i => i));
}
[Fact]
public void NullLongFunc()
{
Expression<Func<long, long>> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long>().AsQueryable().Average(selector));
}
[Fact]
public void MultipleLongValues()
{
long[] source = { 5, -10, 15, 40, 28 };
double expected = 15.6;
Assert.Equal(expected, source.AsQueryable().Average());
}
[Fact]
public void MultipleLongFromSelector()
{
var source = new []
{
new { name = "Tim", num = 40L },
new { name = "John", num = 50L },
new { name = "Bob", num = 60L }
};
double expected = 50;
Assert.Equal(expected, source.AsQueryable().Average(e => e.num));
}
[Fact]
public void NullNLongSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<long?>)null).Average());
}
[Fact]
public void NullNLongSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<long?>)null).Average(i => i));
}
[Fact]
public void NullNLongFunc()
{
Expression<Func<long?, long?>> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long?>().AsQueryable().Average(selector));
}
[Fact]
public void MultipleNullableLongSource()
{
long?[] source = { 5, -10, null, null, null, 15, 40, 28, null, null };
double? expected = 15.6;
Assert.Equal(expected, source.AsQueryable().Average());
}
[Fact]
public void NullableLongFromSelector()
{
var source = new []
{
new { name = "Tim", num = (long?)40L },
new { name = "John", num = default(long?) },
new { name = "Bob", num = (long?)30L }
};
double? expected = 35;
Assert.Equal(expected, source.AsQueryable().Average(e => e.num));
}
[Fact]
public void NullDoubleSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<double>)null).Average());
}
[Fact]
public void NullDoubleSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<double>)null).Average(i => i));
}
[Fact]
public void NullDoubleFunc()
{
Expression<Func<double, double>> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double>().AsQueryable().Average(selector));
}
[Fact]
public void MultipleDoubleValues()
{
double[] source = { 5.5, -10, 15.5, 40.5, 28.5 };
double expected = 16;
Assert.Equal(expected, source.AsQueryable().Average());
}
[Fact]
public void MultipleDoubleFromSelector()
{
var source = new []
{
new { name = "Tim", num = 5.5},
new { name = "John", num = 15.5},
new { name = "Bob", num = 3.0}
};
double expected = 8.0;
Assert.Equal(expected, source.AsQueryable().Average(e => e.num));
}
[Fact]
public void NullNDoubleSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<double?>)null).Average());
}
[Fact]
public void NullNDoubleSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<double?>)null).Average(i => i));
}
[Fact]
public void NullNDoubleFunc()
{
Expression<Func<double?, double?>> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double?>().AsQueryable().Average(selector));
}
[Fact]
public void MultipleNullableDoubleSource()
{
double?[] source = { 5.5, 0, null, null, null, 15.5, 40.5, null, null, -23.5 };
double? expected = 7.6;
Assert.Equal(expected, source.AsQueryable().Average());
}
[Fact]
public void NullableDoubleFromSelector()
{
var source = new[]
{
new{ name = "Tim", num = (double?)5.5 },
new{ name = "John", num = (double?)15.5 },
new{ name = "Bob", num = default(double?) }
};
double? expected = 10.5;
Assert.Equal(expected, source.AsQueryable().Average(e => e.num));
}
[Fact]
public void NullDecimalSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal>)null).Average());
}
[Fact]
public void NullDecimalSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal>)null).Average(i => i));
}
[Fact]
public void NullDecimalFunc()
{
Expression<Func<decimal, decimal>> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal>().AsQueryable().Average(selector));
}
[Fact]
public void MultipleDecimalValues()
{
decimal[] source = { 5.5m, -10m, 15.5m, 40.5m, 28.5m };
decimal expected = 16m;
Assert.Equal(expected, source.AsQueryable().Average());
}
[Fact]
public void MultipleDecimalFromSelector()
{
var source = new[]
{
new{ name = "Tim", num = 5.5m},
new{ name = "John", num = 15.5m},
new{ name = "Bob", num = 3.0m}
};
decimal expected = 8.0m;
Assert.Equal(expected, source.AsQueryable().Average(e => e.num));
}
[Fact]
public void NullNDecimalSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal?>)null).Average());
}
[Fact]
public void NullNDecimalSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal?>)null).Average(i => i));
}
[Fact]
public void NullNDecimalFunc()
{
Expression<Func<decimal?, decimal?>> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal?>().AsQueryable().Average(selector));
}
[Fact]
public void MultipleNullableeDecimalSource()
{
decimal?[] source = { 5.5m, 0, null, null, null, 15.5m, 40.5m, null, null, -23.5m };
decimal? expected = 7.6m;
Assert.Equal(expected, source.AsQueryable().Average());
}
[Fact]
public void NullableDecimalFromSelector()
{
var source = new[]
{
new{ name = "Tim", num = (decimal?)5.5m},
new{ name = "John", num = (decimal?)15.5m},
new{ name = "Bob", num = (decimal?)null}
};
decimal? expected = 10.5m;
Assert.Equal(expected, source.AsQueryable().Average(e => e.num));
}
[Fact]
public void NullFloatSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<float>)null).Average());
}
[Fact]
public void NullFloatSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<float>)null).Average(i => i));
}
[Fact]
public void NullFloatFunc()
{
Expression<Func<float, float>> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float>().AsQueryable().Average(selector));
}
[Fact]
public void MultipleFloatValues()
{
float[] source = { 5.5f, -10f, 15.5f, 40.5f, 28.5f };
float expected = 16f;
Assert.Equal(expected, source.AsQueryable().Average());
}
[Fact]
public void MultipleFloatFromSelector()
{
var source = new[]
{
new{ name = "Tim", num = 5.5f},
new{ name = "John", num = 15.5f},
new{ name = "Bob", num = 3.0f}
};
float expected = 8.0f;
Assert.Equal(expected, source.AsQueryable().Average(e => e.num));
}
[Fact]
public void Average1()
{
var val = (new int[] { 0, 2, 1 }).AsQueryable().Average();
Assert.Equal((double)1, val);
}
[Fact]
public void Average2()
{
var val = (new int?[] { 0, 2, 1 }).AsQueryable().Average();
Assert.Equal((double)1, val);
}
[Fact]
public void Average3()
{
var val = (new long[] { 0, 2, 1 }).AsQueryable().Average();
Assert.Equal((double)1, val);
}
[Fact]
public void Average4()
{
var val = (new long?[] { 0, 2, 1 }).AsQueryable().Average();
Assert.Equal((double)1, val);
}
[Fact]
public void Average5()
{
var val = (new float[] { 0, 2, 1 }).AsQueryable().Average();
Assert.Equal((float)1, val);
}
[Fact]
public void Average6()
{
var val = (new float?[] { 0, 2, 1 }).AsQueryable().Average();
Assert.Equal((float)1, val);
}
[Fact]
public void Average7()
{
var val = (new double[] { 0, 2, 1 }).AsQueryable().Average();
Assert.Equal((double)1, val);
}
[Fact]
public void Average8()
{
var val = (new double?[] { 0, 2, 1 }).AsQueryable().Average();
Assert.Equal((double)1, val);
}
[Fact]
public void Average9()
{
var val = (new decimal[] { 0, 2, 1 }).AsQueryable().Average();
Assert.Equal((decimal)1, val);
}
[Fact]
public void Average10()
{
var val = (new decimal?[] { 0, 2, 1 }).AsQueryable().Average();
Assert.Equal((decimal)1, val);
}
[Fact]
public void Average11()
{
var val = (new int[] { 0, 2, 1 }).AsQueryable().Average(n => n);
Assert.Equal((double)1, val);
}
[Fact]
public void Average12()
{
var val = (new int?[] { 0, 2, 1 }).AsQueryable().Average(n => n);
Assert.Equal((double)1, val);
}
[Fact]
public void Average13()
{
var val = (new long[] { 0, 2, 1 }).AsQueryable().Average(n => n);
Assert.Equal((double)1, val);
}
[Fact]
public void Average14()
{
var val = (new long?[] { 0, 2, 1 }).AsQueryable().Average(n => n);
Assert.Equal((double)1, val);
}
[Fact]
public void Average15()
{
var val = (new float[] { 0, 2, 1 }).AsQueryable().Average(n => n);
Assert.Equal((float)1, val);
}
[Fact]
public void Average16()
{
var val = (new float?[] { 0, 2, 1 }).AsQueryable().Average(n => n);
Assert.Equal((float)1, val);
}
[Fact]
public void Average17()
{
var val = (new double[] { 0, 2, 1 }).AsQueryable().Average(n => n);
Assert.Equal((double)1, val);
}
[Fact]
public void Average18()
{
var val = (new double?[] { 0, 2, 1 }).AsQueryable().Average(n => n);
Assert.Equal((double)1, val);
}
[Fact]
public void Average19()
{
var val = (new decimal[] { 0, 2, 1 }).AsQueryable().Average(n => n);
Assert.Equal((decimal)1, val);
}
[Fact]
public void Average20()
{
var val = (new decimal?[] { 0, 2, 1 }).AsQueryable().Average(n => n);
Assert.Equal((decimal)1, val);
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Xml
{
public enum ConformanceLevel
{
Auto = 0,
Document = 2,
Fragment = 1,
}
public enum DtdProcessing
{
Ignore = 1,
Prohibit = 0,
}
public partial interface IXmlLineInfo
{
int LineNumber { get; }
int LinePosition { get; }
bool HasLineInfo();
}
public partial interface IXmlNamespaceResolver
{
System.Collections.Generic.IDictionary<string, string> GetNamespacesInScope(System.Xml.XmlNamespaceScope scope);
string LookupNamespace(string prefix);
string LookupPrefix(string namespaceName);
}
[System.FlagsAttribute]
public enum NamespaceHandling
{
Default = 0,
OmitDuplicates = 1,
}
public partial class NameTable : System.Xml.XmlNameTable
{
public NameTable() { }
public override string Add(char[] key, int start, int len) { return default(string); }
public override string Add(string key) { return default(string); }
public override string Get(char[] key, int start, int len) { return default(string); }
public override string Get(string value) { return default(string); }
}
public enum NewLineHandling
{
Entitize = 1,
None = 2,
Replace = 0,
}
public enum ReadState
{
Closed = 4,
EndOfFile = 3,
Error = 2,
Initial = 0,
Interactive = 1,
}
public enum WriteState
{
Attribute = 3,
Closed = 5,
Content = 4,
Element = 2,
Error = 6,
Prolog = 1,
Start = 0,
}
public static partial class XmlConvert
{
public static string DecodeName(string name) { return default(string); }
public static string EncodeLocalName(string name) { return default(string); }
public static string EncodeName(string name) { return default(string); }
public static string EncodeNmToken(string name) { return default(string); }
public static bool ToBoolean(string s) { return default(bool); }
public static byte ToByte(string s) { return default(byte); }
public static char ToChar(string s) { return default(char); }
public static System.DateTime ToDateTime(string s, System.Xml.XmlDateTimeSerializationMode dateTimeOption) { return default(System.DateTime); }
public static System.DateTimeOffset ToDateTimeOffset(string s) { return default(System.DateTimeOffset); }
public static System.DateTimeOffset ToDateTimeOffset(string s, string format) { return default(System.DateTimeOffset); }
public static System.DateTimeOffset ToDateTimeOffset(string s, string[] formats) { return default(System.DateTimeOffset); }
public static decimal ToDecimal(string s) { return default(decimal); }
public static double ToDouble(string s) { return default(double); }
public static System.Guid ToGuid(string s) { return default(System.Guid); }
public static short ToInt16(string s) { return default(short); }
public static int ToInt32(string s) { return default(int); }
public static long ToInt64(string s) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string s) { return default(sbyte); }
public static float ToSingle(string s) { return default(float); }
public static string ToString(bool value) { return default(string); }
public static string ToString(byte value) { return default(string); }
public static string ToString(char value) { return default(string); }
public static string ToString(System.DateTime value, System.Xml.XmlDateTimeSerializationMode dateTimeOption) { return default(string); }
public static string ToString(System.DateTimeOffset value) { return default(string); }
public static string ToString(System.DateTimeOffset value, string format) { return default(string); }
public static string ToString(decimal value) { return default(string); }
public static string ToString(double value) { return default(string); }
public static string ToString(System.Guid value) { return default(string); }
public static string ToString(short value) { return default(string); }
public static string ToString(int value) { return default(string); }
public static string ToString(long value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(sbyte value) { return default(string); }
public static string ToString(float value) { return default(string); }
public static string ToString(System.TimeSpan value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ushort value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(uint value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ulong value) { return default(string); }
public static System.TimeSpan ToTimeSpan(string s) { return default(System.TimeSpan); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(string s) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(string s) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(string s) { return default(ulong); }
public static string VerifyName(string name) { return default(string); }
public static string VerifyNCName(string name) { return default(string); }
public static string VerifyNMTOKEN(string name) { return default(string); }
public static string VerifyPublicId(string publicId) { return default(string); }
public static string VerifyWhitespace(string content) { return default(string); }
public static string VerifyXmlChars(string content) { return default(string); }
}
public enum XmlDateTimeSerializationMode
{
Local = 0,
RoundtripKind = 3,
Unspecified = 2,
Utc = 1,
}
public partial class XmlException : System.Exception
{
public XmlException() { }
public XmlException(string message) { }
public XmlException(string message, System.Exception innerException) { }
public XmlException(string message, System.Exception innerException, int lineNumber, int linePosition) { }
public int LineNumber { get { return default(int); } }
public int LinePosition { get { return default(int); } }
public override string Message { get { return default(string); } }
}
public partial class XmlNamespaceManager : System.Collections.IEnumerable, System.Xml.IXmlNamespaceResolver
{
public XmlNamespaceManager(System.Xml.XmlNameTable nameTable) { }
public virtual string DefaultNamespace { get { return default(string); } }
public virtual System.Xml.XmlNameTable NameTable { get { return default(System.Xml.XmlNameTable); } }
public virtual void AddNamespace(string prefix, string uri) { }
public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
public virtual System.Collections.Generic.IDictionary<string, string> GetNamespacesInScope(System.Xml.XmlNamespaceScope scope) { return default(System.Collections.Generic.IDictionary<string, string>); }
public virtual bool HasNamespace(string prefix) { return default(bool); }
public virtual string LookupNamespace(string prefix) { return default(string); }
public virtual string LookupPrefix(string uri) { return default(string); }
public virtual bool PopScope() { return default(bool); }
public virtual void PushScope() { }
public virtual void RemoveNamespace(string prefix, string uri) { }
}
public enum XmlNamespaceScope
{
All = 0,
ExcludeXml = 1,
Local = 2,
}
public abstract partial class XmlNameTable
{
protected XmlNameTable() { }
public abstract string Add(char[] array, int offset, int length);
public abstract string Add(string array);
public abstract string Get(char[] array, int offset, int length);
public abstract string Get(string array);
}
public enum XmlNodeType
{
Attribute = 2,
CDATA = 4,
Comment = 8,
Document = 9,
DocumentFragment = 11,
DocumentType = 10,
Element = 1,
EndElement = 15,
EndEntity = 16,
Entity = 6,
EntityReference = 5,
None = 0,
Notation = 12,
ProcessingInstruction = 7,
SignificantWhitespace = 14,
Text = 3,
Whitespace = 13,
XmlDeclaration = 17,
}
public partial class XmlParserContext
{
public XmlParserContext(System.Xml.XmlNameTable nt, System.Xml.XmlNamespaceManager nsMgr, string docTypeName, string pubId, string sysId, string internalSubset, string baseURI, string xmlLang, System.Xml.XmlSpace xmlSpace) { }
public XmlParserContext(System.Xml.XmlNameTable nt, System.Xml.XmlNamespaceManager nsMgr, string docTypeName, string pubId, string sysId, string internalSubset, string baseURI, string xmlLang, System.Xml.XmlSpace xmlSpace, System.Text.Encoding enc) { }
public XmlParserContext(System.Xml.XmlNameTable nt, System.Xml.XmlNamespaceManager nsMgr, string xmlLang, System.Xml.XmlSpace xmlSpace) { }
public XmlParserContext(System.Xml.XmlNameTable nt, System.Xml.XmlNamespaceManager nsMgr, string xmlLang, System.Xml.XmlSpace xmlSpace, System.Text.Encoding enc) { }
public string BaseURI { get { return default(string); } set { } }
public string DocTypeName { get { return default(string); } set { } }
public System.Text.Encoding Encoding { get { return default(System.Text.Encoding); } set { } }
public string InternalSubset { get { return default(string); } set { } }
public System.Xml.XmlNamespaceManager NamespaceManager { get { return default(System.Xml.XmlNamespaceManager); } set { } }
public System.Xml.XmlNameTable NameTable { get { return default(System.Xml.XmlNameTable); } set { } }
public string PublicId { get { return default(string); } set { } }
public string SystemId { get { return default(string); } set { } }
public string XmlLang { get { return default(string); } set { } }
public System.Xml.XmlSpace XmlSpace { get { return default(System.Xml.XmlSpace); } set { } }
}
public partial class XmlQualifiedName
{
public static readonly System.Xml.XmlQualifiedName Empty;
public XmlQualifiedName() { }
public XmlQualifiedName(string name) { }
public XmlQualifiedName(string name, string ns) { }
public bool IsEmpty { get { return default(bool); } }
public string Name { get { return default(string); } }
public string Namespace { get { return default(string); } }
public override bool Equals(object other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Xml.XmlQualifiedName a, System.Xml.XmlQualifiedName b) { return default(bool); }
public static bool operator !=(System.Xml.XmlQualifiedName a, System.Xml.XmlQualifiedName b) { return default(bool); }
public override string ToString() { return default(string); }
public static string ToString(string name, string ns) { return default(string); }
}
public abstract partial class XmlReader : System.IDisposable
{
protected XmlReader() { }
public abstract int AttributeCount { get; }
public abstract string BaseURI { get; }
public virtual bool CanReadBinaryContent { get { return default(bool); } }
public virtual bool CanReadValueChunk { get { return default(bool); } }
public virtual bool CanResolveEntity { get { return default(bool); } }
public abstract int Depth { get; }
public abstract bool EOF { get; }
public virtual bool HasAttributes { get { return default(bool); } }
public virtual bool HasValue { get { return default(bool); } }
public virtual bool IsDefault { get { return default(bool); } }
public abstract bool IsEmptyElement { get; }
public virtual string this[int i] { get { return default(string); } }
public virtual string this[string name] { get { return default(string); } }
public virtual string this[string name, string namespaceURI] { get { return default(string); } }
public abstract string LocalName { get; }
public virtual string Name { get { return default(string); } }
public abstract string NamespaceURI { get; }
public abstract System.Xml.XmlNameTable NameTable { get; }
public abstract System.Xml.XmlNodeType NodeType { get; }
public abstract string Prefix { get; }
public abstract System.Xml.ReadState ReadState { get; }
public virtual System.Xml.XmlReaderSettings Settings { get { return default(System.Xml.XmlReaderSettings); } }
public abstract string Value { get; }
public virtual System.Type ValueType { get { return default(System.Type); } }
public virtual string XmlLang { get { return default(string); } }
public virtual System.Xml.XmlSpace XmlSpace { get { return default(System.Xml.XmlSpace); } }
public static System.Xml.XmlReader Create(System.IO.Stream input) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(System.IO.Stream input, System.Xml.XmlReaderSettings settings) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(System.IO.Stream input, System.Xml.XmlReaderSettings settings, System.Xml.XmlParserContext inputContext) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(System.IO.TextReader input) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(System.IO.TextReader input, System.Xml.XmlReaderSettings settings) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(System.IO.TextReader input, System.Xml.XmlReaderSettings settings, System.Xml.XmlParserContext inputContext) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(string inputUri) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(string inputUri, System.Xml.XmlReaderSettings settings) { return default(System.Xml.XmlReader); }
public static System.Xml.XmlReader Create(System.Xml.XmlReader reader, System.Xml.XmlReaderSettings settings) { return default(System.Xml.XmlReader); }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract string GetAttribute(int i);
public abstract string GetAttribute(string name);
public abstract string GetAttribute(string name, string namespaceURI);
public virtual System.Threading.Tasks.Task<string> GetValueAsync() { return default(System.Threading.Tasks.Task<string>); }
public static bool IsName(string str) { return default(bool); }
public static bool IsNameToken(string str) { return default(bool); }
public virtual bool IsStartElement() { return default(bool); }
public virtual bool IsStartElement(string name) { return default(bool); }
public virtual bool IsStartElement(string localname, string ns) { return default(bool); }
public abstract string LookupNamespace(string prefix);
public virtual void MoveToAttribute(int i) { }
public abstract bool MoveToAttribute(string name);
public abstract bool MoveToAttribute(string name, string ns);
public virtual System.Xml.XmlNodeType MoveToContent() { return default(System.Xml.XmlNodeType); }
public virtual System.Threading.Tasks.Task<System.Xml.XmlNodeType> MoveToContentAsync() { return default(System.Threading.Tasks.Task<System.Xml.XmlNodeType>); }
public abstract bool MoveToElement();
public abstract bool MoveToFirstAttribute();
public abstract bool MoveToNextAttribute();
public abstract bool Read();
public virtual System.Threading.Tasks.Task<bool> ReadAsync() { return default(System.Threading.Tasks.Task<bool>); }
public abstract bool ReadAttributeValue();
public virtual object ReadContentAs(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver) { return default(object); }
public virtual System.Threading.Tasks.Task<object> ReadContentAsAsync(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver) { return default(System.Threading.Tasks.Task<object>); }
public virtual int ReadContentAsBase64(byte[] buffer, int index, int count) { return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual int ReadContentAsBinHex(byte[] buffer, int index, int count) { return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual bool ReadContentAsBoolean() { return default(bool); }
public virtual System.DateTimeOffset ReadContentAsDateTimeOffset() { return default(System.DateTimeOffset); }
public virtual decimal ReadContentAsDecimal() { return default(decimal); }
public virtual double ReadContentAsDouble() { return default(double); }
public virtual float ReadContentAsFloat() { return default(float); }
public virtual int ReadContentAsInt() { return default(int); }
public virtual long ReadContentAsLong() { return default(long); }
public virtual object ReadContentAsObject() { return default(object); }
public virtual System.Threading.Tasks.Task<object> ReadContentAsObjectAsync() { return default(System.Threading.Tasks.Task<object>); }
public virtual string ReadContentAsString() { return default(string); }
public virtual System.Threading.Tasks.Task<string> ReadContentAsStringAsync() { return default(System.Threading.Tasks.Task<string>); }
public virtual object ReadElementContentAs(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver) { return default(object); }
public virtual object ReadElementContentAs(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver, string localName, string namespaceURI) { return default(object); }
public virtual System.Threading.Tasks.Task<object> ReadElementContentAsAsync(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver) { return default(System.Threading.Tasks.Task<object>); }
public virtual int ReadElementContentAsBase64(byte[] buffer, int index, int count) { return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public virtual bool ReadElementContentAsBoolean() { return default(bool); }
public virtual bool ReadElementContentAsBoolean(string localName, string namespaceURI) { return default(bool); }
public virtual decimal ReadElementContentAsDecimal() { return default(decimal); }
public virtual decimal ReadElementContentAsDecimal(string localName, string namespaceURI) { return default(decimal); }
public virtual double ReadElementContentAsDouble() { return default(double); }
public virtual double ReadElementContentAsDouble(string localName, string namespaceURI) { return default(double); }
public virtual float ReadElementContentAsFloat() { return default(float); }
public virtual float ReadElementContentAsFloat(string localName, string namespaceURI) { return default(float); }
public virtual int ReadElementContentAsInt() { return default(int); }
public virtual int ReadElementContentAsInt(string localName, string namespaceURI) { return default(int); }
public virtual long ReadElementContentAsLong() { return default(long); }
public virtual long ReadElementContentAsLong(string localName, string namespaceURI) { return default(long); }
public virtual object ReadElementContentAsObject() { return default(object); }
public virtual object ReadElementContentAsObject(string localName, string namespaceURI) { return default(object); }
public virtual System.Threading.Tasks.Task<object> ReadElementContentAsObjectAsync() { return default(System.Threading.Tasks.Task<object>); }
public virtual string ReadElementContentAsString() { return default(string); }
public virtual string ReadElementContentAsString(string localName, string namespaceURI) { return default(string); }
public virtual System.Threading.Tasks.Task<string> ReadElementContentAsStringAsync() { return default(System.Threading.Tasks.Task<string>); }
public virtual void ReadEndElement() { }
public virtual string ReadInnerXml() { return default(string); }
public virtual System.Threading.Tasks.Task<string> ReadInnerXmlAsync() { return default(System.Threading.Tasks.Task<string>); }
public virtual string ReadOuterXml() { return default(string); }
public virtual System.Threading.Tasks.Task<string> ReadOuterXmlAsync() { return default(System.Threading.Tasks.Task<string>); }
public virtual void ReadStartElement() { }
public virtual void ReadStartElement(string name) { }
public virtual void ReadStartElement(string localname, string ns) { }
public virtual System.Xml.XmlReader ReadSubtree() { return default(System.Xml.XmlReader); }
public virtual bool ReadToDescendant(string name) { return default(bool); }
public virtual bool ReadToDescendant(string localName, string namespaceURI) { return default(bool); }
public virtual bool ReadToFollowing(string name) { return default(bool); }
public virtual bool ReadToFollowing(string localName, string namespaceURI) { return default(bool); }
public virtual bool ReadToNextSibling(string name) { return default(bool); }
public virtual bool ReadToNextSibling(string localName, string namespaceURI) { return default(bool); }
public virtual int ReadValueChunk(char[] buffer, int index, int count) { return default(int); }
public virtual System.Threading.Tasks.Task<int> ReadValueChunkAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); }
public abstract void ResolveEntity();
public virtual void Skip() { }
public virtual System.Threading.Tasks.Task SkipAsync() { return default(System.Threading.Tasks.Task); }
}
public sealed partial class XmlReaderSettings
{
public XmlReaderSettings() { }
public bool Async { get { return default(bool); } set { } }
public bool CheckCharacters { get { return default(bool); } set { } }
public bool CloseInput { get { return default(bool); } set { } }
public System.Xml.ConformanceLevel ConformanceLevel { get { return default(System.Xml.ConformanceLevel); } set { } }
public System.Xml.DtdProcessing DtdProcessing { get { return default(System.Xml.DtdProcessing); } set { } }
public bool IgnoreComments { get { return default(bool); } set { } }
public bool IgnoreProcessingInstructions { get { return default(bool); } set { } }
public bool IgnoreWhitespace { get { return default(bool); } set { } }
public int LineNumberOffset { get { return default(int); } set { } }
public int LinePositionOffset { get { return default(int); } set { } }
public long MaxCharactersFromEntities { get { return default(long); } set { } }
public long MaxCharactersInDocument { get { return default(long); } set { } }
public System.Xml.XmlNameTable NameTable { get { return default(System.Xml.XmlNameTable); } set { } }
public System.Xml.XmlReaderSettings Clone() { return default(System.Xml.XmlReaderSettings); }
public void Reset() { }
}
public enum XmlSpace
{
Default = 1,
None = 0,
Preserve = 2,
}
public abstract partial class XmlWriter : System.IDisposable
{
protected XmlWriter() { }
public virtual System.Xml.XmlWriterSettings Settings { get { return default(System.Xml.XmlWriterSettings); } }
public abstract System.Xml.WriteState WriteState { get; }
public virtual string XmlLang { get { return default(string); } }
public virtual System.Xml.XmlSpace XmlSpace { get { return default(System.Xml.XmlSpace); } }
public static System.Xml.XmlWriter Create(System.IO.Stream output) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.IO.Stream output, System.Xml.XmlWriterSettings settings) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.IO.TextWriter output) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.IO.TextWriter output, System.Xml.XmlWriterSettings settings) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.Text.StringBuilder output) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.Text.StringBuilder output, System.Xml.XmlWriterSettings settings) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.Xml.XmlWriter output) { return default(System.Xml.XmlWriter); }
public static System.Xml.XmlWriter Create(System.Xml.XmlWriter output, System.Xml.XmlWriterSettings settings) { return default(System.Xml.XmlWriter); }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract void Flush();
public virtual System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); }
public abstract string LookupPrefix(string ns);
public virtual void WriteAttributes(System.Xml.XmlReader reader, bool defattr) { }
public virtual System.Threading.Tasks.Task WriteAttributesAsync(System.Xml.XmlReader reader, bool defattr) { return default(System.Threading.Tasks.Task); }
public void WriteAttributeString(string localName, string value) { }
public void WriteAttributeString(string localName, string ns, string value) { }
public void WriteAttributeString(string prefix, string localName, string ns, string value) { }
public System.Threading.Tasks.Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value) { return default(System.Threading.Tasks.Task); }
public abstract void WriteBase64(byte[] buffer, int index, int count);
public virtual System.Threading.Tasks.Task WriteBase64Async(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public virtual void WriteBinHex(byte[] buffer, int index, int count) { }
public virtual System.Threading.Tasks.Task WriteBinHexAsync(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public abstract void WriteCData(string text);
public virtual System.Threading.Tasks.Task WriteCDataAsync(string text) { return default(System.Threading.Tasks.Task); }
public abstract void WriteCharEntity(char ch);
public virtual System.Threading.Tasks.Task WriteCharEntityAsync(char ch) { return default(System.Threading.Tasks.Task); }
public abstract void WriteChars(char[] buffer, int index, int count);
public virtual System.Threading.Tasks.Task WriteCharsAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public abstract void WriteComment(string text);
public virtual System.Threading.Tasks.Task WriteCommentAsync(string text) { return default(System.Threading.Tasks.Task); }
public abstract void WriteDocType(string name, string pubid, string sysid, string subset);
public virtual System.Threading.Tasks.Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { return default(System.Threading.Tasks.Task); }
public void WriteElementString(string localName, string value) { }
public void WriteElementString(string localName, string ns, string value) { }
public void WriteElementString(string prefix, string localName, string ns, string value) { }
public System.Threading.Tasks.Task WriteElementStringAsync(string prefix, string localName, string ns, string value) { return default(System.Threading.Tasks.Task); }
public abstract void WriteEndAttribute();
protected internal virtual System.Threading.Tasks.Task WriteEndAttributeAsync() { return default(System.Threading.Tasks.Task); }
public abstract void WriteEndDocument();
public virtual System.Threading.Tasks.Task WriteEndDocumentAsync() { return default(System.Threading.Tasks.Task); }
public abstract void WriteEndElement();
public virtual System.Threading.Tasks.Task WriteEndElementAsync() { return default(System.Threading.Tasks.Task); }
public abstract void WriteEntityRef(string name);
public virtual System.Threading.Tasks.Task WriteEntityRefAsync(string name) { return default(System.Threading.Tasks.Task); }
public abstract void WriteFullEndElement();
public virtual System.Threading.Tasks.Task WriteFullEndElementAsync() { return default(System.Threading.Tasks.Task); }
public virtual void WriteName(string name) { }
public virtual System.Threading.Tasks.Task WriteNameAsync(string name) { return default(System.Threading.Tasks.Task); }
public virtual void WriteNmToken(string name) { }
public virtual System.Threading.Tasks.Task WriteNmTokenAsync(string name) { return default(System.Threading.Tasks.Task); }
public virtual void WriteNode(System.Xml.XmlReader reader, bool defattr) { }
public virtual System.Threading.Tasks.Task WriteNodeAsync(System.Xml.XmlReader reader, bool defattr) { return default(System.Threading.Tasks.Task); }
public abstract void WriteProcessingInstruction(string name, string text);
public virtual System.Threading.Tasks.Task WriteProcessingInstructionAsync(string name, string text) { return default(System.Threading.Tasks.Task); }
public virtual void WriteQualifiedName(string localName, string ns) { }
public virtual System.Threading.Tasks.Task WriteQualifiedNameAsync(string localName, string ns) { return default(System.Threading.Tasks.Task); }
public abstract void WriteRaw(char[] buffer, int index, int count);
public abstract void WriteRaw(string data);
public virtual System.Threading.Tasks.Task WriteRawAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteRawAsync(string data) { return default(System.Threading.Tasks.Task); }
public void WriteStartAttribute(string localName) { }
public void WriteStartAttribute(string localName, string ns) { }
public abstract void WriteStartAttribute(string prefix, string localName, string ns);
protected internal virtual System.Threading.Tasks.Task WriteStartAttributeAsync(string prefix, string localName, string ns) { return default(System.Threading.Tasks.Task); }
public abstract void WriteStartDocument();
public abstract void WriteStartDocument(bool standalone);
public virtual System.Threading.Tasks.Task WriteStartDocumentAsync() { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task WriteStartDocumentAsync(bool standalone) { return default(System.Threading.Tasks.Task); }
public void WriteStartElement(string localName) { }
public void WriteStartElement(string localName, string ns) { }
public abstract void WriteStartElement(string prefix, string localName, string ns);
public virtual System.Threading.Tasks.Task WriteStartElementAsync(string prefix, string localName, string ns) { return default(System.Threading.Tasks.Task); }
public abstract void WriteString(string text);
public virtual System.Threading.Tasks.Task WriteStringAsync(string text) { return default(System.Threading.Tasks.Task); }
public abstract void WriteSurrogateCharEntity(char lowChar, char highChar);
public virtual System.Threading.Tasks.Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { return default(System.Threading.Tasks.Task); }
public virtual void WriteValue(bool value) { }
public virtual void WriteValue(System.DateTime value) { }
public virtual void WriteValue(System.DateTimeOffset value) { }
public virtual void WriteValue(decimal value) { }
public virtual void WriteValue(double value) { }
public virtual void WriteValue(int value) { }
public virtual void WriteValue(long value) { }
public virtual void WriteValue(object value) { }
public virtual void WriteValue(float value) { }
public virtual void WriteValue(string value) { }
public abstract void WriteWhitespace(string ws);
public virtual System.Threading.Tasks.Task WriteWhitespaceAsync(string ws) { return default(System.Threading.Tasks.Task); }
}
public sealed partial class XmlWriterSettings
{
public XmlWriterSettings() { }
public bool Async { get { return default(bool); } set { } }
public bool CheckCharacters { get { return default(bool); } set { } }
public bool CloseOutput { get { return default(bool); } set { } }
public System.Xml.ConformanceLevel ConformanceLevel { get { return default(System.Xml.ConformanceLevel); } set { } }
public System.Text.Encoding Encoding { get { return default(System.Text.Encoding); } set { } }
public bool Indent { get { return default(bool); } set { } }
public string IndentChars { get { return default(string); } set { } }
public System.Xml.NamespaceHandling NamespaceHandling { get { return default(System.Xml.NamespaceHandling); } set { } }
public string NewLineChars { get { return default(string); } set { } }
public System.Xml.NewLineHandling NewLineHandling { get { return default(System.Xml.NewLineHandling); } set { } }
public bool NewLineOnAttributes { get { return default(bool); } set { } }
public bool OmitXmlDeclaration { get { return default(bool); } set { } }
public bool WriteEndDocumentOnClose { get { return default(bool); } set { } }
public System.Xml.XmlWriterSettings Clone() { return default(System.Xml.XmlWriterSettings); }
public void Reset() { }
}
}
namespace System.Xml.Schema
{
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
public partial class XmlSchema
{
internal XmlSchema() { }
}
public enum XmlSchemaForm
{
None = 0,
Qualified = 1,
Unqualified = 2,
}
}
namespace System.Xml.Serialization
{
public partial interface IXmlSerializable
{
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
System.Xml.Schema.XmlSchema GetSchema();
void ReadXml(System.Xml.XmlReader reader);
void WriteXml(System.Xml.XmlWriter writer);
}
[System.AttributeUsageAttribute((System.AttributeTargets)(1036))]
public sealed partial class XmlSchemaProviderAttribute : System.Attribute
{
public XmlSchemaProviderAttribute(string methodName) { }
public bool IsAny { get { return default(bool); } set { } }
public string MethodName { get { return default(string); } }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics.Contracts;
namespace System.Drawing
{
/// <summary>
/// <para>
/// Stores the location and size of a rectangular region.
/// </para>
/// </summary>
public struct Rectangle
{
public static readonly Rectangle Empty = new Rectangle();
private int _x;
private int _y;
private int _width;
private int _height;
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.Drawing.Rectangle'/>
/// class with the specified location and size.
/// </para>
/// </summary>
public Rectangle(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
/// <summary>
/// <para>
/// Initializes a new instance of the Rectangle class with the specified location
/// and size.
/// </para>
/// </summary>
public Rectangle(Point location, Size size)
{
_x = location.X;
_y = location.Y;
_width = size.Width;
_height = size.Height;
}
/// <summary>
/// Creates a new <see cref='System.Drawing.Rectangle'/> with
/// the specified location and size.
/// </summary>
public static Rectangle FromLTRB(int left, int top, int right, int bottom)
{
return new Rectangle(left,
top,
right - left,
bottom - top);
}
/// <summary>
/// <para>
/// Gets or sets the coordinates of the
/// upper-left corner of the rectangular region represented by this <see cref='System.Drawing.Rectangle'/>.
/// </para>
/// </summary>
public Point Location
{
get
{
return new Point(X, Y);
}
set
{
X = value.X;
Y = value.Y;
}
}
/// <summary>
/// Gets or sets the size of this <see cref='System.Drawing.Rectangle'/>.
/// </summary>
public Size Size
{
get
{
return new Size(Width, Height);
}
set
{
Width = value.Width;
Height = value.Height;
}
}
/// <summary>
/// Gets or sets the x-coordinate of the
/// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </summary>
public int X
{
get
{
return _x;
}
set
{
_x = value;
}
}
/// <summary>
/// Gets or sets the y-coordinate of the
/// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </summary>
public int Y
{
get
{
return _y;
}
set
{
_y = value;
}
}
/// <summary>
/// Gets or sets the width of the rectangular
/// region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </summary>
public int Width
{
get
{
return _width;
}
set
{
_width = value;
}
}
/// <summary>
/// Gets or sets the width of the rectangular
/// region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </summary>
public int Height
{
get
{
return _height;
}
set
{
_height = value;
}
}
/// <summary>
/// <para>
/// Gets the x-coordinate of the upper-left corner of the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> .
/// </para>
/// </summary>
public int Left
{
get
{
return X;
}
}
/// <summary>
/// <para>
/// Gets the y-coordinate of the upper-left corner of the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </para>
/// </summary>
public int Top
{
get
{
return Y;
}
}
/// <summary>
/// <para>
/// Gets the x-coordinate of the lower-right corner of the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </para>
/// </summary>
public int Right
{
get
{
return X + Width;
}
}
/// <summary>
/// <para>
/// Gets the y-coordinate of the lower-right corner of the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/>.
/// </para>
/// </summary>
public int Bottom
{
get
{
return Y + Height;
}
}
/// <summary>
/// <para>
/// Tests whether this <see cref='System.Drawing.Rectangle'/> has a <see cref='System.Drawing.Rectangle.Width'/>
/// or a <see cref='System.Drawing.Rectangle.Height'/> of 0.
/// </para>
/// </summary>
public bool IsEmpty
{
get
{
return _height == 0 && _width == 0 && _x == 0 && _y == 0;
}
}
/// <summary>
/// <para>
/// Tests whether <paramref name="obj"/> is a <see cref='System.Drawing.Rectangle'/> with
/// the same location and size of this Rectangle.
/// </para>
/// </summary>
public override bool Equals(object obj)
{
if (!(obj is Rectangle))
return false;
Rectangle comp = (Rectangle)obj;
return (comp.X == X) && (comp.Y == Y) && (comp.Width == Width) && (comp.Height == Height);
}
/// <summary>
/// <para>
/// Tests whether two <see cref='System.Drawing.Rectangle'/>
/// objects have equal location and size.
/// </para>
/// </summary>
public static bool operator ==(Rectangle left, Rectangle right)
{
return (left.X == right.X && left.Y == right.Y &&
left.Width == right.Width && left.Height == right.Height);
}
/// <summary>
/// <para>
/// Tests whether two <see cref='System.Drawing.Rectangle'/>
/// objects differ in location or size.
/// </para>
/// </summary>
public static bool operator !=(Rectangle left, Rectangle right)
{
return !(left == right);
}
/// <summary>
/// Converts a RectangleF to a Rectangle by performing a ceiling operation on
/// all the coordinates.
/// </summary>
public static Rectangle Ceiling(RectangleF value)
{
return new Rectangle((int)Math.Ceiling(value.X),
(int)Math.Ceiling(value.Y),
(int)Math.Ceiling(value.Width),
(int)Math.Ceiling(value.Height));
}
/// <summary>
/// Converts a RectangleF to a Rectangle by performing a truncate operation on
/// all the coordinates.
/// </summary>
public static Rectangle Truncate(RectangleF value)
{
return new Rectangle((int)value.X,
(int)value.Y,
(int)value.Width,
(int)value.Height);
}
/// <summary>
/// Converts a RectangleF to a Rectangle by performing a round operation on
/// all the coordinates.
/// </summary>
public static Rectangle Round(RectangleF value)
{
return new Rectangle((int)Math.Round(value.X),
(int)Math.Round(value.Y),
(int)Math.Round(value.Width),
(int)Math.Round(value.Height));
}
/// <summary>
/// <para>
/// Determines if the specfied point is contained within the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> .
/// </para>
/// </summary>
[Pure]
public bool Contains(int x, int y)
{
return X <= x && x < X + Width && Y <= y && y < Y + Height;
}
/// <summary>
/// <para>
/// Determines if the specfied point is contained within the
/// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> .
/// </para>
/// </summary>
[Pure]
public bool Contains(Point pt)
{
return Contains(pt.X, pt.Y);
}
/// <summary>
/// <para>
/// Determines if the rectangular region represented by
/// <paramref name="rect"/> is entirely contained within the rectangular region represented by
/// this <see cref='System.Drawing.Rectangle'/> .
/// </para>
/// </summary>
[Pure]
public bool Contains(Rectangle rect)
{
return (X <= rect.X) && ((rect.X + rect.Width) <= (X + Width)) &&
(Y <= rect.Y) && ((rect.Y + rect.Height) <= (Y + Height));
}
public override int GetHashCode()
{
return (int)((uint)X ^ (((uint)Y << 13) | ((uint)Y >> 19)) ^
(((uint)Width << 26) | ((uint)Width >> 6)) ^ (((uint)Height << 7) | ((uint)Height >> 25)));
}
/// <summary>
/// <para>
/// Inflates this <see cref='System.Drawing.Rectangle'/>
/// by the specified amount.
/// </para>
/// </summary>
public void Inflate(int width, int height)
{
X -= width;
Y -= height;
Width += 2 * width;
Height += 2 * height;
}
/// <summary>
/// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount.
/// </summary>
public void Inflate(Size size)
{
Inflate(size.Width, size.Height);
}
/// <summary>
/// <para>
/// Creates a <see cref='System.Drawing.Rectangle'/>
/// that is inflated by the specified amount.
/// </para>
/// </summary>
public static Rectangle Inflate(Rectangle rect, int x, int y)
{
Rectangle r = rect;
r.Inflate(x, y);
return r;
}
/// <summary> Creates a Rectangle that represents the intersection between this Rectangle and rect.
/// </summary>
public void Intersect(Rectangle rect)
{
Rectangle result = Rectangle.Intersect(rect, this);
X = result.X;
Y = result.Y;
Width = result.Width;
Height = result.Height;
}
/// <summary>
/// Creates a rectangle that represents the intersetion between a and
/// b. If there is no intersection, null is returned.
/// </summary>
public static Rectangle Intersect(Rectangle a, Rectangle b)
{
int x1 = Math.Max(a.X, b.X);
int x2 = Math.Min(a.X + a.Width, b.X + b.Width);
int y1 = Math.Max(a.Y, b.Y);
int y2 = Math.Min(a.Y + a.Height, b.Y + b.Height);
if (x2 >= x1 && y2 >= y1)
{
return new Rectangle(x1, y1, x2 - x1, y2 - y1);
}
return Empty;
}
/// <summary>
/// Determines if this rectangle intersets with rect.
/// </summary>
[Pure]
public bool IntersectsWith(Rectangle rect)
{
return (rect.X < X + Width) && (X < (rect.X + rect.Width)) &&
(rect.Y < Y + Height) && (Y < rect.Y + rect.Height);
}
/// <summary>
/// <para>
/// Creates a rectangle that represents the union between a and
/// b.
/// </para>
/// </summary>
[Pure]
public static Rectangle Union(Rectangle a, Rectangle b)
{
int x1 = Math.Min(a.X, b.X);
int x2 = Math.Max(a.X + a.Width, b.X + b.Width);
int y1 = Math.Min(a.Y, b.Y);
int y2 = Math.Max(a.Y + a.Height, b.Y + b.Height);
return new Rectangle(x1, y1, x2 - x1, y2 - y1);
}
/// <summary>
/// <para>
/// Adjusts the location of this rectangle by the specified amount.
/// </para>
/// </summary>
public void Offset(Point pos)
{
Offset(pos.X, pos.Y);
}
/// <summary>
/// Adjusts the location of this rectangle by the specified amount.
/// </summary>
public void Offset(int x, int y)
{
X += x;
Y += y;
}
/// <summary>
/// <para>
/// Converts the attributes of this <see cref='System.Drawing.Rectangle'/> to a
/// human readable string.
/// </para>
/// </summary>
public override string ToString()
{
return "{X=" + X.ToString() + ",Y=" + Y.ToString() +
",Width=" + Width.ToString() + ",Height=" + Height.ToString() + "}";
}
}
}
| |
//
// Mono.System.Xml.NameTable.cs
//
// Authors:
// Duncan Mak (duncan@ximian.com)
// Ben Maurer (bmaurer@users.sourceforge.net)
//
// (C) Ximian, Inc.
// (C) 2003 Ben Maurer
//
//
// 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;
namespace Mono.System.Xml {
//
// This class implements the name table as a simple
// hashtable, using buckets and a linked list.
//
public class NameTable : XmlNameTable {
const int INITIAL_BUCKETS = 2 << 6; // 64
int count = INITIAL_BUCKETS;
Entry [] buckets = new Entry [INITIAL_BUCKETS];
int size;
public NameTable () {}
class Entry {
public string str;
public int hash, len;
public Entry next;
public Entry (string str, int hash, Entry next)
{
this.str = str;
this.len = str.Length;
this.hash = hash;
this.next = next;
}
}
public override string Add (char [] key, int start, int len)
{
if (((0 > start) && (start >= key.Length))
|| ((0 > len) && (len >= key.Length - len)))
throw new IndexOutOfRangeException ("The Index is out of range.");
if (len == 0) return String.Empty;
int h = 0;
// This is from the String.Gethash () icall
int end = start + len;
for (int i = start; i < end; i++)
h = (h << 5) - h + key [i];
// h must be be >= 0
h &= 0x7FFFFFFF;
for (Entry e = buckets [h % count]; e != null; e = e.next) {
if (e.hash == h && e.len == len && StrEqArray (e.str, key, start))
return e.str;
}
return AddEntry (new string (key, start, len), h);
}
public override string Add (string key)
{
if (key == null) throw new ArgumentNullException ("key");
int keyLen = key.Length;
if (keyLen == 0) return String.Empty;
int h = 0;
// This is from the String.Gethash () icall
for (int i = 0; i < keyLen; i++)
h = (h << 5) - h + key [i];
// h must be be >= 0
h &= 0x7FFFFFFF;
for (Entry e = buckets [h % count]; e != null; e = e.next) {
if (e.hash == h && e.len == key.Length && e.str == key)
return e.str;
}
return AddEntry (key, h);
}
public override string Get (char [] key, int start, int len)
{
if (((0 > start) && (start >= key.Length))
|| ((0 > len) && (len >= key.Length - len)))
throw new IndexOutOfRangeException ("The Index is out of range.");
if (len == 0) return String.Empty;
int h = 0;
// This is from the String.Gethash () icall
int end = start + len;
for (int i = start; i < end; i++)
h = (h << 5) - h + key [i];
// h must be be >= 0
h &= 0x7FFFFFFF;
for (Entry e = buckets [h % count]; e != null; e = e.next) {
if (e.hash == h && e.len == len && StrEqArray (e.str, key, start))
return e.str;
}
return null;
}
public override string Get (string value) {
if (value == null) throw new ArgumentNullException ("value");
int valLen = value.Length;
if (valLen == 0) return String.Empty;
int h = 0;
// This is from the String.Gethash () icall
for (int i = 0; i < valLen; i++)
h = (h << 5) - h + value [i];
// h must be be >= 0
h &= 0x7FFFFFFF;
for (Entry e = buckets [h % count]; e != null; e = e.next) {
if (e.hash == h && e.len == value.Length && e.str == value)
return e.str;
}
return null;
}
string AddEntry (string str, int hash)
{
int bucket = hash % count;
buckets [bucket] = new Entry (str, hash, buckets [bucket]);
// Grow whenever we double in size
if (size++ == count) {
count <<= 1;
int csub1 = count - 1;
Entry [] newBuckets = new Entry [count];
for (int i = 0; i < buckets.Length; i++) {
Entry root = buckets [i];
Entry e = root;
while (e != null) {
int newLoc = e.hash & csub1;
Entry n = e.next;
e.next = newBuckets [newLoc];
newBuckets [newLoc] = e;
e = n;
}
}
buckets = newBuckets;
}
return str;
}
static bool StrEqArray (string str, char [] str2, int start)
{
int i = str.Length;
i --;
start += i;
do
{
if (str[i] != str2[start])
return false;
i--;
start--;
}
while(i >= 0);
return true;
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Visualizations
{
using System;
using System.Globalization;
using System.Linq;
using System.ServiceModel;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Adxstudio.Xrm.Core;
using Adxstudio.Xrm.Metadata;
using Adxstudio.Xrm.Services.Query;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
/// <summary>
/// Definition of a CRM chart visualization (savedqueryvisualization).
/// </summary>
public class CrmChart
{
/// <summary>
/// Regex pattern for chart definition XML option set placeholder values.
/// </summary>
private static readonly Regex OptionSetPatternRegex = new Regex(@"^o:(?<optionSetName>\w+),(?<optionSetValue>\d+)$", RegexOptions.CultureInvariant);
/// <summary>
/// Current langauge code (LCID) for this chart definition.
/// </summary>
private readonly int languageCode;
/// <summary>
/// Information that indicates what data to retrieve and how it is categorized for the series.
/// </summary>
public DataDefinition DataDescription { get; set; }
/// <summary>
/// Raw XML of the chart data description that is parsed into <see cref="DataDescription"/>
/// </summary>
public string DataDescriptionXml { get; set; }
/// <summary>
/// Additional information that describes the chart.
/// </summary>
public string Description { get; set; }
/// <summary>
/// FetchXml query to be executed to retrieve the data for the chart.
/// </summary>
public Fetch Fetch { get; set; }
/// <summary>
/// Unique identifier of the chart.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Name of the chart.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Raw XML of the chart presentation description that is a serialization of the .Net Chart Control.
/// </summary>
public string PresentationDescriptionXml { get; set; }
/// <summary>
/// Gets the <see cref="EntityMetadata"/> for the primary entity of the chart.
/// </summary>
public EntityMetadata PrimaryEntityMetadata { get; private set; }
/// <summary>
/// Logical name of the entity being charted.
/// </summary>
public string PrimaryEntityTypeCode { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="CrmChart" /> class.
/// </summary>
/// <param name="chart">An <see cref="Entity"/> record that must be of type savedqueryvisualization.</param>
/// <param name="serviceContext">The <see cref="OrganizationServiceContext"/> to use to execute retrieval of localized labels.</param>
/// <param name="languageCode">The locale used to retrieve the localized labels.</param>
public CrmChart(Entity chart, OrganizationServiceContext serviceContext, int languageCode = 0)
{
if (chart == null || chart.LogicalName != "savedqueryvisualization")
{
return;
}
this.languageCode = languageCode;
this.DataDescriptionXml = chart.GetAttributeValue<string>("datadescription");
this.DataDescription = DataDefinition.Parse(this.DataDescriptionXml);
var localizedDescription = serviceContext.RetrieveLocalizedLabel(chart.ToEntityReference(), "description", languageCode);
this.Description = string.IsNullOrWhiteSpace(localizedDescription) ? chart.GetAttributeValue<string>("description") : localizedDescription;
if (this.DataDescription != null && this.DataDescription.FetchCollection != null)
{
this.Fetch = this.DataDescription.FetchCollection.FirstOrDefault();
}
this.Id = chart.Id;
var localizedName = serviceContext.RetrieveLocalizedLabel(chart.ToEntityReference(), "name", languageCode);
this.Name = string.IsNullOrWhiteSpace(localizedName) ? chart.GetAttributeValue<string>("name") : localizedName;
this.PrimaryEntityTypeCode = chart.GetAttributeValue<string>("primaryentitytypecode");
this.PrimaryEntityMetadata = MetadataHelper.GetEntityMetadata(serviceContext, this.PrimaryEntityTypeCode);
this.PresentationDescriptionXml = this.ReplacePresentationDescriptionMetadataPlaceholders(chart.GetAttributeValue<string>("presentationdescription"), serviceContext);
}
/// <summary>
/// Replaces placeholder values in chart presentation XML with localized labels.
/// </summary>
/// <param name="presentationDescription">Chart presentation description XML.</param>
/// <param name="serviceContext">CRM service context.</param>
/// <returns>Chart presentation description XML with placeholder values replaced with proper labels.</returns>
private string ReplacePresentationDescriptionMetadataPlaceholders(string presentationDescription, OrganizationServiceContext serviceContext)
{
if (string.IsNullOrEmpty(presentationDescription))
{
return presentationDescription;
}
try
{
var xml = XElement.Parse(presentationDescription);
foreach (var namedElement in xml.XPathSelectElements("//*[@Name]"))
{
this.ReplacePresentationDescriptionOptionSetPlaceholders(namedElement, "Name", serviceContext);
}
return xml.ToString(SaveOptions.DisableFormatting);
}
catch (XmlException)
{
return presentationDescription;
}
}
/// <summary>
/// Replaces placeholder values in chart presentation XML element attribute values with localized labels, in place.
/// </summary>
/// <param name="element">The XML element with a given attribute value to be parsed and potentialy replaced.</param>
/// <param name="attributeName">The name of the XML attribute to be parsed for replacements.</param>
/// <param name="serviceContext">CRM service context.</param>
private void ReplacePresentationDescriptionOptionSetPlaceholders(XElement element, string attributeName, OrganizationServiceContext serviceContext)
{
var attribute = element.Attribute(attributeName);
if (attribute == null)
{
return;
}
var placeholderMatch = OptionSetPatternRegex.Match(attribute.Value);
if (placeholderMatch.Success)
{
attribute.SetValue(this.ReplacePresentationDescriptionOptionSetPlaceholderMatch(placeholderMatch, serviceContext));
}
}
/// <summary>
/// Replaces placeholder values in chart presentation XML option set value matches.
/// </summary>
/// <param name="match">The regex match for which to find a localized replacement value.</param>
/// <param name="serviceContext">CRM service context.</param>
/// <returns>Localized option set value label.</returns>
private string ReplacePresentationDescriptionOptionSetPlaceholderMatch(Match match, OrganizationServiceContext serviceContext)
{
var optionSetName = match.Groups["optionSetName"].Value;
var optionSetValue = match.Groups["optionSetValue"].Value;
var optionSetAttributeMetadata = this.PrimaryEntityMetadata.Attributes
.OfType<EnumAttributeMetadata>()
.FirstOrDefault(e => e.OptionSet != null && string.Equals(optionSetName, e.OptionSet.Name, StringComparison.OrdinalIgnoreCase));
if (optionSetAttributeMetadata != null)
{
return this.GetOptionSetValueLabel(optionSetAttributeMetadata.OptionSet, optionSetValue);
}
OptionSetMetadata optionSet;
try
{
var retrieveOptionSetResponse = (RetrieveOptionSetResponse)serviceContext.Execute(new RetrieveOptionSetRequest
{
Name = optionSetName
});
optionSet = retrieveOptionSetResponse.OptionSetMetadata as OptionSetMetadata;
}
catch (FaultException<OrganizationServiceFault>)
{
return optionSetValue;
}
if (optionSet == null)
{
return optionSetValue;
}
return this.GetOptionSetValueLabel(optionSet, optionSetValue);
}
/// <summary>
/// Gets the localized label for a given option set value.
/// </summary>
/// <param name="optionSet">Metadata for a given option set.</param>
/// <param name="optionSetValue">An option set value, as a string.</param>
/// <returns>Localized label for a given option set value, otherwise the option set value itself if not found.</returns>
private string GetOptionSetValueLabel(OptionSetMetadata optionSet, string optionSetValue)
{
int value;
if (!int.TryParse(optionSetValue, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
{
return optionSetValue;
}
var option = optionSet.Options.FirstOrDefault(e => e.Value == value);
if (option == null)
{
return optionSetValue;
}
return this.GetLocalizedLabel(option.Label);
}
/// <summary>
/// Get the localized string from a <see cref="Label"/>.
/// </summary>
/// <param name="label">The <see cref="Label"/> to get the localized string from.</param>
/// <returns>A localized string.</returns>
private string GetLocalizedLabel(Label label)
{
var localizedLabel = label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == this.languageCode);
if (localizedLabel != null)
{
return localizedLabel.Label;
}
if (label.UserLocalizedLabel != null)
{
return label.UserLocalizedLabel.Label;
}
return null;
}
}
}
| |
/**
* (C) Copyright IBM Corp. 2018, 2021.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using NSubstitute;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using IBM.Cloud.SDK.Core.Http;
using IBM.Cloud.SDK.Core.Http.Exceptions;
using IBM.Cloud.SDK.Core.Authentication.NoAuth;
using IBM.Watson.Discovery.v1.Model;
using IBM.Cloud.SDK.Core.Model;
using Environment = IBM.Watson.Discovery.v1.Model.Environment;
namespace IBM.Watson.Discovery.v1.UnitTests
{
[TestClass]
public class DiscoveryServiceUnitTests
{
#region Constructor
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void Constructor_HttpClient_Null()
{
DiscoveryService service = new DiscoveryService(httpClient: null);
}
[TestMethod]
public void ConstructorHttpClient()
{
DiscoveryService service = new DiscoveryService(new IBMHttpClient());
Assert.IsNotNull(service);
}
[TestMethod]
public void ConstructorExternalConfig()
{
var apikey = System.Environment.GetEnvironmentVariable("DISCOVERY_APIKEY");
System.Environment.SetEnvironmentVariable("DISCOVERY_APIKEY", "apikey");
DiscoveryService service = Substitute.For<DiscoveryService>("versionDate");
Assert.IsNotNull(service);
System.Environment.SetEnvironmentVariable("DISCOVERY_APIKEY", apikey);
}
[TestMethod]
public void Constructor()
{
DiscoveryService service = new DiscoveryService(new IBMHttpClient());
Assert.IsNotNull(service);
}
[TestMethod]
public void ConstructorAuthenticator()
{
DiscoveryService service = new DiscoveryService("versionDate", new NoAuthAuthenticator());
Assert.IsNotNull(service);
}
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void ConstructorNoVersion()
{
DiscoveryService service = new DiscoveryService(null, new NoAuthAuthenticator());
}
[TestMethod]
public void ConstructorNoUrl()
{
var apikey = System.Environment.GetEnvironmentVariable("DISCOVERY_APIKEY");
System.Environment.SetEnvironmentVariable("DISCOVERY_APIKEY", "apikey");
var url = System.Environment.GetEnvironmentVariable("DISCOVERY_URL");
System.Environment.SetEnvironmentVariable("DISCOVERY_URL", null);
DiscoveryService service = Substitute.For<DiscoveryService>("versionDate");
Assert.IsTrue(service.ServiceUrl == "https://api.us-south.discovery.watson.cloud.ibm.com");
System.Environment.SetEnvironmentVariable("DISCOVERY_APIKEY", apikey);
}
#endregion
[TestMethod]
public void CreateEnvironment_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var name = "name";
var description = "description";
var size = "size";
var result = service.CreateEnvironment(name: name, description: description, size: size);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(name))
{
bodyObject["name"] = JToken.FromObject(name);
}
if (!string.IsNullOrEmpty(description))
{
bodyObject["description"] = JToken.FromObject(description);
}
if (!string.IsNullOrEmpty(size))
{
bodyObject["size"] = JToken.FromObject(size);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
}
[TestMethod]
public void ListEnvironments_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var name = "name";
var result = service.ListEnvironments(name: name);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void GetEnvironment_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var result = service.GetEnvironment(environmentId: environmentId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}");
}
[TestMethod]
public void UpdateEnvironment_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PutAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var name = "name";
var description = "description";
var size = "size";
var result = service.UpdateEnvironment(environmentId: environmentId, name: name, description: description, size: size);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(name))
{
bodyObject["name"] = JToken.FromObject(name);
}
if (!string.IsNullOrEmpty(description))
{
bodyObject["description"] = JToken.FromObject(description);
}
if (!string.IsNullOrEmpty(size))
{
bodyObject["size"] = JToken.FromObject(size);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PutAsync($"{service.ServiceUrl}/v1/environments/{environmentId}");
}
[TestMethod]
public void DeleteEnvironment_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var result = service.DeleteEnvironment(environmentId: environmentId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/environments/{environmentId}");
}
[TestMethod]
public void ListFields_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionIds = new List<string>() { "collectionIds0", "collectionIds1" };
var result = service.ListFields(environmentId: environmentId, collectionIds: collectionIds);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/fields");
}
[TestMethod]
public void CreateConfiguration_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var name = "name";
var description = "description";
var conversions = new Conversions();
var enrichments = new List<Enrichment>();
var normalizations = new List<NormalizationOperation>();
var source = new Source();
var result = service.CreateConfiguration(environmentId: environmentId, name: name, description: description, conversions: conversions, enrichments: enrichments, normalizations: normalizations, source: source);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(name))
{
bodyObject["name"] = JToken.FromObject(name);
}
if (!string.IsNullOrEmpty(description))
{
bodyObject["description"] = JToken.FromObject(description);
}
if (conversions != null)
{
bodyObject["conversions"] = JToken.FromObject(conversions);
}
if (enrichments != null && enrichments.Count > 0)
{
bodyObject["enrichments"] = JToken.FromObject(enrichments);
}
if (normalizations != null && normalizations.Count > 0)
{
bodyObject["normalizations"] = JToken.FromObject(normalizations);
}
if (source != null)
{
bodyObject["source"] = JToken.FromObject(source);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/configurations");
}
[TestMethod]
public void ListConfigurations_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var name = "name";
var result = service.ListConfigurations(environmentId: environmentId, name: name);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/configurations");
}
[TestMethod]
public void GetConfiguration_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var configurationId = "configurationId";
var result = service.GetConfiguration(environmentId: environmentId, configurationId: configurationId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/configurations/{configurationId}");
}
[TestMethod]
public void UpdateConfiguration_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PutAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var configurationId = "configurationId";
var name = "name";
var description = "description";
var conversions = new Conversions();
var enrichments = new List<Enrichment>();
var normalizations = new List<NormalizationOperation>();
var source = new Source();
var result = service.UpdateConfiguration(environmentId: environmentId, configurationId: configurationId, name: name, description: description, conversions: conversions, enrichments: enrichments, normalizations: normalizations, source: source);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(name))
{
bodyObject["name"] = JToken.FromObject(name);
}
if (!string.IsNullOrEmpty(description))
{
bodyObject["description"] = JToken.FromObject(description);
}
if (conversions != null)
{
bodyObject["conversions"] = JToken.FromObject(conversions);
}
if (enrichments != null && enrichments.Count > 0)
{
bodyObject["enrichments"] = JToken.FromObject(enrichments);
}
if (normalizations != null && normalizations.Count > 0)
{
bodyObject["normalizations"] = JToken.FromObject(normalizations);
}
if (source != null)
{
bodyObject["source"] = JToken.FromObject(source);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PutAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/configurations/{configurationId}");
}
[TestMethod]
public void DeleteConfiguration_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var configurationId = "configurationId";
var result = service.DeleteConfiguration(environmentId: environmentId, configurationId: configurationId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/configurations/{configurationId}");
}
[TestMethod]
public void CreateCollection_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var name = "name";
var description = "description";
var configurationId = "configurationId";
var language = "language";
var result = service.CreateCollection(environmentId: environmentId, name: name, description: description, configurationId: configurationId, language: language);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(name))
{
bodyObject["name"] = JToken.FromObject(name);
}
if (!string.IsNullOrEmpty(description))
{
bodyObject["description"] = JToken.FromObject(description);
}
if (!string.IsNullOrEmpty(configurationId))
{
bodyObject["configuration_id"] = JToken.FromObject(configurationId);
}
if (!string.IsNullOrEmpty(language))
{
bodyObject["language"] = JToken.FromObject(language);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections");
}
[TestMethod]
public void ListCollections_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var name = "name";
var result = service.ListCollections(environmentId: environmentId, name: name);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections");
}
[TestMethod]
public void GetCollection_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var result = service.GetCollection(environmentId: environmentId, collectionId: collectionId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}");
}
[TestMethod]
public void UpdateCollection_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PutAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var name = "name";
var description = "description";
var configurationId = "configurationId";
var result = service.UpdateCollection(environmentId: environmentId, collectionId: collectionId, name: name, description: description, configurationId: configurationId);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(name))
{
bodyObject["name"] = JToken.FromObject(name);
}
if (!string.IsNullOrEmpty(description))
{
bodyObject["description"] = JToken.FromObject(description);
}
if (!string.IsNullOrEmpty(configurationId))
{
bodyObject["configuration_id"] = JToken.FromObject(configurationId);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PutAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}");
}
[TestMethod]
public void DeleteCollection_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var result = service.DeleteCollection(environmentId: environmentId, collectionId: collectionId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}");
}
[TestMethod]
public void ListCollectionFields_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var result = service.ListCollectionFields(environmentId: environmentId, collectionId: collectionId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/fields");
}
[TestMethod]
public void ListExpansions_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var result = service.ListExpansions(environmentId: environmentId, collectionId: collectionId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/expansions");
}
[TestMethod]
public void CreateExpansions_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var expansions = new List<Expansion>();
var result = service.CreateExpansions(environmentId: environmentId, collectionId: collectionId, expansions: expansions);
JObject bodyObject = new JObject();
if (expansions != null && expansions.Count > 0)
{
bodyObject["expansions"] = JToken.FromObject(expansions);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/expansions");
}
[TestMethod]
public void DeleteExpansions_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var result = service.DeleteExpansions(environmentId: environmentId, collectionId: collectionId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/expansions");
}
[TestMethod]
public void GetTokenizationDictionaryStatus_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var result = service.GetTokenizationDictionaryStatus(environmentId: environmentId, collectionId: collectionId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/word_lists/tokenization_dictionary");
}
[TestMethod]
public void CreateTokenizationDictionary_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var tokenizationRules = new List<TokenDictRule>();
var result = service.CreateTokenizationDictionary(environmentId: environmentId, collectionId: collectionId, tokenizationRules: tokenizationRules);
JObject bodyObject = new JObject();
if (tokenizationRules != null && tokenizationRules.Count > 0)
{
bodyObject["tokenization_rules"] = JToken.FromObject(tokenizationRules);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/word_lists/tokenization_dictionary");
}
[TestMethod]
public void DeleteTokenizationDictionary_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var result = service.DeleteTokenizationDictionary(environmentId: environmentId, collectionId: collectionId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/word_lists/tokenization_dictionary");
}
[TestMethod]
public void GetStopwordListStatus_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var result = service.GetStopwordListStatus(environmentId: environmentId, collectionId: collectionId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/word_lists/stopwords");
}
[TestMethod]
public void CreateStopwordList_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var stopwordFile = new MemoryStream();
var stopwordFilename = "stopwordFilename";
var result = service.CreateStopwordList(environmentId: environmentId, collectionId: collectionId, stopwordFile: stopwordFile, stopwordFilename: stopwordFilename);
request.Received().WithArgument("version", versionDate);
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/word_lists/stopwords");
}
[TestMethod]
public void DeleteStopwordList_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var result = service.DeleteStopwordList(environmentId: environmentId, collectionId: collectionId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/word_lists/stopwords");
}
[TestMethod]
public void AddDocument_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var file = new MemoryStream();
var filename = "filename";
var fileContentType = "fileContentType";
var metadata = "metadata";
var result = service.AddDocument(environmentId: environmentId, collectionId: collectionId, file: file, filename: filename, fileContentType: fileContentType, metadata: metadata);
request.Received().WithArgument("version", versionDate);
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/documents");
}
[TestMethod]
public void GetDocumentStatus_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var documentId = "documentId";
var result = service.GetDocumentStatus(environmentId: environmentId, collectionId: collectionId, documentId: documentId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/documents/{documentId}");
}
[TestMethod]
public void UpdateDocument_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var documentId = "documentId";
var file = new MemoryStream();
var filename = "filename";
var fileContentType = "fileContentType";
var metadata = "metadata";
var result = service.UpdateDocument(environmentId: environmentId, collectionId: collectionId, documentId: documentId, file: file, filename: filename, fileContentType: fileContentType, metadata: metadata);
request.Received().WithArgument("version", versionDate);
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/documents/{documentId}");
}
[TestMethod]
public void DeleteDocument_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var documentId = "documentId";
var result = service.DeleteDocument(environmentId: environmentId, collectionId: collectionId, documentId: documentId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/documents/{documentId}");
}
[TestMethod]
public void Query_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var filter = "filter";
var query = "query";
var naturalLanguageQuery = "naturalLanguageQuery";
var passages = false;
var aggregation = "aggregation";
var count = 1;
var _return = "_return";
var offset = 1;
var sort = "sort";
var highlight = false;
var passagesFields = "passagesFields";
var passagesCount = 1;
var passagesCharacters = 1;
var deduplicate = false;
var deduplicateField = "deduplicateField";
var similar = false;
var similarDocumentIds = "similarDocumentIds";
var similarFields = "similarFields";
var bias = "bias";
var spellingSuggestions = false;
var xWatsonLoggingOptOut = false;
var result = service.Query(environmentId: environmentId, collectionId: collectionId, filter: filter, query: query, naturalLanguageQuery: naturalLanguageQuery, passages: passages, aggregation: aggregation, count: count, _return: _return, offset: offset, sort: sort, highlight: highlight, passagesFields: passagesFields, passagesCount: passagesCount, passagesCharacters: passagesCharacters, deduplicate: deduplicate, deduplicateField: deduplicateField, similar: similar, similarDocumentIds: similarDocumentIds, similarFields: similarFields, bias: bias, spellingSuggestions: spellingSuggestions, xWatsonLoggingOptOut: xWatsonLoggingOptOut);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(filter))
{
bodyObject["filter"] = JToken.FromObject(filter);
}
if (!string.IsNullOrEmpty(query))
{
bodyObject["query"] = JToken.FromObject(query);
}
if (!string.IsNullOrEmpty(naturalLanguageQuery))
{
bodyObject["natural_language_query"] = JToken.FromObject(naturalLanguageQuery);
}
bodyObject["passages"] = JToken.FromObject(passages);
if (!string.IsNullOrEmpty(aggregation))
{
bodyObject["aggregation"] = JToken.FromObject(aggregation);
}
if (count != null)
{
bodyObject["count"] = JToken.FromObject(count);
}
if (!string.IsNullOrEmpty(_return))
{
bodyObject["return"] = JToken.FromObject(_return);
}
if (offset != null)
{
bodyObject["offset"] = JToken.FromObject(offset);
}
if (!string.IsNullOrEmpty(sort))
{
bodyObject["sort"] = JToken.FromObject(sort);
}
bodyObject["highlight"] = JToken.FromObject(highlight);
if (!string.IsNullOrEmpty(passagesFields))
{
bodyObject["passages.fields"] = JToken.FromObject(passagesFields);
}
if (passagesCount != null)
{
bodyObject["passages.count"] = JToken.FromObject(passagesCount);
}
if (passagesCharacters != null)
{
bodyObject["passages.characters"] = JToken.FromObject(passagesCharacters);
}
bodyObject["deduplicate"] = JToken.FromObject(deduplicate);
if (!string.IsNullOrEmpty(deduplicateField))
{
bodyObject["deduplicate.field"] = JToken.FromObject(deduplicateField);
}
bodyObject["similar"] = JToken.FromObject(similar);
if (!string.IsNullOrEmpty(similarDocumentIds))
{
bodyObject["similar.document_ids"] = JToken.FromObject(similarDocumentIds);
}
if (!string.IsNullOrEmpty(similarFields))
{
bodyObject["similar.fields"] = JToken.FromObject(similarFields);
}
if (!string.IsNullOrEmpty(bias))
{
bodyObject["bias"] = JToken.FromObject(bias);
}
bodyObject["spelling_suggestions"] = JToken.FromObject(spellingSuggestions);
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/query");
}
[TestMethod]
public void QueryNotices_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var filter = "filter";
var query = "query";
var naturalLanguageQuery = "naturalLanguageQuery";
var passages = false;
var aggregation = "aggregation";
long? count = 1;
var _return = new List<string>() { "_return0", "_return1" };
long? offset = 1;
var sort = new List<string>() { "sort0", "sort1" };
var highlight = false;
var passagesFields = new List<string>() { "passagesFields0", "passagesFields1" };
long? passagesCount = 1;
long? passagesCharacters = 1;
var deduplicateField = "deduplicateField";
var similar = false;
var similarDocumentIds = new List<string>() { "similarDocumentIds0", "similarDocumentIds1" };
var similarFields = new List<string>() { "similarFields0", "similarFields1" };
var result = service.QueryNotices(environmentId: environmentId, collectionId: collectionId, filter: filter, query: query, naturalLanguageQuery: naturalLanguageQuery, passages: passages, aggregation: aggregation, count: count, _return: _return, offset: offset, sort: sort, highlight: highlight, passagesFields: passagesFields, passagesCount: passagesCount, passagesCharacters: passagesCharacters, deduplicateField: deduplicateField, similar: similar, similarDocumentIds: similarDocumentIds, similarFields: similarFields);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/notices");
}
[TestMethod]
public void FederatedQuery_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionIds = "collectionIds";
var filter = "filter";
var query = "query";
var naturalLanguageQuery = "naturalLanguageQuery";
var passages = false;
var aggregation = "aggregation";
var count = 1;
var _return = "_return";
var offset = 1;
var sort = "sort";
var highlight = false;
var passagesFields = "passagesFields";
var passagesCount = 1;
var passagesCharacters = 1;
var deduplicate = false;
var deduplicateField = "deduplicateField";
var similar = false;
var similarDocumentIds = "similarDocumentIds";
var similarFields = "similarFields";
var bias = "bias";
var xWatsonLoggingOptOut = false;
var result = service.FederatedQuery(environmentId: environmentId, collectionIds: collectionIds, filter: filter, query: query, naturalLanguageQuery: naturalLanguageQuery, passages: passages, aggregation: aggregation, count: count, _return: _return, offset: offset, sort: sort, highlight: highlight, passagesFields: passagesFields, passagesCount: passagesCount, passagesCharacters: passagesCharacters, deduplicate: deduplicate, deduplicateField: deduplicateField, similar: similar, similarDocumentIds: similarDocumentIds, similarFields: similarFields, bias: bias, xWatsonLoggingOptOut: xWatsonLoggingOptOut);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(collectionIds))
{
bodyObject["collection_ids"] = JToken.FromObject(collectionIds);
}
if (!string.IsNullOrEmpty(filter))
{
bodyObject["filter"] = JToken.FromObject(filter);
}
if (!string.IsNullOrEmpty(query))
{
bodyObject["query"] = JToken.FromObject(query);
}
if (!string.IsNullOrEmpty(naturalLanguageQuery))
{
bodyObject["natural_language_query"] = JToken.FromObject(naturalLanguageQuery);
}
bodyObject["passages"] = JToken.FromObject(passages);
if (!string.IsNullOrEmpty(aggregation))
{
bodyObject["aggregation"] = JToken.FromObject(aggregation);
}
if (count != null)
{
bodyObject["count"] = JToken.FromObject(count);
}
if (!string.IsNullOrEmpty(_return))
{
bodyObject["return"] = JToken.FromObject(_return);
}
if (offset != null)
{
bodyObject["offset"] = JToken.FromObject(offset);
}
if (!string.IsNullOrEmpty(sort))
{
bodyObject["sort"] = JToken.FromObject(sort);
}
bodyObject["highlight"] = JToken.FromObject(highlight);
if (!string.IsNullOrEmpty(passagesFields))
{
bodyObject["passages.fields"] = JToken.FromObject(passagesFields);
}
if (passagesCount != null)
{
bodyObject["passages.count"] = JToken.FromObject(passagesCount);
}
if (passagesCharacters != null)
{
bodyObject["passages.characters"] = JToken.FromObject(passagesCharacters);
}
bodyObject["deduplicate"] = JToken.FromObject(deduplicate);
if (!string.IsNullOrEmpty(deduplicateField))
{
bodyObject["deduplicate.field"] = JToken.FromObject(deduplicateField);
}
bodyObject["similar"] = JToken.FromObject(similar);
if (!string.IsNullOrEmpty(similarDocumentIds))
{
bodyObject["similar.document_ids"] = JToken.FromObject(similarDocumentIds);
}
if (!string.IsNullOrEmpty(similarFields))
{
bodyObject["similar.fields"] = JToken.FromObject(similarFields);
}
if (!string.IsNullOrEmpty(bias))
{
bodyObject["bias"] = JToken.FromObject(bias);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/query");
}
[TestMethod]
public void FederatedQueryNotices_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionIds = new List<string>() { "collectionIds0", "collectionIds1" };
var filter = "filter";
var query = "query";
var naturalLanguageQuery = "naturalLanguageQuery";
var aggregation = "aggregation";
long? count = 1;
var _return = new List<string>() { "_return0", "_return1" };
long? offset = 1;
var sort = new List<string>() { "sort0", "sort1" };
var highlight = false;
var deduplicateField = "deduplicateField";
var similar = false;
var similarDocumentIds = new List<string>() { "similarDocumentIds0", "similarDocumentIds1" };
var similarFields = new List<string>() { "similarFields0", "similarFields1" };
var result = service.FederatedQueryNotices(environmentId: environmentId, collectionIds: collectionIds, filter: filter, query: query, naturalLanguageQuery: naturalLanguageQuery, aggregation: aggregation, count: count, _return: _return, offset: offset, sort: sort, highlight: highlight, deduplicateField: deduplicateField, similar: similar, similarDocumentIds: similarDocumentIds, similarFields: similarFields);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/notices");
}
[TestMethod]
public void GetAutocompletion_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var prefix = "prefix";
var field = "field";
long? count = 1;
var result = service.GetAutocompletion(environmentId: environmentId, collectionId: collectionId, prefix: prefix, field: field, count: count);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/autocompletion");
}
[TestMethod]
public void ListTrainingData_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var result = service.ListTrainingData(environmentId: environmentId, collectionId: collectionId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/training_data");
}
[TestMethod]
public void AddTrainingData_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var naturalLanguageQuery = "naturalLanguageQuery";
var filter = "filter";
var examples = new List<TrainingExample>();
var result = service.AddTrainingData(environmentId: environmentId, collectionId: collectionId, naturalLanguageQuery: naturalLanguageQuery, filter: filter, examples: examples);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(naturalLanguageQuery))
{
bodyObject["natural_language_query"] = JToken.FromObject(naturalLanguageQuery);
}
if (!string.IsNullOrEmpty(filter))
{
bodyObject["filter"] = JToken.FromObject(filter);
}
if (examples != null && examples.Count > 0)
{
bodyObject["examples"] = JToken.FromObject(examples);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/training_data");
}
[TestMethod]
public void DeleteAllTrainingData_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var result = service.DeleteAllTrainingData(environmentId: environmentId, collectionId: collectionId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/training_data");
}
[TestMethod]
public void GetTrainingData_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var queryId = "queryId";
var result = service.GetTrainingData(environmentId: environmentId, collectionId: collectionId, queryId: queryId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/training_data/{queryId}");
}
[TestMethod]
public void DeleteTrainingData_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var queryId = "queryId";
var result = service.DeleteTrainingData(environmentId: environmentId, collectionId: collectionId, queryId: queryId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/training_data/{queryId}");
}
[TestMethod]
public void ListTrainingExamples_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var queryId = "queryId";
var result = service.ListTrainingExamples(environmentId: environmentId, collectionId: collectionId, queryId: queryId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/training_data/{queryId}/examples");
}
[TestMethod]
public void CreateTrainingExample_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var queryId = "queryId";
var documentId = "documentId";
var crossReference = "crossReference";
var relevance = 1;
var result = service.CreateTrainingExample(environmentId: environmentId, collectionId: collectionId, queryId: queryId, documentId: documentId, crossReference: crossReference, relevance: relevance);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(documentId))
{
bodyObject["document_id"] = JToken.FromObject(documentId);
}
if (!string.IsNullOrEmpty(crossReference))
{
bodyObject["cross_reference"] = JToken.FromObject(crossReference);
}
if (relevance != null)
{
bodyObject["relevance"] = JToken.FromObject(relevance);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/training_data/{queryId}/examples");
}
[TestMethod]
public void DeleteTrainingExample_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var queryId = "queryId";
var exampleId = "exampleId";
var result = service.DeleteTrainingExample(environmentId: environmentId, collectionId: collectionId, queryId: queryId, exampleId: exampleId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/training_data/{queryId}/examples/{exampleId}");
}
[TestMethod]
public void UpdateTrainingExample_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PutAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var queryId = "queryId";
var exampleId = "exampleId";
var crossReference = "crossReference";
var relevance = 1;
var result = service.UpdateTrainingExample(environmentId: environmentId, collectionId: collectionId, queryId: queryId, exampleId: exampleId, crossReference: crossReference, relevance: relevance);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(crossReference))
{
bodyObject["cross_reference"] = JToken.FromObject(crossReference);
}
if (relevance != null)
{
bodyObject["relevance"] = JToken.FromObject(relevance);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PutAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/training_data/{queryId}/examples/{exampleId}");
}
[TestMethod]
public void GetTrainingExample_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var collectionId = "collectionId";
var queryId = "queryId";
var exampleId = "exampleId";
var result = service.GetTrainingExample(environmentId: environmentId, collectionId: collectionId, queryId: queryId, exampleId: exampleId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/collections/{collectionId}/training_data/{queryId}/examples/{exampleId}");
}
[TestMethod]
public void DeleteUserData_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var customerId = "customerId";
var result = service.DeleteUserData(customerId: customerId);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void CreateEvent_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var type = "type";
var data = new EventData();
var result = service.CreateEvent(type: type, data: data);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(type))
{
bodyObject["type"] = JToken.FromObject(type);
}
if (data != null)
{
bodyObject["data"] = JToken.FromObject(data);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
}
[TestMethod]
public void QueryLog_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var filter = "filter";
var query = "query";
long? count = 1;
long? offset = 1;
var sort = new List<string>() { "sort0", "sort1" };
var result = service.QueryLog(filter: filter, query: query, count: count, offset: offset, sort: sort);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void GetMetricsQuery_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
DateTime? startTime = DateTime.MaxValue;
DateTime? endTime = DateTime.MaxValue;
var resultType = "resultType";
var result = service.GetMetricsQuery(startTime: startTime, endTime: endTime, resultType: resultType);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void GetMetricsQueryEvent_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
DateTime? startTime = DateTime.MaxValue;
DateTime? endTime = DateTime.MaxValue;
var resultType = "resultType";
var result = service.GetMetricsQueryEvent(startTime: startTime, endTime: endTime, resultType: resultType);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void GetMetricsQueryNoResults_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
DateTime? startTime = DateTime.MaxValue;
DateTime? endTime = DateTime.MaxValue;
var resultType = "resultType";
var result = service.GetMetricsQueryNoResults(startTime: startTime, endTime: endTime, resultType: resultType);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void GetMetricsEventRate_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
DateTime? startTime = DateTime.MaxValue;
DateTime? endTime = DateTime.MaxValue;
var resultType = "resultType";
var result = service.GetMetricsEventRate(startTime: startTime, endTime: endTime, resultType: resultType);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void GetMetricsQueryTokenEvent_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
long? count = 1;
var result = service.GetMetricsQueryTokenEvent(count: count);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void ListCredentials_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var result = service.ListCredentials(environmentId: environmentId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/credentials");
}
[TestMethod]
public void CreateCredentials_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var sourceType = "sourceType";
var credentialDetails = new CredentialDetails();
var status = new StatusDetails();
var result = service.CreateCredentials(environmentId: environmentId, sourceType: sourceType, credentialDetails: credentialDetails, status: status);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(sourceType))
{
bodyObject["source_type"] = JToken.FromObject(sourceType);
}
if (credentialDetails != null)
{
bodyObject["credential_details"] = JToken.FromObject(credentialDetails);
}
if (status != null)
{
bodyObject["status"] = JToken.FromObject(status);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/credentials");
}
[TestMethod]
public void GetCredentials_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var credentialId = "credentialId";
var result = service.GetCredentials(environmentId: environmentId, credentialId: credentialId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/credentials/{credentialId}");
}
[TestMethod]
public void UpdateCredentials_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PutAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var credentialId = "credentialId";
var sourceType = "sourceType";
var credentialDetails = new CredentialDetails();
var status = new StatusDetails();
var result = service.UpdateCredentials(environmentId: environmentId, credentialId: credentialId, sourceType: sourceType, credentialDetails: credentialDetails, status: status);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(sourceType))
{
bodyObject["source_type"] = JToken.FromObject(sourceType);
}
if (credentialDetails != null)
{
bodyObject["credential_details"] = JToken.FromObject(credentialDetails);
}
if (status != null)
{
bodyObject["status"] = JToken.FromObject(status);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PutAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/credentials/{credentialId}");
}
[TestMethod]
public void DeleteCredentials_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var credentialId = "credentialId";
var result = service.DeleteCredentials(environmentId: environmentId, credentialId: credentialId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/credentials/{credentialId}");
}
[TestMethod]
public void ListGateways_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var result = service.ListGateways(environmentId: environmentId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/gateways");
}
[TestMethod]
public void CreateGateway_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var name = "name";
var result = service.CreateGateway(environmentId: environmentId, name: name);
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(name))
{
bodyObject["name"] = JToken.FromObject(name);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
client.Received().PostAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/gateways");
}
[TestMethod]
public void GetGateway_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var gatewayId = "gatewayId";
var result = service.GetGateway(environmentId: environmentId, gatewayId: gatewayId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/gateways/{gatewayId}");
}
[TestMethod]
public void DeleteGateway_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
DiscoveryService service = new DiscoveryService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var environmentId = "environmentId";
var gatewayId = "gatewayId";
var result = service.DeleteGateway(environmentId: environmentId, gatewayId: gatewayId);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/environments/{environmentId}/gateways/{gatewayId}");
}
}
}
| |
using System;
using System.Linq;
using System.Collections;
using System.Xml;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using Umbraco.Core.Strings;
using umbraco.DataLayer;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using umbraco.cms.businesslogic.cache;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;
namespace umbraco.cms.businesslogic.template
{
/// <summary>
/// Summary description for Template.
/// </summary>
[Obsolete("Obsolete, Use IFileService and ITemplate to work with templates instead")]
public class Template : CMSNode
{
#region Private members
private readonly ViewHelper _viewHelper = new ViewHelper(new PhysicalFileSystem(SystemDirectories.MvcViews));
private readonly MasterPageHelper _masterPageHelper = new MasterPageHelper(new PhysicalFileSystem(SystemDirectories.Masterpages));
internal ITemplate TemplateEntity;
private int? _mastertemplate;
#endregion
#region Static members
public static readonly string UmbracoMasterTemplate = SystemDirectories.Umbraco + "/masterpages/default.master";
private static Hashtable _templateAliases = new Hashtable();
#endregion
[Obsolete("Use TemplateFilePath instead")]
public string MasterPageFile
{
get { return TemplateFilePath; }
}
/// <summary>
/// Returns the file path for the current template
/// </summary>
public string TemplateFilePath
{
get
{
switch (ApplicationContext.Current.Services.FileService.DetermineTemplateRenderingEngine(TemplateEntity))
{
case RenderingEngine.Mvc:
return _viewHelper.GetPhysicalFilePath(TemplateEntity);
case RenderingEngine.WebForms:
return _masterPageHelper.GetPhysicalFilePath(TemplateEntity);
default:
throw new ArgumentOutOfRangeException();
}
}
}
[Obsolete("This is not used at all, do not use this")]
public static Hashtable TemplateAliases
{
get { return _templateAliases; }
set { _templateAliases = value; }
}
#region Constructors
internal Template(ITemplate template)
: base(template)
{
TemplateEntity = template;
}
public Template(int id) : base(id) { }
public Template(Guid id) : base(id) { }
#endregion
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
public override void Save()
{
SaveEventArgs e = new SaveEventArgs();
FireBeforeSave(e);
if (!e.Cancel)
{
ApplicationContext.Current.Services.FileService.SaveTemplate(TemplateEntity);
//base.Save();
FireAfterSave(e);
}
}
public string GetRawText()
{
return TemplateEntity.Name;
//return base.Text;
}
//TODO: This is the name of the template, which can apparenlty be localized using the umbraco dictionary, so we need to cater for this but that
// shoud really be done as part of mapping logic for models that are being consumed in the UI, not at the business logic layer.
public override string Text
{
get
{
var tempText = TemplateEntity.Name;
//string tempText = base.Text;
if (!tempText.StartsWith("#"))
return tempText;
else
{
language.Language lang = language.Language.GetByCultureCode(System.Threading.Thread.CurrentThread.CurrentCulture.Name);
if (lang != null)
{
if (Dictionary.DictionaryItem.hasKey(tempText.Substring(1, tempText.Length - 1)))
{
Dictionary.DictionaryItem di = new Dictionary.DictionaryItem(tempText.Substring(1, tempText.Length - 1));
if (di != null)
return di.Value(lang.id);
}
}
return "[" + tempText + "]";
}
}
set
{
FlushCache();
TemplateEntity.Name = value;
}
}
[Obsolete("This is not used whatsoever")]
public string OutputContentType { get; set; }
protected override void setupNode()
{
TemplateEntity = ApplicationContext.Current.Services.FileService.GetTemplate(Id);
if (TemplateEntity == null)
{
throw new ArgumentException(string.Format("No node exists with id '{0}'", Id));
}
}
public new string Path
{
get
{
return TemplateEntity.Path;
}
set
{
TemplateEntity.Path = value;
}
}
public string Alias
{
get { return TemplateEntity.Alias; }
set { TemplateEntity.Alias = value; }
}
public bool HasMasterTemplate
{
get { return (_mastertemplate > 0); }
}
public override bool HasChildren
{
get { return TemplateEntity.IsMasterTemplate; }
set
{
//Do nothing!
}
}
public int MasterTemplate
{
get
{
if (_mastertemplate.HasValue == false)
{
var master = ApplicationContext.Current.Services.FileService.GetTemplate(TemplateEntity.MasterTemplateAlias);
if (master != null)
{
_mastertemplate = master.Id;
}
else
{
_mastertemplate = -1;
}
}
return _mastertemplate.Value;
}
set
{
//set to null if it's zero
if (value == 0)
{
TemplateEntity.SetMasterTemplate(null);
}
else
{
var found = ApplicationContext.Current.Services.FileService.GetTemplate(value);
if (found != null)
{
TemplateEntity.SetMasterTemplate(found);
_mastertemplate = found.Id;
}
}
}
}
public string Design
{
get
{
return TemplateEntity.Content;
}
set
{
TemplateEntity.Content = value;
}
}
public XmlNode ToXml(XmlDocument doc)
{
var serializer = new EntityXmlSerializer();
var serialized = serializer.Serialize(TemplateEntity);
return serialized.GetXmlNode(doc);
}
/// <summary>
/// Removes any references to this templates from child templates, documenttypes and documents
/// </summary>
public void RemoveAllReferences()
{
if (HasChildren)
{
foreach (var t in GetAllAsList().FindAll(t => t.MasterTemplate == Id))
{
t.MasterTemplate = 0;
t.Save();
}
}
RemoveFromDocumentTypes();
// remove from documents
Document.RemoveTemplateFromDocument(this.Id);
//save it
Save();
}
public void RemoveFromDocumentTypes()
{
foreach (DocumentType dt in DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id)))
{
dt.RemoveTemplate(this.Id);
dt.Save();
}
}
[Obsolete("This method should have never existed here")]
public IEnumerable<DocumentType> GetDocumentTypes()
{
return DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id));
}
public static Template MakeNew(string Name, User u, Template master)
{
return MakeNew(Name, u, master, null);
}
private static Template MakeNew(string name, User u, string design)
{
return MakeNew(name, u, null, design);
}
public static Template MakeNew(string name, User u)
{
return MakeNew(name, u, design: null);
}
private static Template MakeNew(string name, User u, Template master, string design)
{
var foundMaster = master == null ? null : ApplicationContext.Current.Services.FileService.GetTemplate(master.Id);
var template = ApplicationContext.Current.Services.FileService.CreateTemplateWithIdentity(name, design, foundMaster, u.Id);
var legacyTemplate = new Template(template);
var e = new NewEventArgs();
legacyTemplate.OnNew(e);
return legacyTemplate;
}
public static Template GetByAlias(string Alias)
{
return GetByAlias(Alias, false);
}
[Obsolete("this overload is the same as the other one, the useCache has no affect")]
public static Template GetByAlias(string Alias, bool useCache)
{
var found = ApplicationContext.Current.Services.FileService.GetTemplate(Alias);
return found == null ? null : new Template(found);
}
[Obsolete("Obsolete, please use GetAllAsList() method instead", true)]
public static Template[] getAll()
{
return GetAllAsList().ToArray();
}
public static List<Template> GetAllAsList()
{
return ApplicationContext.Current.Services.FileService.GetTemplates().Select(x => new Template(x)).ToList();
}
public static int GetTemplateIdFromAlias(string alias)
{
var found = ApplicationContext.Current.Services.FileService.GetTemplate(alias);
return found == null ? -1 : found.Id;
}
public override void delete()
{
// don't allow template deletion if it has child templates
if (this.HasChildren)
{
var ex = new InvalidOperationException("Can't delete a master template. Remove any bindings from child templates first.");
LogHelper.Error<Template>("Can't delete a master template. Remove any bindings from child templates first.", ex);
throw ex;
}
DeleteEventArgs e = new DeleteEventArgs();
FireBeforeDelete(e);
if (!e.Cancel)
{
//remove refs from documents
SqlHelper.ExecuteNonQuery("UPDATE cmsDocument SET templateId = NULL WHERE templateId = " + this.Id);
ApplicationContext.Current.Services.FileService.DeleteTemplate(TemplateEntity.Alias);
FireAfterDelete(e);
}
}
[Obsolete("This method, doesnt actually do anything, as the file is created when the design is set", false)]
public void _SaveAsMasterPage()
{
}
public string GetMasterContentElement(int masterTemplateId)
{
if (masterTemplateId != 0)
{
string masterAlias = new Template(masterTemplateId).Alias.Replace(" ", "");
return
String.Format("<asp:Content ContentPlaceHolderID=\"{1}ContentPlaceHolder\" runat=\"server\">",
Alias.Replace(" ", ""), masterAlias);
}
else
return
String.Format("<asp:Content ContentPlaceHolderID=\"ContentPlaceHolderDefault\" runat=\"server\">",
Alias.Replace(" ", ""));
}
public List<string> contentPlaceholderIds()
{
return MasterPageHelper.GetContentPlaceholderIds(TemplateEntity).ToList();
}
public string ConvertToMasterPageSyntax(string templateDesign)
{
string masterPageContent = GetMasterContentElement(MasterTemplate) + Environment.NewLine;
masterPageContent += templateDesign;
// Parse the design for getitems
masterPageContent = EnsureMasterPageSyntax(masterPageContent);
// append ending asp:content element
masterPageContent += Environment.NewLine
+ "</asp:Content>"
+ Environment.NewLine;
return masterPageContent;
}
public string EnsureMasterPageSyntax(string masterPageContent)
{
ReplaceElement(ref masterPageContent, "?UMBRACO_GETITEM", "umbraco:Item", true);
ReplaceElement(ref masterPageContent, "?UMBRACO_GETITEM", "umbraco:Item", false);
// Parse the design for macros
ReplaceElement(ref masterPageContent, "?UMBRACO_MACRO", "umbraco:Macro", true);
ReplaceElement(ref masterPageContent, "?UMBRACO_MACRO", "umbraco:Macro", false);
// Parse the design for load childs
masterPageContent = masterPageContent.Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD/>", GetAspNetMasterPageContentContainer()).Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD />", GetAspNetMasterPageContentContainer());
// Parse the design for aspnet forms
GetAspNetMasterPageForm(ref masterPageContent);
masterPageContent = masterPageContent.Replace("</?ASPNET_FORM>", "</form>");
// Parse the design for aspnet heads
masterPageContent = masterPageContent.Replace("</ASPNET_HEAD>", String.Format("<head id=\"{0}Head\" runat=\"server\">", Alias.Replace(" ", "")));
masterPageContent = masterPageContent.Replace("</?ASPNET_HEAD>", "</head>");
return masterPageContent;
}
public void ImportDesign(string design)
{
Design = design;
}
public void SaveMasterPageFile(string masterPageContent)
{
//this will trigger the helper and store everything
this.Design = masterPageContent;
}
private void GetAspNetMasterPageForm(ref string design)
{
Match formElement = Regex.Match(design, GetElementRegExp("?ASPNET_FORM", false), RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
if (formElement != null && formElement.Value != "")
{
string formReplace = String.Format("<form id=\"{0}Form\" runat=\"server\">", Alias.Replace(" ", ""));
if (formElement.Groups.Count == 0)
{
formReplace += "<asp:scriptmanager runat=\"server\"></asp:scriptmanager>";
}
design = design.Replace(formElement.Value, formReplace);
}
}
private string GetAspNetMasterPageContentContainer()
{
return String.Format(
"<asp:ContentPlaceHolder ID=\"{0}ContentPlaceHolder\" runat=\"server\"></asp:ContentPlaceHolder>",
Alias.Replace(" ", ""));
}
private void ReplaceElement(ref string design, string elementName, string newElementName, bool checkForQuotes)
{
MatchCollection m =
Regex.Matches(design, GetElementRegExp(elementName, checkForQuotes),
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match match in m)
{
GroupCollection groups = match.Groups;
// generate new element (compensate for a closing trail on single elements ("/"))
string elementAttributes = groups[1].Value;
// test for macro alias
if (elementName == "?UMBRACO_MACRO")
{
Hashtable tags = helpers.xhtml.ReturnAttributes(match.Value);
if (tags["macroAlias"] != null)
elementAttributes = String.Format(" Alias=\"{0}\"", tags["macroAlias"].ToString()) + elementAttributes;
else if (tags["macroalias"] != null)
elementAttributes = String.Format(" Alias=\"{0}\"", tags["macroalias"].ToString()) + elementAttributes;
}
string newElement = "<" + newElementName + " runat=\"server\" " + elementAttributes.Trim() + ">";
if (elementAttributes.EndsWith("/"))
{
elementAttributes = elementAttributes.Substring(0, elementAttributes.Length - 1);
}
else if (groups[0].Value.StartsWith("</"))
// It's a closing element, so generate that instead of a starting element
newElement = "</" + newElementName + ">";
if (checkForQuotes)
{
// if it's inside quotes, we'll change element attribute quotes to single quotes
newElement = newElement.Replace("\"", "'");
newElement = String.Format("\"{0}\"", newElement);
}
design = design.Replace(match.Value, newElement);
}
}
private string GetElementRegExp(string elementName, bool checkForQuotes)
{
if (checkForQuotes)
return String.Format("\"<[^>\\s]*\\b{0}(\\b[^>]*)>\"", elementName);
else
return String.Format("<[^>\\s]*\\b{0}(\\b[^>]*)>", elementName);
}
[Obsolete("Umbraco automatically ensures that template cache is cleared when saving or deleting")]
protected virtual void FlushCache()
{
//ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(Id));
}
public static Template GetTemplate(int id)
{
var found = ApplicationContext.Current.Services.FileService.GetTemplate(id);
return found == null ? null : new Template(found);
}
public static Template Import(XmlNode n, User u)
{
var element = System.Xml.Linq.XElement.Parse(n.OuterXml);
var templates = ApplicationContext.Current.Services.PackagingService.ImportTemplates(element, u.Id);
return new Template(templates.First().Id);
}
#region Events
//EVENTS
/// <summary>
/// The save event handler
/// </summary>
public delegate void SaveEventHandler(Template sender, SaveEventArgs e);
/// <summary>
/// The new event handler
/// </summary>
public delegate void NewEventHandler(Template sender, NewEventArgs e);
/// <summary>
/// The delete event handler
/// </summary>
public delegate void DeleteEventHandler(Template sender, DeleteEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
public new static event SaveEventHandler BeforeSave;
/// <summary>
/// Raises the <see cref="E:BeforeSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected override void FireBeforeSave(SaveEventArgs e)
{
if (BeforeSave != null)
BeforeSave(this, e);
}
/// <summary>
/// Occurs when [after save].
/// </summary>
public new static event SaveEventHandler AfterSave;
/// <summary>
/// Raises the <see cref="E:AfterSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected override void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
AfterSave(this, e);
}
/// <summary>
/// Occurs when [new].
/// </summary>
public static event NewEventHandler New;
/// <summary>
/// Raises the <see cref="E:New"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnNew(NewEventArgs e)
{
if (New != null)
New(this, e);
}
/// <summary>
/// Occurs when [before delete].
/// </summary>
public new static event DeleteEventHandler BeforeDelete;
/// <summary>
/// Raises the <see cref="E:BeforeDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected override void FireBeforeDelete(DeleteEventArgs e)
{
if (BeforeDelete != null)
BeforeDelete(this, e);
}
/// <summary>
/// Occurs when [after delete].
/// </summary>
public new static event DeleteEventHandler AfterDelete;
/// <summary>
/// Raises the <see cref="E:AfterDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected override void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
AfterDelete(this, e);
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Controls.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 DotSpatial.dll for the DotSpatial project
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in September, 2007.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using DotSpatial.Data;
using DotSpatial.Symbology;
using GeoAPI.Geometries;
namespace DotSpatial.Controls
{
public class MapLineLayer : LineLayer, IMapLineLayer
{
#region Events
/// <summary>
/// Fires an event that indicates to the parent map-frame that it should first
/// redraw the specified clip
/// </summary>
public event EventHandler<ClipArgs> BufferChanged;
#endregion
#region Private variables
const int SELECTED = 1;
#endregion
#region Constructors
/// <summary>
/// Creates an empty line layer with a Line FeatureSet that has no members.
/// </summary>
public MapLineLayer()
: base(new FeatureSet(FeatureType.Line))
{
Configure();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="inFeatureSet"></param>
public MapLineLayer(IFeatureSet inFeatureSet)
: base(inFeatureSet)
{
Configure();
OnFinishedLoading();
}
/// <summary>
/// Constructor that also shows progress
/// </summary>
/// <param name="featureSet">A featureset that contains lines</param>
/// <param name="container">An IContainer that the line layer should be created in</param>
public MapLineLayer(IFeatureSet featureSet, ICollection<ILayer> container)
: base(featureSet, container, null)
{
Configure();
OnFinishedLoading();
}
/// <summary>
/// Creates a GeoLineLayer constructor, but passes the boolean notFinished variable to indicate
/// whether or not this layer should fire the FinishedLoading event.
/// </summary>
/// <param name="featureSet"></param>
/// <param name="container"></param>
/// <param name="notFinished"></param>
public MapLineLayer(IFeatureSet featureSet, ICollection<ILayer> container, bool notFinished)
: base(featureSet, container, null)
{
Configure();
if (notFinished == false) OnFinishedLoading();
}
private void Configure()
{
BufferRectangle = new Rectangle(0, 0, 3000, 3000);
ChunkSize = 50000;
}
#endregion
#region Methods
/// <summary>
/// This will draw any features that intersect this region. To specify the features
/// directly, use OnDrawFeatures. This will not clear existing buffer content.
/// For that call Initialize instead.
/// </summary>
/// <param name="args">A GeoArgs clarifying the transformation from geographic to image space</param>
/// <param name="regions">The geographic regions to draw</param>
public virtual void DrawRegions(MapArgs args, List<Extent> regions)
{
// First determine the number of features we are talking about based on region.
List<Rectangle> clipRects = args.ProjToPixel(regions);
if (EditMode)
{
List<IFeature> drawList = new List<IFeature>();
foreach (Extent region in regions)
{
if (region != null)
{
// Use union to prevent duplicates. No sense in drawing more than we have to.
drawList = drawList.Union(DataSet.Select(region)).ToList();
}
}
DrawFeatures(args, drawList, clipRects, true);
}
else
{
List<int> drawList = new List<int>();
List<ShapeRange> shapes = DataSet.ShapeIndices;
for (int shp = 0; shp < shapes.Count; shp++)
{
foreach (Extent region in regions)
{
if (!shapes[shp].Extent.Intersects(region)) continue;
drawList.Add(shp);
break;
}
}
DrawFeatures(args, drawList, clipRects, true);
}
}
/// <summary>
/// Call StartDrawing before using this.
/// </summary>
/// <param name="rectangles">The rectangular region in pixels to clear.</param>
/// <param name= "color">The color to use when clearing. Specifying transparent
/// will replace content with transparent pixels.</param>
public void Clear(List<Rectangle> rectangles, Color color)
{
if (BackBuffer == null) return;
Graphics g = Graphics.FromImage(BackBuffer);
foreach (Rectangle r in rectangles)
{
if (r.IsEmpty == false)
{
g.Clip = new Region(r);
g.Clear(color);
}
}
g.Dispose();
}
/// <summary>
/// This is testing the idea of using an input parameter type that is marked as out
/// instead of a return type.
/// </summary>
/// <param name="result">The result of the creation</param>
/// <returns>Boolean, true if a layer can be created</returns>
public override bool CreateLayerFromSelectedFeatures(out IFeatureLayer result)
{
MapLineLayer temp;
bool resultOk = CreateLayerFromSelectedFeatures(out temp);
result = temp;
return resultOk;
}
/// <summary>
/// This is the strong typed version of the same process that is specific to geo point layers.
/// </summary>
/// <param name="result">The new GeoPointLayer to be created</param>
/// <returns>Boolean, true if there were any values in the selection</returns>
public virtual bool CreateLayerFromSelectedFeatures(out MapLineLayer result)
{
result = null;
if (Selection == null || Selection.Count == 0) return false;
FeatureSet fs = Selection.ToFeatureSet();
result = new MapLineLayer(fs);
return true;
}
/// <summary>
/// If useChunks is true, then this method
/// </summary>
/// <param name="args">The GeoArgs that control how these features should be drawn.</param>
/// <param name="features">The features that should be drawn.</param>
/// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param>
/// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param>
public virtual void DrawFeatures(MapArgs args, List<IFeature> features, List<Rectangle> clipRectangles, bool useChunks)
{
if (useChunks == false)
{
DrawFeatures(args, features);
return;
}
int count = features.Count;
int numChunks = (int)Math.Ceiling(count / (double)ChunkSize);
for (int chunk = 0; chunk < numChunks; chunk++)
{
int numFeatures = ChunkSize;
if (chunk == numChunks - 1) numFeatures = features.Count - (chunk * ChunkSize);
DrawFeatures(args, features.GetRange(chunk * ChunkSize, numFeatures));
if (numChunks > 0 && chunk < numChunks - 1)
{
OnBufferChanged(clipRectangles);
Application.DoEvents();
}
}
}
/// <summary>
/// If useChunks is true, then this method
/// </summary>
/// <param name="args">The GeoArgs that control how these features should be drawn.</param>
/// <param name="indices">The features that should be drawn.</param>
/// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param>
/// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param>
public virtual void DrawFeatures(MapArgs args, List<int> indices, List<Rectangle> clipRectangles, bool useChunks)
{
if (useChunks == false)
{
DrawFeatures(args, indices);
return;
}
int count = indices.Count;
int numChunks = (int)Math.Ceiling(count / (double)ChunkSize);
for (int chunk = 0; chunk < numChunks; chunk++)
{
int numFeatures = ChunkSize;
if (chunk == numChunks - 1) numFeatures = indices.Count - (chunk * ChunkSize);
DrawFeatures(args, indices.GetRange(chunk * ChunkSize, numFeatures));
if (numChunks > 0 && chunk < numChunks - 1)
{
// FinishDrawing();
OnBufferChanged(clipRectangles);
Application.DoEvents();
// this.StartDrawing();
}
}
}
/// <summary>
/// Builds a linestring into the graphics path, using minX, maxY, dx and dy for the transformations.
/// </summary>
internal static void BuildLineString(GraphicsPath path, ILineString ls, double minX, double maxY, double dx, double dy)
{
IList<Coordinate> cs = ls.Coordinates;
List<Point> points = new List<Point>();
Point previousPoint = new Point();
for (int iPoint = 0; iPoint < ls.NumPoints; iPoint++)
{
Coordinate c = cs[iPoint];
Point pt = new Point { X = Convert.ToInt32((c.X - minX) * dx), Y = Convert.ToInt32((maxY - c.Y) * dy) };
if (previousPoint.IsEmpty == false)
{
if (pt.X != previousPoint.X || pt.Y != previousPoint.Y)
{
points.Add(pt);
}
}
else
{
points.Add(pt);
}
previousPoint = pt;
}
if (points.Count < 2) return;
Point[] pointArray = points.ToArray();
path.StartFigure();
path.AddLines(pointArray);
}
internal static void BuildLineString(GraphicsPath path, double[] vertices, ShapeRange shpx, MapArgs args, Rectangle clipRect)
{
double minX = args.MinX;
double maxY = args.MaxY;
double dx = args.Dx;
double dy = args.Dy;
for (int prt = 0; prt < shpx.Parts.Count; prt++)
{
PartRange prtx = shpx.Parts[prt];
int start = prtx.StartIndex;
int end = prtx.EndIndex;
var points = new List<double[]>(end - start + 1);
for (int i = start; i <= end; i++)
{
var pt = new[]
{
(vertices[i*2] - minX)*dx ,
(maxY - vertices[i*2 + 1])*dy
};
points.Add(pt);
}
List<List<double[]>> multiLinestrings;
if (!shpx.Extent.Within(args.GeographicExtents))
{
multiLinestrings = CohenSutherland.ClipLinestring(points, clipRect.Left, clipRect.Top, clipRect.Right, clipRect.Bottom);
}
else
{
multiLinestrings = new List<List<double[]>> { points };
}
foreach (List<double[]> linestring in multiLinestrings)
{
var intPoints = DuplicationPreventer.Clean(linestring).ToArray();
if (intPoints.Length < 2)
{
continue;
}
path.StartFigure();
path.AddLines(intPoints);
}
}
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the back buffer that will be drawn to as part of the initialization process.
/// </summary>
[ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Image BackBuffer { get; set; }
/// <summary>
/// Gets the current buffer.
/// </summary>
[ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Image Buffer { get; set; }
/// <summary>
/// Gets or sets the geographic region represented by the buffer
/// Calling Initialize will set this automatically.
/// </summary>
[ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Envelope BufferEnvelope { get; set; }
/// <summary>
/// Gets or sets the rectangle in pixels to use as the back buffer.
/// Calling Initialize will set this automatically.
/// </summary>
[ShallowCopy, Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Rectangle BufferRectangle { get; set; }
/// <summary>
/// Gets an integer number of chunks for this layer.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int NumChunks
{
get
{
if (DrawingFilter == null) return 0;
return DrawingFilter.NumChunks;
}
}
/// <summary>
/// Gets or sets the label layer that is associated with this line layer.
/// </summary>
[ShallowCopy]
public new IMapLabelLayer LabelLayer
{
get { return base.LabelLayer as IMapLabelLayer; }
set { base.LabelLayer = value; }
}
#endregion
#region Protected Methods
/// <summary>
/// Fires the OnBufferChanged event
/// </summary>
/// <param name="clipRectangles">The Rectangle in pixels</param>
protected virtual void OnBufferChanged(List<Rectangle> clipRectangles)
{
if (BufferChanged != null)
{
ClipArgs e = new ClipArgs(clipRectangles);
BufferChanged(this, e);
}
}
/// <summary>
/// Indiciates that whatever drawing is going to occur has finished and the contents
/// are about to be flipped forward to the front buffer.
/// </summary>
protected virtual void OnFinishDrawing()
{
}
/// <summary>
/// A default method to generate a label layer.
/// </summary>
protected override void OnCreateLabels()
{
LabelLayer = new MapLabelLayer(this);
}
/// <summary>
/// Occurs when a new drawing is started, but after the BackBuffer has been established.
/// </summary>
protected virtual void OnStartDrawing()
{
}
#endregion
#region Private Methods
private void DrawFeatures(MapArgs e, IEnumerable<int> indices)
{
Graphics g = e.Device ?? Graphics.FromImage(BackBuffer);
if (DrawnStatesNeeded)
{
FastDrawnState[] states = DrawnStates;
int max = indices.Max();
if (max >= states.Length)
{
AssignFastDrawnStates();
states = DrawnStates;
}
for (int selectState = 0; selectState < 2; selectState++)
{
foreach (ILineCategory category in Symbology.Categories)
{
// Define the symbology based on the category and selection state
ILineSymbolizer ls = category.Symbolizer;
if (selectState == SELECTED) ls = category.SelectionSymbolizer;
g.SmoothingMode = ls.Smoothing ? SmoothingMode.AntiAlias : SmoothingMode.None;
// Compute a clipping rectangle that accounts for symbology
Rectangle clipRect = ComputeClippingRectangle(e, ls);
// Determine the subset of the specified features that are visible and match the category
ILineCategory lineCategory = category;
int i = selectState;
List<int> drawnFeatures = new List<int>();
foreach (int index in indices)
{
if (index >= states.Length) break;
FastDrawnState state = states[index];
if (state.Category == lineCategory && state.Selected == (i == 1) && state.Visible)
{
drawnFeatures.Add(index);
}
}
GraphicsPath graphPath = new GraphicsPath();
foreach (int shp in drawnFeatures)
{
ShapeRange shape = DataSet.ShapeIndices[shp];
BuildLineString(graphPath, DataSet.Vertex, shape, e, clipRect);
}
double scale = 1;
if (ls.ScaleMode == ScaleMode.Geographic)
{
scale = e.ImageRectangle.Width / e.GeographicExtents.Width;
}
foreach (IStroke stroke in ls.Strokes)
{
stroke.DrawPath(g, graphPath, scale);
}
graphPath.Dispose();
}
}
}
else
{
// Selection state is disabled
// Category is only the very first category
ILineCategory category = Symbology.Categories[0];
ILineSymbolizer ls = category.Symbolizer;
g.SmoothingMode = ls.Smoothing ? SmoothingMode.AntiAlias : SmoothingMode.None;
Rectangle clipRect = ComputeClippingRectangle(e, ls);
// Determine the subset of the specified features that are visible and match the category
GraphicsPath graphPath = new GraphicsPath();
foreach (int shp in indices)
{
ShapeRange shape = DataSet.ShapeIndices[shp];
BuildLineString(graphPath, DataSet.Vertex, shape, e, clipRect);
}
double scale = 1;
if (ls.ScaleMode == ScaleMode.Geographic)
{
scale = e.ImageRectangle.Width / e.GeographicExtents.Width;
}
foreach (IStroke stroke in ls.Strokes)
{
stroke.DrawPath(g, graphPath, scale);
}
graphPath.Dispose();
}
if (e.Device == null) g.Dispose();
}
// This draws the individual line features
private void DrawFeatures(MapArgs e, IEnumerable<IFeature> features)
{
Graphics g = e.Device ?? Graphics.FromImage(BackBuffer);
for (int selectState = 0; selectState < 2; selectState++)
{
foreach (ILineCategory category in Symbology.Categories)
{
// Define the symbology based on the category and selection state
ILineSymbolizer ls = category.Symbolizer;
if (selectState == SELECTED) ls = category.SelectionSymbolizer;
g.SmoothingMode = ls.Smoothing ? SmoothingMode.AntiAlias : SmoothingMode.None;
Rectangle clipRect = ComputeClippingRectangle(e, ls);
// Determine the subset of the specified features that are visible and match the category
ILineCategory lineCategory = category;
int i = selectState;
Func<IDrawnState, bool> isMember = state =>
state.SchemeCategory == lineCategory &&
state.IsVisible &&
state.IsSelected == (i == 1);
var drawnFeatures = from feature in features
where isMember(DrawingFilter[feature])
select feature;
GraphicsPath graphPath = new GraphicsPath();
foreach (IFeature f in drawnFeatures)
{
BuildLineString(graphPath, DataSet.Vertex, f.ShapeIndex, e, clipRect);
}
double scale = 1;
if (ls.ScaleMode == ScaleMode.Geographic)
{
scale = e.ImageRectangle.Width / e.GeographicExtents.Width;
}
foreach (IStroke stroke in ls.Strokes)
{
stroke.DrawPath(g, graphPath, scale);
}
graphPath.Dispose();
}
}
if (e.Device == null) g.Dispose();
}
private static Rectangle ComputeClippingRectangle(MapArgs args, ILineSymbolizer ls)
{
// Compute a clipping rectangle that accounts for symbology
int maxLineWidth = 2 * (int)Math.Ceiling(ls.GetWidth());
Rectangle clipRect = args.ProjToPixel(args.GeographicExtents); //use GeographicExtent for clipping because ImageRect clips to much
clipRect.Inflate(maxLineWidth, maxLineWidth);
return clipRect;
}
private static void FastBuildLine(GraphicsPath graphPath, double[] vertices, ShapeRange shpx, double minX, double maxY, double dx, double dy)
{
for (int prt = 0; prt < shpx.Parts.Count; prt++)
{
PartRange prtx = shpx.Parts[prt];
int start = prtx.StartIndex;
int end = prtx.EndIndex;
List<Point> partPoints = new List<Point>();
Point previousPoint = new Point();
for (int i = start; i <= end; i++)
{
if (double.IsNaN(vertices[i * 2]) || double.IsNaN(vertices[i * 2 + 1])) continue;
var pt = new Point
{
X = Convert.ToInt32((vertices[i * 2] - minX) * dx),
Y = Convert.ToInt32((maxY - vertices[i * 2 + 1]) * dy)
};
if (i == 0 || (pt.X != previousPoint.X || pt.Y != previousPoint.Y))
{
// Don't add the same point twice
partPoints.Add(pt);
previousPoint = pt;
}
}
if (partPoints.Count < 2) continue; // we need two distinct points to make a line
graphPath.StartFigure();
graphPath.AddLines(partPoints.ToArray());
}
}
#endregion
}
}
| |
/**
* _____ _____ _____ _____ __ _____ _____ _____ _____
* | __| | | | | | | | | __| | |
* |__ | | | | | | | | | |__| | | | |- -| --|
* |_____|_____|_|_|_|_____| |_____|_____|_____|_____|_____|
*
* UNICORNS AT WARP SPEED SINCE 2010
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace SumoLogic.Logging.Log4Net
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using log4net.Appender;
using log4net.Core;
using SumoLogic.Logging.Common.Log;
using SumoLogic.Logging.Common.Queue;
using SumoLogic.Logging.Common.Sender;
/// <summary>
/// Buffered SumoLogic Appender implementation.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Disposing of disposabled donde on OnClose method, called by base class")]
public class BufferedSumoLogicAppender : AppenderSkeleton
{
/// <summary>
/// The Sumo HTTP sender executor.
/// </summary>
private Timer flushBufferTimer;
/// <summary>
/// The messages queue.
/// </summary>
private volatile BufferWithEviction<string> messagesQueue;
/// <summary>
/// The flush buffer task.
/// </summary>
private SumoLogicMessageSenderBufferFlushingTask flushBufferTask;
/// <summary>
/// Initializes a new instance of the <see cref="BufferedSumoLogicAppender"/> class.
/// </summary>
public BufferedSumoLogicAppender()
: this(null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferedSumoLogicAppender"/> class.
/// </summary>
/// <param name="log">The log service.</param>
/// <param name="httpMessageHandler">The HTTP message handler.</param>
public BufferedSumoLogicAppender(SumoLogic.Logging.Common.Log.ILog log, HttpMessageHandler httpMessageHandler)
{
this.SourceName = "Log4Net-SumoObject";
this.ConnectionTimeout = 60000;
this.RetryInterval = 10000;
this.MessagesPerRequest = 100;
this.MaxFlushInterval = 10000;
this.FlushingAccuracy = 250;
this.MaxQueueSizeBytes = 1000000;
this.LogLog = log ?? new DummyLog();
this.HttpMessageHandler = httpMessageHandler;
}
/// <summary>
/// Gets or sets the SumoLogic server URL.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Property needs to be exposed as string for allowing configuration")]
public string Url
{
get;
set;
}
/// <summary>
/// Gets or sets the name used for messages sent to SumoLogic server (sent as X-Sumo-Name header).
/// </summary>
public string SourceName
{
get;
set;
}
/// <summary>
/// Gets or sets the source category for messages sent to SumoLogic server
/// </summary>
public string SourceCategory
{
get;
set;
}
/// <summary>
/// Gets or sets the source host for messages sent to SumoLogic server
/// </summary>
public string SourceHost
{
get;
set;
}
/// <summary>
/// Gets or sets the send message retry interval, in milliseconds.
/// </summary>
public long RetryInterval
{
get;
set;
}
/// <summary>
/// Gets or sets the connection timeout, in milliseconds.
/// </summary>
public long ConnectionTimeout
{
get;
set;
}
/// <summary>
/// Gets or sets how often the messages queue is checked for messages to send, in milliseconds.
/// </summary>
public long FlushingAccuracy
{
get;
set;
}
/// <summary>
/// Gets or sets the maximum interval between flushes, in milliseconds.
/// </summary>
public long MaxFlushInterval
{
get;
set;
}
/// <summary>
/// Gets or sets how many messages need to be in the queue before flushing.
/// </summary>
public long MessagesPerRequest
{
get;
set;
}
/// <summary>
/// Gets or sets the messages queue capacity, in bytes.
/// </summary>
/// <remarks>Messages are dropped When the queue capacity is exceeded.</remarks>
public long MaxQueueSizeBytes
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether the console log should be used.
/// </summary>
public bool UseConsoleLog
{
get;
set;
}
protected override bool RequiresLayout { get { return true; } }
/// <summary>
/// Gets or sets the log service.
/// </summary>
private SumoLogic.Logging.Common.Log.ILog LogLog
{
get;
set;
}
/// <summary>
/// Gets or sets the HTTP message handler.
/// </summary>
private HttpMessageHandler HttpMessageHandler
{
get;
set;
}
/// <summary>
/// Gets or sets the SumoLogic message sender.
/// </summary>
private SumoLogicMessageSender SumoLogicMessageSender
{
get;
set;
}
/// <summary>
/// Initialize the appender based on the options set
/// </summary>
/// <remarks>
/// This is part of the log4net.Core.IOptionHandler delayed object activation scheme. The ActivateOptions() method must be called
/// on this object after the configuration properties have been set. Until ActivateOptions() is called this object is in an undefined
/// state and must not be used. If any of the configuration properties are modified then ActivateOptions() must be called again.
/// </remarks>
public override void ActivateOptions()
{
if (this.UseConsoleLog)
{
this.ActivateConsoleLog();
}
if (this.LogLog.IsDebugEnabled)
{
this.LogLog.Debug("Activating options");
}
// Initialize the messages queue
if (this.messagesQueue == null)
{
this.messagesQueue = new BufferWithFifoEviction<string>(this.MaxQueueSizeBytes, new StringLengthCostAssigner(), this.LogLog);
}
else
{
this.messagesQueue.Capacity = this.MaxQueueSizeBytes;
}
// Initialize the sender
if (this.SumoLogicMessageSender == null)
{
this.SumoLogicMessageSender = new SumoLogicMessageSender(this.HttpMessageHandler, this.LogLog, "sumo-log4net-buffered-sender");
}
this.SumoLogicMessageSender.RetryInterval = TimeSpan.FromMilliseconds(this.RetryInterval);
this.SumoLogicMessageSender.ConnectionTimeout = TimeSpan.FromMilliseconds(this.ConnectionTimeout);
this.SumoLogicMessageSender.Url = string.IsNullOrEmpty(this.Url) ? null : new Uri(this.Url);
// Initialize flusher
if (this.flushBufferTimer != null)
{
this.flushBufferTimer.Dispose();
}
this.flushBufferTask = new SumoLogicMessageSenderBufferFlushingTask(
this.messagesQueue,
this.SumoLogicMessageSender,
TimeSpan.FromMilliseconds(this.MaxFlushInterval),
this.MessagesPerRequest,
this.SourceName,
this.SourceCategory,
this.SourceHost,
this.LogLog);
this.flushBufferTimer = new Timer(
_ => flushBufferTask.Run(), // No task await to avoid unhandled exception
null,
TimeSpan.FromMilliseconds(0),
TimeSpan.FromMilliseconds(this.FlushingAccuracy));
}
/// <summary>
/// Performs the actual logging of events.
/// </summary>
/// <param name="loggingEvent">The event to append.</param>
protected override void Append(LoggingEvent loggingEvent)
{
if (loggingEvent == null)
{
throw new ArgumentNullException("loggingEvent");
}
if (this.SumoLogicMessageSender == null || !this.SumoLogicMessageSender.CanSend)
{
if (this.LogLog.IsWarnEnabled)
{
this.LogLog.Warn("Appender not initialized. Dropping log entry");
}
return;
}
var bodyBuilder = new StringBuilder();
using (var textWriter = new StringWriter(bodyBuilder, CultureInfo.InvariantCulture))
{
Layout.Format(textWriter, loggingEvent);
if (Layout.IgnoresException)
{
textWriter.Write(loggingEvent.GetExceptionString());
textWriter.WriteLine();
}
}
this.messagesQueue.Add(bodyBuilder.ToString());
}
/// <summary>
/// Is called when the appender is closed. Derived classes should override this method if resources need to be released.
/// </summary>
/// <remarks>
/// Releases any resources allocated within the appender such as file handles, network connections, etc.
/// It is a programming error to append to a closed appender.
/// </remarks>
protected override void OnClose()
{
try
{
this.flushBufferTimer?.Dispose();
this.flushBufferTimer = null;
Flush(5000);
this.SumoLogicMessageSender?.Dispose();
this.SumoLogicMessageSender = null;
}
catch (Exception ex)
{
this.LogLog.Warn($"Appender closed with error. {ex.GetType()}: {ex.Message}");
}
}
/// <summary>
/// Activate Console Log.
/// </summary>
private void ActivateConsoleLog()
{
this.LogLog = new ConsoleLog();
}
/// <summary>
/// Flush the any remaining messages that are buffered.
/// </summary>
/// <param name="millisecondsTimeout"></param>
/// <returns></returns>
public override bool Flush(int millisecondsTimeout)
{
try
{
var flushTask = flushBufferTask?.FlushAndSend() ?? Task.FromResult<object>(null);
return Task.WhenAny(flushTask, Task.Delay(TimeSpan.FromMilliseconds(millisecondsTimeout))).GetAwaiter().GetResult().Id == flushTask.Id;
}
catch (Exception ex)
{
this.LogLog.Warn($"Appender flush with error. {ex.GetType()}: {ex.Message}");
return false; // Not allowed to throw exceptions, as it will affect flush of other appenders
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace System
{
// Provides Windows-based support for System.Console.
internal static class ConsolePal
{
private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers
private static IntPtr s_InvalidHandleValue = new IntPtr(-1);
public static Stream OpenStandardInput()
{
return GetStandardFile(Interop.mincore.HandleTypes.STD_INPUT_HANDLE, FileAccess.Read);
}
public static Stream OpenStandardOutput()
{
return GetStandardFile(Interop.mincore.HandleTypes.STD_OUTPUT_HANDLE, FileAccess.Write);
}
public static Stream OpenStandardError()
{
return GetStandardFile(Interop.mincore.HandleTypes.STD_ERROR_HANDLE, FileAccess.Write);
}
private static IntPtr InputHandle
{
get { return Interop.mincore.GetStdHandle(Interop.mincore.HandleTypes.STD_INPUT_HANDLE); }
}
private static IntPtr OutputHandle
{
get { return Interop.mincore.GetStdHandle(Interop.mincore.HandleTypes.STD_OUTPUT_HANDLE); }
}
private static IntPtr ErrorHandle
{
get { return Interop.mincore.GetStdHandle(Interop.mincore.HandleTypes.STD_ERROR_HANDLE); }
}
private static Stream GetStandardFile(int handleType, FileAccess access)
{
IntPtr handle = Interop.mincore.GetStdHandle(handleType);
// If someone launches a managed process via CreateProcess, stdout,
// stderr, & stdin could independently be set to INVALID_HANDLE_VALUE.
// Additionally they might use 0 as an invalid handle. We also need to
// ensure that if the handle is meant to be writable it actually is.
if (handle == IntPtr.Zero || handle == s_InvalidHandleValue ||
(access != FileAccess.Read && !ConsoleHandleIsWritable(handle)))
{
return Stream.Null;
}
return new WindowsConsoleStream(handle, access, GetUseFileAPIs(handleType));
}
// Checks whether stdout or stderr are writable. Do NOT pass
// stdin here! The console handles are set to values like 3, 7,
// and 11 OR if you've been created via CreateProcess, possibly -1
// or 0. -1 is definitely invalid, while 0 is probably invalid.
// Also note each handle can independently be invalid or good.
// For Windows apps, the console handles are set to values like 3, 7,
// and 11 but are invalid handles - you may not write to them. However,
// you can still spawn a Windows app via CreateProcess and read stdout
// and stderr. So, we always need to check each handle independently for validity
// by trying to write or read to it, unless it is -1.
private static unsafe bool ConsoleHandleIsWritable(IntPtr outErrHandle)
{
// Windows apps may have non-null valid looking handle values for
// stdin, stdout and stderr, but they may not be readable or
// writable. Verify this by calling WriteFile in the
// appropriate modes. This must handle console-less Windows apps.
int bytesWritten;
byte junkByte = 0x41;
int r = Interop.mincore.WriteFile(outErrHandle, &junkByte, 0, out bytesWritten, IntPtr.Zero);
return r != 0; // In Win32 apps w/ no console, bResult should be 0 for failure.
}
public static Encoding InputEncoding
{
get { return EncodingHelper.GetSupportedConsoleEncoding((int)Interop.mincore.GetConsoleCP()); }
}
public static void SetConsoleInputEncoding(Encoding enc)
{
if (enc.CodePage != Encoding.Unicode.CodePage)
{
if (!Interop.mincore.SetConsoleCP(enc.CodePage))
Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
}
public static Encoding OutputEncoding
{
get { return EncodingHelper.GetSupportedConsoleEncoding((int)Interop.mincore.GetConsoleOutputCP()); }
}
public static void SetConsoleOutputEncoding(Encoding enc)
{
if (enc.CodePage != Encoding.Unicode.CodePage)
{
if (!Interop.mincore.SetConsoleOutputCP(enc.CodePage))
Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
}
private static bool GetUseFileAPIs(int handleType)
{
switch (handleType)
{
case Interop.mincore.HandleTypes.STD_INPUT_HANDLE:
return Console.InputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsInputRedirected;
case Interop.mincore.HandleTypes.STD_OUTPUT_HANDLE:
return Console.OutputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsOutputRedirected;
case Interop.mincore.HandleTypes.STD_ERROR_HANDLE:
return Console.OutputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsErrorRedirected;
default:
// This can never happen.
Debug.Assert(false, "Unexpected handleType value (" + handleType + ")");
return true;
}
}
/// <summary>Gets whether Console.In is targeting a terminal display.</summary>
public static bool IsInputRedirectedCore()
{
return IsHandleRedirected(InputHandle);
}
/// <summary>Gets whether Console.Out is targeting a terminal display.</summary>
public static bool IsOutputRedirectedCore()
{
return IsHandleRedirected(OutputHandle);
}
/// <summary>Gets whether Console.In is targeting a terminal display.</summary>
public static bool IsErrorRedirectedCore()
{
return IsHandleRedirected(ErrorHandle);
}
private static bool IsHandleRedirected(IntPtr handle)
{
// If handle is not to a character device, we must be redirected:
uint fileType = Interop.mincore.GetFileType(handle);
if ((fileType & Interop.mincore.FileTypes.FILE_TYPE_CHAR) != Interop.mincore.FileTypes.FILE_TYPE_CHAR)
return true;
// We are on a char device if GetConsoleMode succeeds and so we are not redirected.
return (!Interop.mincore.IsGetConsoleModeCallSuccessful(handle));
}
internal static TextReader GetOrCreateReader()
{
Stream inputStream = OpenStandardInput();
return SyncTextReader.GetSynchronizedTextReader(inputStream == Stream.Null ?
StreamReader.Null :
new StreamReader(
stream: inputStream,
encoding: new ConsoleEncoding(Console.InputEncoding),
detectEncodingFromByteOrderMarks: false,
bufferSize: DefaultConsoleBufferSize,
leaveOpen: true));
}
// Use this for blocking in Console.ReadKey, which needs to protect itself in case multiple threads call it simultaneously.
// Use a ReadKey-specific lock though, to allow other fields to be initialized on this type.
private static readonly Object s_readKeySyncObject = new object();
// ReadLine & Read can't use this because they need to use ReadFile
// to be able to handle redirected input. We have to accept that
// we will lose repeated keystrokes when someone switches from
// calling ReadKey to calling Read or ReadLine. Those methods should
// ideally flush this cache as well.
[System.Security.SecurityCritical] // auto-generated
private static Interop.InputRecord _cachedInputRecord;
// Skip non key events. Generally we want to surface only KeyDown event
// and suppress KeyUp event from the same Key press but there are cases
// where the assumption of KeyDown-KeyUp pairing for a given key press
// is invalid. For example in IME Unicode keyboard input, we often see
// only KeyUp until the key is released.
[System.Security.SecurityCritical] // auto-generated
private static bool IsKeyDownEvent(Interop.InputRecord ir)
{
return (ir.eventType == Interop.KEY_EVENT && ir.keyEvent.keyDown);
}
[System.Security.SecurityCritical] // auto-generated
private static bool IsModKey(Interop.InputRecord ir)
{
// We should also skip over Shift, Control, and Alt, as well as caps lock.
// Apparently we don't need to check for 0xA0 through 0xA5, which are keys like
// Left Control & Right Control. See the ConsoleKey enum for these values.
short keyCode = ir.keyEvent.virtualKeyCode;
return ((keyCode >= 0x10 && keyCode <= 0x12)
|| keyCode == 0x14 || keyCode == 0x90 || keyCode == 0x91);
}
[Flags]
internal enum ControlKeyState
{
RightAltPressed = 0x0001,
LeftAltPressed = 0x0002,
RightCtrlPressed = 0x0004,
LeftCtrlPressed = 0x0008,
ShiftPressed = 0x0010,
NumLockOn = 0x0020,
ScrollLockOn = 0x0040,
CapsLockOn = 0x0080,
EnhancedKey = 0x0100
}
// For tracking Alt+NumPad unicode key sequence. When you press Alt key down
// and press a numpad unicode decimal sequence and then release Alt key, the
// desired effect is to translate the sequence into one Unicode KeyPress.
// We need to keep track of the Alt+NumPad sequence and surface the final
// unicode char alone when the Alt key is released.
[System.Security.SecurityCritical] // auto-generated
private static bool IsAltKeyDown(Interop.InputRecord ir)
{
return (((ControlKeyState)ir.keyEvent.controlKeyState)
& (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0;
}
private const int NumberLockVKCode = 0x90;
private const int CapsLockVKCode = 0x14;
public static bool NumberLock
{
get
{
try
{
short s = Interop.mincore.GetKeyState(NumberLockVKCode);
return (s & 1) == 1;
}
catch (Exception)
{
// Since we depend on an extension api-set here
// it is not guaranteed to work across the board.
// In case of exception we simply throw PNSE
throw new PlatformNotSupportedException();
}
}
}
public static bool CapsLock
{
get
{
try
{
short s = Interop.mincore.GetKeyState(CapsLockVKCode);
return (s & 1) == 1;
}
catch (Exception)
{
// Since we depend on an extension api-set here
// it is not guaranteed to work across the board.
// In case of exception we simply throw PNSE
throw new PlatformNotSupportedException();
}
}
}
public static bool KeyAvailable
{
get
{
if (_cachedInputRecord.eventType == Interop.KEY_EVENT)
return true;
Interop.InputRecord ir = new Interop.InputRecord();
int numEventsRead = 0;
while (true)
{
bool r = Interop.mincore.PeekConsoleInput(InputHandle, out ir, 1, out numEventsRead);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.mincore.Errors.ERROR_INVALID_HANDLE)
throw new InvalidOperationException(SR.InvalidOperation_ConsoleKeyAvailableOnFile);
throw Win32Marshal.GetExceptionForWin32Error(errorCode, "stdin");
}
if (numEventsRead == 0)
return false;
// Skip non key-down && mod key events.
if (!IsKeyDownEvent(ir) || IsModKey(ir))
{
r = Interop.mincore.ReadConsoleInput(InputHandle, out ir, 1, out numEventsRead);
if (!r)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
else
{
return true;
}
}
} // get
}
private const short AltVKCode = 0x12;
public static ConsoleKeyInfo ReadKey(bool intercept)
{
Interop.InputRecord ir;
int numEventsRead = -1;
bool r;
lock (s_readKeySyncObject)
{
if (_cachedInputRecord.eventType == Interop.KEY_EVENT)
{
// We had a previous keystroke with repeated characters.
ir = _cachedInputRecord;
if (_cachedInputRecord.keyEvent.repeatCount == 0)
_cachedInputRecord.eventType = -1;
else
{
_cachedInputRecord.keyEvent.repeatCount--;
}
// We will return one key from this method, so we decrement the
// repeatCount here, leaving the cachedInputRecord in the "queue".
}
else
{ // We did NOT have a previous keystroke with repeated characters:
while (true)
{
r = Interop.mincore.ReadConsoleInput(InputHandle, out ir, 1, out numEventsRead);
if (!r || numEventsRead == 0)
{
// This will fail when stdin is redirected from a file or pipe.
// We could theoretically call Console.Read here, but I
// think we might do some things incorrectly then.
throw new InvalidOperationException(SR.InvalidOperation_ConsoleReadKeyOnFile);
}
short keyCode = ir.keyEvent.virtualKeyCode;
// First check for non-keyboard events & discard them. Generally we tap into only KeyDown events and ignore the KeyUp events
// but it is possible that we are dealing with a Alt+NumPad unicode key sequence, the final unicode char is revealed only when
// the Alt key is released (i.e when the sequence is complete). To avoid noise, when the Alt key is down, we should eat up
// any intermediate key strokes (from NumPad) that collectively forms the Unicode character.
if (!IsKeyDownEvent(ir))
{
// REVIEW: Unicode IME input comes through as KeyUp event with no accompanying KeyDown.
if (keyCode != AltVKCode)
continue;
}
char ch = (char)ir.keyEvent.uChar;
// In a Alt+NumPad unicode sequence, when the alt key is released uChar will represent the final unicode character, we need to
// surface this. VirtualKeyCode for this event will be Alt from the Alt-Up key event. This is probably not the right code,
// especially when we don't expose ConsoleKey.Alt, so this will end up being the hex value (0x12). VK_PACKET comes very
// close to being useful and something that we could look into using for this purpose...
if (ch == 0)
{
// Skip mod keys.
if (IsModKey(ir))
continue;
}
// When Alt is down, it is possible that we are in the middle of a Alt+NumPad unicode sequence.
// Escape any intermediate NumPad keys whether NumLock is on or not (notepad behavior)
ConsoleKey key = (ConsoleKey)keyCode;
if (IsAltKeyDown(ir) && ((key >= ConsoleKey.NumPad0 && key <= ConsoleKey.NumPad9)
|| (key == ConsoleKey.Clear) || (key == ConsoleKey.Insert)
|| (key >= ConsoleKey.PageUp && key <= ConsoleKey.DownArrow)))
{
continue;
}
if (ir.keyEvent.repeatCount > 1)
{
ir.keyEvent.repeatCount--;
_cachedInputRecord = ir;
}
break;
}
} // we did NOT have a previous keystroke with repeated characters.
}
ControlKeyState state = (ControlKeyState)ir.keyEvent.controlKeyState;
bool shift = (state & ControlKeyState.ShiftPressed) != 0;
bool alt = (state & (ControlKeyState.LeftAltPressed | ControlKeyState.RightAltPressed)) != 0;
bool control = (state & (ControlKeyState.LeftCtrlPressed | ControlKeyState.RightCtrlPressed)) != 0;
ConsoleKeyInfo info = new ConsoleKeyInfo((char)ir.keyEvent.uChar, (ConsoleKey)ir.keyEvent.virtualKeyCode, shift, alt, control);
if (!intercept)
Console.Write(ir.keyEvent.uChar);
return info;
}
public static bool TreatControlCAsInput
{
get
{
IntPtr handle = InputHandle;
if (handle == s_InvalidHandleValue)
throw new IOException(SR.IO_NoConsole);
int mode = 0;
if (!Interop.mincore.GetConsoleMode(handle, out mode))
Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
return (mode & Interop.mincore.ENABLE_PROCESSED_INPUT) == 0;
}
set
{
IntPtr handle = InputHandle;
if (handle == s_InvalidHandleValue)
throw new IOException(SR.IO_NoConsole);
int mode = 0;
Interop.mincore.GetConsoleMode(handle, out mode); // failure ignored in full framework
if (value)
{
mode &= ~Interop.mincore.ENABLE_PROCESSED_INPUT;
}
else
{
mode |= Interop.mincore.ENABLE_PROCESSED_INPUT;
}
if (!Interop.mincore.SetConsoleMode(handle, mode))
Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
}
// For ResetColor
private static volatile bool _haveReadDefaultColors;
private static volatile byte _defaultColors;
public static ConsoleColor BackgroundColor
{
get
{
bool succeeded;
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
return succeeded ?
ColorAttributeToConsoleColor((Interop.mincore.Color)csbi.wAttributes & Interop.mincore.Color.BackgroundMask) :
ConsoleColor.Black; // for code that may be used from Windows app w/ no console
}
set
{
Interop.mincore.Color c = ConsoleColorToColorAttribute(value, true);
bool succeeded;
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
// For code that may be used from Windows app w/ no console
if (!succeeded)
return;
Debug.Assert(_haveReadDefaultColors, "Setting the background color before we've read the default foreground color!");
short attrs = csbi.wAttributes;
attrs &= ~((short)Interop.mincore.Color.BackgroundMask);
// C#'s bitwise-or sign-extends to 32 bits.
attrs = (short)(((uint)(ushort)attrs) | ((uint)(ushort)c));
// Ignore errors here - there are some scenarios for running code that wants
// to print in colors to the console in a Windows application.
Interop.mincore.SetConsoleTextAttribute(OutputHandle, attrs);
}
}
public static ConsoleColor ForegroundColor
{
get
{
bool succeeded;
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
// For code that may be used from Windows app w/ no console
return succeeded ?
ColorAttributeToConsoleColor((Interop.mincore.Color)csbi.wAttributes & Interop.mincore.Color.ForegroundMask) :
ConsoleColor.Gray;
}
set
{
Interop.mincore.Color c = ConsoleColorToColorAttribute(value, false);
bool succeeded;
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
// For code that may be used from Windows app w/ no console
if (!succeeded)
return;
Debug.Assert(_haveReadDefaultColors, "Setting the foreground color before we've read the default foreground color!");
short attrs = csbi.wAttributes;
attrs &= ~((short)Interop.mincore.Color.ForegroundMask);
// C#'s bitwise-or sign-extends to 32 bits.
attrs = (short)(((uint)(ushort)attrs) | ((uint)(ushort)c));
// Ignore errors here - there are some scenarios for running code that wants
// to print in colors to the console in a Windows application.
Interop.mincore.SetConsoleTextAttribute(OutputHandle, attrs);
}
}
public static void ResetColor()
{
if (!_haveReadDefaultColors) // avoid the costs of GetBufferInfo if we already know we checked it
{
bool succeeded;
GetBufferInfo(false, out succeeded);
if (!succeeded)
return; // For code that may be used from Windows app w/ no console
Debug.Assert(_haveReadDefaultColors, "Resetting color before we've read the default foreground color!");
}
// Ignore errors here - there are some scenarios for running code that wants
// to print in colors to the console in a Windows application.
Interop.mincore.SetConsoleTextAttribute(OutputHandle, (short)(ushort)_defaultColors);
}
public static int CursorSize
{
get
{
Interop.mincore.CONSOLE_CURSOR_INFO cci;
if (!Interop.mincore.GetConsoleCursorInfo(OutputHandle, out cci))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
return cci.dwSize;
}
set
{
// Value should be a percentage from [1, 100].
if (value < 1 || value > 100)
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_CursorSize);
Contract.EndContractBlock();
Interop.mincore.CONSOLE_CURSOR_INFO cci;
if (!Interop.mincore.GetConsoleCursorInfo(OutputHandle, out cci))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
cci.dwSize = value;
if (!Interop.mincore.SetConsoleCursorInfo(OutputHandle, ref cci))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
}
public static bool CursorVisible
{
get
{
Interop.mincore.CONSOLE_CURSOR_INFO cci;
if (!Interop.mincore.GetConsoleCursorInfo(OutputHandle, out cci))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
return cci.bVisible;
}
set
{
Interop.mincore.CONSOLE_CURSOR_INFO cci;
if (!Interop.mincore.GetConsoleCursorInfo(OutputHandle, out cci))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
cci.bVisible = value;
if (!Interop.mincore.SetConsoleCursorInfo(OutputHandle, ref cci))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
}
public static int CursorLeft
{
get
{
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.dwCursorPosition.X;
}
}
public static int CursorTop
{
get
{
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.dwCursorPosition.Y;
}
}
// Although msdn states that the max allowed limit is 65K,
// desktop limits this to 24500 as buffer sizes greater than it
// throw.
private const int MaxConsoleTitleLength = 24500;
public static string Title
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
string title = null;
int titleLength = -1;
int r = Interop.mincore.GetConsoleTitle(out title, out titleLength);
if (0 != r)
{
throw Win32Marshal.GetExceptionForWin32Error(r, string.Empty);
}
if (titleLength > MaxConsoleTitleLength)
throw new InvalidOperationException(SR.ArgumentOutOfRange_ConsoleTitleTooLong);
Debug.Assert(title.Length == titleLength);
return title;
}
[System.Security.SecuritySafeCritical] // auto-generated
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.Length > MaxConsoleTitleLength)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_ConsoleTitleTooLong);
Contract.EndContractBlock();
if (!Interop.mincore.SetConsoleTitle(value))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
}
private const int BeepFrequencyInHz = 800;
private const int BeepDurationInMs = 200;
public static void Beep()
{
Interop.mincore.Beep(BeepFrequencyInHz, BeepDurationInMs);
}
private const int MinBeepFrequency = 37;
private const int MaxBeepFrequency = 32767;
public static void Beep(int frequency, int duration)
{
if (frequency < MinBeepFrequency || frequency > MaxBeepFrequency)
throw new ArgumentOutOfRangeException(nameof(frequency), frequency, SR.Format(SR.ArgumentOutOfRange_BeepFrequency, MinBeepFrequency, MaxBeepFrequency));
if (duration <= 0)
throw new ArgumentOutOfRangeException(nameof(duration), duration, SR.ArgumentOutOfRange_NeedPosNum);
Contract.EndContractBlock();
Interop.mincore.Beep(frequency, duration);
}
public unsafe static void MoveBufferArea(int sourceLeft, int sourceTop,
int sourceWidth, int sourceHeight, int targetLeft, int targetTop,
char sourceChar, ConsoleColor sourceForeColor,
ConsoleColor sourceBackColor)
{
if (sourceForeColor < ConsoleColor.Black || sourceForeColor > ConsoleColor.White)
throw new ArgumentException(SR.Arg_InvalidConsoleColor, nameof(sourceForeColor));
if (sourceBackColor < ConsoleColor.Black || sourceBackColor > ConsoleColor.White)
throw new ArgumentException(SR.Arg_InvalidConsoleColor, nameof(sourceBackColor));
Contract.EndContractBlock();
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
Interop.mincore.COORD bufferSize = csbi.dwSize;
if (sourceLeft < 0 || sourceLeft > bufferSize.X)
throw new ArgumentOutOfRangeException(nameof(sourceLeft), sourceLeft, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (sourceTop < 0 || sourceTop > bufferSize.Y)
throw new ArgumentOutOfRangeException(nameof(sourceTop), sourceTop, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (sourceWidth < 0 || sourceWidth > bufferSize.X - sourceLeft)
throw new ArgumentOutOfRangeException(nameof(sourceWidth), sourceWidth, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (sourceHeight < 0 || sourceTop > bufferSize.Y - sourceHeight)
throw new ArgumentOutOfRangeException(nameof(sourceHeight), sourceHeight, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
// Note: if the target range is partially in and partially out
// of the buffer, then we let the OS clip it for us.
if (targetLeft < 0 || targetLeft > bufferSize.X)
throw new ArgumentOutOfRangeException(nameof(targetLeft), targetLeft, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (targetTop < 0 || targetTop > bufferSize.Y)
throw new ArgumentOutOfRangeException(nameof(targetTop), targetTop, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
// If we're not doing any work, bail out now (Windows will return
// an error otherwise)
if (sourceWidth == 0 || sourceHeight == 0)
return;
// Read data from the original location, blank it out, then write
// it to the new location. This will handle overlapping source and
// destination regions correctly.
// Read the old data
Interop.mincore.CHAR_INFO[] data = new Interop.mincore.CHAR_INFO[sourceWidth * sourceHeight];
bufferSize.X = (short)sourceWidth;
bufferSize.Y = (short)sourceHeight;
Interop.mincore.COORD bufferCoord = new Interop.mincore.COORD();
Interop.mincore.SMALL_RECT readRegion = new Interop.mincore.SMALL_RECT();
readRegion.Left = (short)sourceLeft;
readRegion.Right = (short)(sourceLeft + sourceWidth - 1);
readRegion.Top = (short)sourceTop;
readRegion.Bottom = (short)(sourceTop + sourceHeight - 1);
bool r;
fixed (Interop.mincore.CHAR_INFO* pCharInfo = data)
r = Interop.mincore.ReadConsoleOutput(OutputHandle, pCharInfo, bufferSize, bufferCoord, ref readRegion);
if (!r)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
// Overwrite old section
Interop.mincore.COORD writeCoord = new Interop.mincore.COORD();
writeCoord.X = (short)sourceLeft;
Interop.mincore.Color c = ConsoleColorToColorAttribute(sourceBackColor, true);
c |= ConsoleColorToColorAttribute(sourceForeColor, false);
short attr = (short)c;
int numWritten;
for (int i = sourceTop; i < sourceTop + sourceHeight; i++)
{
writeCoord.Y = (short)i;
r = Interop.mincore.FillConsoleOutputCharacter(OutputHandle, sourceChar, sourceWidth, writeCoord, out numWritten);
Debug.Assert(numWritten == sourceWidth, "FillConsoleOutputCharacter wrote the wrong number of chars!");
if (!r)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
r = Interop.mincore.FillConsoleOutputAttribute(OutputHandle, attr, sourceWidth, writeCoord, out numWritten);
if (!r)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
// Write text to new location
Interop.mincore.SMALL_RECT writeRegion = new Interop.mincore.SMALL_RECT();
writeRegion.Left = (short)targetLeft;
writeRegion.Right = (short)(targetLeft + sourceWidth);
writeRegion.Top = (short)targetTop;
writeRegion.Bottom = (short)(targetTop + sourceHeight);
fixed (Interop.mincore.CHAR_INFO* pCharInfo = data)
Interop.mincore.WriteConsoleOutput(OutputHandle, pCharInfo, bufferSize, bufferCoord, ref writeRegion);
}
public static void Clear()
{
Interop.mincore.COORD coordScreen = new Interop.mincore.COORD();
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi;
bool success;
int conSize;
IntPtr hConsole = OutputHandle;
if (hConsole == s_InvalidHandleValue)
throw new IOException(SR.IO_NoConsole);
// get the number of character cells in the current buffer
// Go through my helper method for fetching a screen buffer info
// to correctly handle default console colors.
csbi = GetBufferInfo();
conSize = csbi.dwSize.X * csbi.dwSize.Y;
// fill the entire screen with blanks
int numCellsWritten = 0;
success = Interop.mincore.FillConsoleOutputCharacter(hConsole, ' ',
conSize, coordScreen, out numCellsWritten);
if (!success)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
// now set the buffer's attributes accordingly
numCellsWritten = 0;
success = Interop.mincore.FillConsoleOutputAttribute(hConsole, csbi.wAttributes,
conSize, coordScreen, out numCellsWritten);
if (!success)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
// put the cursor at (0, 0)
success = Interop.mincore.SetConsoleCursorPosition(hConsole, coordScreen);
if (!success)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
public static void SetCursorPosition(int left, int top)
{
// Note on argument checking - the upper bounds are NOT correct
// here! But it looks slightly expensive to compute them. Let
// Windows calculate them, then we'll give a nice error message.
if (left < 0 || left >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (top < 0 || top >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
Contract.EndContractBlock();
IntPtr hConsole = OutputHandle;
Interop.mincore.COORD coords = new Interop.mincore.COORD();
coords.X = (short)left;
coords.Y = (short)top;
if (!Interop.mincore.SetConsoleCursorPosition(hConsole, coords))
{
// Give a nice error message for out of range sizes
int errorCode = Marshal.GetLastWin32Error();
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
if (left < 0 || left >= csbi.dwSize.X)
throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (top < 0 || top >= csbi.dwSize.Y)
throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
public static int BufferWidth
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.dwSize.X;
}
set
{
SetBufferSize(value, BufferHeight);
}
}
public static int BufferHeight
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.dwSize.Y;
}
set
{
SetBufferSize(BufferWidth, value);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void SetBufferSize(int width, int height)
{
// Ensure the new size is not smaller than the console window
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
Interop.mincore.SMALL_RECT srWindow = csbi.srWindow;
if (width < srWindow.Right + 1 || width >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(width), width, SR.ArgumentOutOfRange_ConsoleBufferLessThanWindowSize);
if (height < srWindow.Bottom + 1 || height >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(height), height, SR.ArgumentOutOfRange_ConsoleBufferLessThanWindowSize);
Interop.mincore.COORD size = new Interop.mincore.COORD();
size.X = (short)width;
size.Y = (short)height;
if (!Interop.mincore.SetConsoleScreenBufferSize(OutputHandle, size))
{
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
}
public static int LargestWindowWidth
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
// Note this varies based on current screen resolution and
// current console font. Do not cache this value.
Interop.mincore.COORD bounds = Interop.mincore.GetLargestConsoleWindowSize(OutputHandle);
return bounds.X;
}
}
public static int LargestWindowHeight
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
// Note this varies based on current screen resolution and
// current console font. Do not cache this value.
Interop.mincore.COORD bounds = Interop.mincore.GetLargestConsoleWindowSize(OutputHandle);
return bounds.Y;
}
}
public static int WindowLeft
{
get
{
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.srWindow.Left;
}
set
{
SetWindowPosition(value, WindowTop);
}
}
public static int WindowTop
{
get
{
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.srWindow.Top;
}
set
{
SetWindowPosition(WindowLeft, value);
}
}
public static int WindowWidth
{
get
{
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.srWindow.Right - csbi.srWindow.Left + 1;
}
set
{
SetWindowSize(value, WindowHeight);
}
}
public static int WindowHeight
{
get
{
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
return csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
}
set
{
SetWindowSize(WindowWidth, value);
}
}
public static unsafe void SetWindowPosition(int left, int top)
{
// Get the size of the current console window
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
Interop.mincore.SMALL_RECT srWindow = csbi.srWindow;
// Check for arithmetic underflows & overflows.
int newRight = left + srWindow.Right - srWindow.Left + 1;
if (left < 0 || newRight > csbi.dwSize.X || newRight < 0)
throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleWindowPos);
int newBottom = top + srWindow.Bottom - srWindow.Top + 1;
if (top < 0 || newBottom > csbi.dwSize.Y || newBottom < 0)
throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleWindowPos);
// Preserve the size, but move the position.
srWindow.Bottom -= (short)(srWindow.Top - top);
srWindow.Right -= (short)(srWindow.Left - left);
srWindow.Left = (short)left;
srWindow.Top = (short)top;
bool r = Interop.mincore.SetConsoleWindowInfo(OutputHandle, true, &srWindow);
if (!r)
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
public static unsafe void SetWindowSize(int width, int height)
{
if (width <= 0)
throw new ArgumentOutOfRangeException(nameof(width), width, SR.ArgumentOutOfRange_NeedPosNum);
if (height <= 0)
throw new ArgumentOutOfRangeException(nameof(height), height, SR.ArgumentOutOfRange_NeedPosNum);
// Get the position of the current console window
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
// If the buffer is smaller than this new window size, resize the
// buffer to be large enough. Include window position.
bool resizeBuffer = false;
Interop.mincore.COORD size = new Interop.mincore.COORD();
size.X = csbi.dwSize.X;
size.Y = csbi.dwSize.Y;
if (csbi.dwSize.X < csbi.srWindow.Left + width)
{
if (csbi.srWindow.Left >= short.MaxValue - width)
throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_ConsoleWindowBufferSize);
size.X = (short)(csbi.srWindow.Left + width);
resizeBuffer = true;
}
if (csbi.dwSize.Y < csbi.srWindow.Top + height)
{
if (csbi.srWindow.Top >= short.MaxValue - height)
throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_ConsoleWindowBufferSize);
size.Y = (short)(csbi.srWindow.Top + height);
resizeBuffer = true;
}
if (resizeBuffer)
{
if (!Interop.mincore.SetConsoleScreenBufferSize(OutputHandle, size))
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
}
Interop.mincore.SMALL_RECT srWindow = csbi.srWindow;
// Preserve the position, but change the size.
srWindow.Bottom = (short)(srWindow.Top + height - 1);
srWindow.Right = (short)(srWindow.Left + width - 1);
if (!Interop.mincore.SetConsoleWindowInfo(OutputHandle, true, &srWindow))
{
int errorCode = Marshal.GetLastWin32Error();
// If we resized the buffer, un-resize it.
if (resizeBuffer)
{
Interop.mincore.SetConsoleScreenBufferSize(OutputHandle, csbi.dwSize);
}
// Try to give a better error message here
Interop.mincore.COORD bounds = Interop.mincore.GetLargestConsoleWindowSize(OutputHandle);
if (width > bounds.X)
throw new ArgumentOutOfRangeException(nameof(width), width, SR.Format(SR.ArgumentOutOfRange_ConsoleWindowSize_Size, bounds.X));
if (height > bounds.Y)
throw new ArgumentOutOfRangeException(nameof(height), height, SR.Format(SR.ArgumentOutOfRange_ConsoleWindowSize_Size, bounds.Y));
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
private static Interop.mincore.Color ConsoleColorToColorAttribute(ConsoleColor color, bool isBackground)
{
if ((((int)color) & ~0xf) != 0)
throw new ArgumentException(SR.Arg_InvalidConsoleColor);
Contract.EndContractBlock();
Interop.mincore.Color c = (Interop.mincore.Color)color;
// Make these background colors instead of foreground
if (isBackground)
c = (Interop.mincore.Color)((int)c << 4);
return c;
}
private static ConsoleColor ColorAttributeToConsoleColor(Interop.mincore.Color c)
{
// Turn background colors into foreground colors.
if ((c & Interop.mincore.Color.BackgroundMask) != 0)
{
c = (Interop.mincore.Color)(((int)c) >> 4);
}
return (ConsoleColor)c;
}
private static Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo()
{
bool unused;
return GetBufferInfo(true, out unused);
}
// For apps that don't have a console (like Windows apps), they might
// run other code that includes color console output. Allow a mechanism
// where that code won't throw an exception for simple errors.
private static Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo(bool throwOnNoConsole, out bool succeeded)
{
succeeded = false;
IntPtr outputHandle = OutputHandle;
if (outputHandle == s_InvalidHandleValue)
{
if (throwOnNoConsole)
{
throw new IOException(SR.IO_NoConsole);
}
return new Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO();
}
// Note that if stdout is redirected to a file, the console handle may be a file.
// First try stdout; if this fails, try stderr and then stdin.
Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!Interop.mincore.GetConsoleScreenBufferInfo(outputHandle, out csbi) &&
!Interop.mincore.GetConsoleScreenBufferInfo(ErrorHandle, out csbi) &&
!Interop.mincore.GetConsoleScreenBufferInfo(InputHandle, out csbi))
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.mincore.Errors.ERROR_INVALID_HANDLE && !throwOnNoConsole)
return new Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO();
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
if (!_haveReadDefaultColors)
{
// Fetch the default foreground and background color for the ResetColor method.
Debug.Assert((int)Interop.mincore.Color.ColorMask == 0xff, "Make sure one byte is large enough to store a Console color value!");
_defaultColors = (byte)(csbi.wAttributes & (short)Interop.mincore.Color.ColorMask);
_haveReadDefaultColors = true; // also used by ResetColor to know when GetBufferInfo has been called successfully
}
succeeded = true;
return csbi;
}
private sealed class WindowsConsoleStream : ConsoleStream
{
// We know that if we are using console APIs rather than file APIs, then the encoding
// is Encoding.Unicode implying 2 bytes per character:
const int BytesPerWChar = 2;
private readonly bool _isPipe; // When reading from pipes, we need to properly handle EOF cases.
private IntPtr _handle;
private readonly bool _useFileAPIs;
internal WindowsConsoleStream(IntPtr handle, FileAccess access, bool useFileAPIs)
: base(access)
{
Debug.Assert(handle != IntPtr.Zero && handle != s_InvalidHandleValue, "ConsoleStream expects a valid handle!");
_handle = handle;
_isPipe = Interop.mincore.GetFileType(handle) == Interop.mincore.FileTypes.FILE_TYPE_PIPE;
_useFileAPIs = useFileAPIs;
}
protected override void Dispose(bool disposing)
{
// We're probably better off not closing the OS handle here. First,
// we allow a program to get multiple instances of ConsoleStreams
// around the same OS handle, so closing one handle would invalidate
// them all. Additionally, we want a second AppDomain to be able to
// write to stdout if a second AppDomain quits.
_handle = IntPtr.Zero;
base.Dispose(disposing);
}
public override int Read(byte[] buffer, int offset, int count)
{
ValidateRead(buffer, offset, count);
int bytesRead;
int errCode = ReadFileNative(_handle, buffer, offset, count, _isPipe, out bytesRead, _useFileAPIs);
if (Interop.mincore.Errors.ERROR_SUCCESS != errCode)
throw Win32Marshal.GetExceptionForWin32Error(errCode);
return bytesRead;
}
public override void Write(byte[] buffer, int offset, int count)
{
ValidateWrite(buffer, offset, count);
int errCode = WriteFileNative(_handle, buffer, offset, count, _useFileAPIs);
if (Interop.mincore.Errors.ERROR_SUCCESS != errCode)
throw Win32Marshal.GetExceptionForWin32Error(errCode);
}
public override void Flush()
{
if (_handle == IntPtr.Zero) throw Error.GetFileNotOpen();
base.Flush();
}
// P/Invoke wrappers for writing to and from a file, nearly identical
// to the ones on FileStream. These are duplicated to save startup/hello
// world working set and to avoid requiring a reference to the
// System.IO.FileSystem contract.
private unsafe static int ReadFileNative(IntPtr hFile, byte[] bytes, int offset, int count, bool isPipe, out int bytesRead, bool useFileAPIs)
{
Debug.Assert(offset >= 0, "offset >= 0");
Debug.Assert(count >= 0, "count >= 0");
Debug.Assert(bytes != null, "bytes != null");
// Don't corrupt memory when multiple threads are erroneously writing
// to this stream simultaneously.
if (bytes.Length - offset < count)
throw new IndexOutOfRangeException(SR.IndexOutOfRange_IORaceCondition);
Contract.EndContractBlock();
// You can't use the fixed statement on an array of length 0.
if (bytes.Length == 0)
{
bytesRead = 0;
return Interop.mincore.Errors.ERROR_SUCCESS;
}
bool readSuccess;
fixed (byte* p = bytes)
{
if (useFileAPIs)
{
readSuccess = (0 != Interop.mincore.ReadFile(hFile, p + offset, count, out bytesRead, IntPtr.Zero));
}
else
{
// If the code page could be Unicode, we should use ReadConsole instead, e.g.
int charsRead;
readSuccess = Interop.mincore.ReadConsole(hFile, p + offset, count / BytesPerWChar, out charsRead, IntPtr.Zero);
bytesRead = charsRead * BytesPerWChar;
}
}
if (readSuccess)
return Interop.mincore.Errors.ERROR_SUCCESS;
// For pipes that are closing or broken, just stop.
// (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing;
// ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is mot an error, but EOF.)
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.mincore.Errors.ERROR_NO_DATA || errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE)
return Interop.mincore.Errors.ERROR_SUCCESS;
return errorCode;
}
private static unsafe int WriteFileNative(IntPtr hFile, byte[] bytes, int offset, int count, bool useFileAPIs)
{
Debug.Assert(offset >= 0, "offset >= 0");
Debug.Assert(count >= 0, "count >= 0");
Debug.Assert(bytes != null, "bytes != null");
Debug.Assert(bytes.Length >= offset + count, "bytes.Length >= offset + count");
// You can't use the fixed statement on an array of length 0.
if (bytes.Length == 0)
return Interop.mincore.Errors.ERROR_SUCCESS;
bool writeSuccess;
fixed (byte* p = bytes)
{
if (useFileAPIs)
{
int numBytesWritten;
writeSuccess = (0 != Interop.mincore.WriteFile(hFile, p + offset, count, out numBytesWritten, IntPtr.Zero));
Debug.Assert(!writeSuccess || count == numBytesWritten);
}
else
{
// If the code page could be Unicode, we should use ReadConsole instead, e.g.
// Note that WriteConsoleW has a max limit on num of chars to write (64K)
// [http://msdn.microsoft.com/en-us/library/ms687401.aspx]
// However, we do not need to worry about that because the StreamWriter in Console has
// a much shorter buffer size anyway.
int charsWritten;
writeSuccess = Interop.mincore.WriteConsole(hFile, p + offset, count / BytesPerWChar, out charsWritten, IntPtr.Zero);
Debug.Assert(!writeSuccess || count / BytesPerWChar == charsWritten);
}
}
if (writeSuccess)
return Interop.mincore.Errors.ERROR_SUCCESS;
// For pipes that are closing or broken, just stop.
// (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing;
// ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is mot an error, but EOF.)
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.mincore.Errors.ERROR_NO_DATA || errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE)
return Interop.mincore.Errors.ERROR_SUCCESS;
return errorCode;
}
}
internal sealed class ControlCHandlerRegistrar
{
private bool _handlerRegistered;
private Interop.mincore.ConsoleCtrlHandlerRoutine _handler;
internal ControlCHandlerRegistrar()
{
_handler = new Interop.mincore.ConsoleCtrlHandlerRoutine(BreakEvent);
}
internal void Register()
{
Debug.Assert(!_handlerRegistered);
bool r = Interop.mincore.SetConsoleCtrlHandler(_handler, true);
if (!r)
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
_handlerRegistered = true;
}
internal void Unregister()
{
Debug.Assert(_handlerRegistered);
bool r = Interop.mincore.SetConsoleCtrlHandler(_handler, false);
if (!r)
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
_handlerRegistered = false;
}
private static bool BreakEvent(int controlType)
{
if (controlType != Interop.mincore.CTRL_C_EVENT &&
controlType != Interop.mincore.CTRL_BREAK_EVENT)
{
return false;
}
return Console.HandleBreakEvent(controlType == Interop.mincore.CTRL_C_EVENT ? ConsoleSpecialKey.ControlC : ConsoleSpecialKey.ControlBreak);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Net;
using System.Threading;
using NUnit.Framework;
using NServiceKit.Text;
namespace RazorRockstars.Console
{
[TestFixture]
public class RazorRockstars_EmbeddedFilesTests
{
AppHost appHost;
Stopwatch startedAt;
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
startedAt = Stopwatch.StartNew();
appHost = new AppHost();
appHost.Init();
appHost.Start("http://*:1337/");
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
"Time Taken {0}ms".Fmt(startedAt.ElapsedMilliseconds).Print();
appHost.Dispose();
}
[Ignore("Debug Run")][Test]
public void RunFor10Mins()
{
Thread.Sleep(TimeSpan.FromMinutes(10));
}
public static string AcceptContentType = "*/*";
public void Assert200(string url, params string[] containsItems)
{
url.Print();
var text = url.GetStringFromUrl(AcceptContentType, r => {
if (r.StatusCode != HttpStatusCode.OK)
Assert.Fail(url + " did not return 200 OK");
});
foreach (var item in containsItems)
{
if (!text.Contains(item))
{
Assert.Fail(item + " was not found in " + url);
}
}
}
public void Assert200UrlContentType(string url, string contentType)
{
url.Print();
url.GetStringFromUrl(AcceptContentType, r => {
if (r.StatusCode != HttpStatusCode.OK)
Assert.Fail(url + " did not return 200 OK: " + r.StatusCode);
if (!r.ContentType.StartsWith(contentType))
Assert.Fail(url + " did not return contentType " + contentType);
});
}
public static string Host = "http://localhost:1337";
static string ViewRockstars = "<!--view:Rockstars.cshtml-->";
static string ViewRockstars2 = "<!--view:Rockstars2.cshtml-->";
static string ViewRockstars3 = "<!--view:Rockstars3.cshtml-->";
static string ViewRockstarsMark = "<!--view:RockstarsMark.md-->";
static string ViewNoModelNoController = "<!--view:NoModelNoController.cshtml-->";
static string ViewTypedModelNoController = "<!--view:TypedModelNoController.cshtml-->";
static string ViewPage1 = "<!--view:Page1.cshtml-->";
static string ViewPage2 = "<!--view:Page2.cshtml-->";
static string ViewPage3 = "<!--view:Page3.cshtml-->";
static string ViewPage4 = "<!--view:Page4.cshtml-->";
static string ViewMarkdownRootPage = "<!--view:MRootPage.md-->";
static string ViewMPage1 = "<!--view:MPage1.md-->";
static string ViewMPage2 = "<!--view:MPage2.md-->";
static string ViewMPage3 = "<!--view:MPage3.md-->";
static string ViewMPage4 = "<!--view:MPage4.md-->";
static string ViewRazorPartial = "<!--view:RazorPartial.cshtml-->";
static string ViewMarkdownPartial = "<!--view:MarkdownPartial.md-->";
static string ViewRazorPartialModel = "<!--view:RazorPartialModel.cshtml-->";
static string View_Default = "<!--view:default.cshtml-->";
static string View_Pages_Default = "<!--view:Pages/default.cshtml-->";
static string View_Pages_Dir_Default = "<!--view:Pages/Dir/default.cshtml-->";
static string ViewM_Pages_Dir2_Default = "<!--view:Pages/Dir2/default.md-->";
static string Template_Layout = "<!--template:_Layout.cshtml-->";
static string Template_Pages_Layout = "<!--template:Pages/_Layout.cshtml-->";
static string Template_Pages_Dir_Layout = "<!--template:Pages/Dir/_Layout.cshtml-->";
static string Template_SimpleLayout = "<!--template:SimpleLayout.cshtml-->";
static string Template_SimpleLayout2 = "<!--template:SimpleLayout2.cshtml-->";
static string Template_HtmlReport = "<!--template:HtmlReport.cshtml-->";
static string TemplateM_Layout = "<!--template:_Layout.shtml-->";
static string TemplateM_Pages_Layout = "<!--template:Pages/_Layout.shtml-->";
static string TemplateM_Pages_Dir_Layout = "<!--template:Pages/Dir/_Layout.shtml-->";
static string TemplateM_HtmlReport = "<!--template:HtmlReport.shtml-->";
[Test]
public void Can_get_page_with_default_view_and_template()
{
Assert200(Host + "/rockstars", ViewRockstars, Template_HtmlReport);
}
[Test]
public void Can_get_page_with_alt_view_and_default_template()
{
Assert200(Host + "/rockstars?View=Rockstars2", ViewRockstars2, Template_Layout);
}
[Test]
public void Can_get_page_with_alt_viewengine_view_and_default_template()
{
Assert200(Host + "/rockstars?View=RockstarsMark", ViewRockstarsMark, TemplateM_HtmlReport);
}
[Test]
public void Can_get_page_with_default_view_and_alt_template()
{
Assert200(Host + "/rockstars?Template=SimpleLayout", ViewRockstars, Template_SimpleLayout);
}
[Test]
public void Can_get_page_with_alt_viewengine_view_and_alt_razor_template()
{
Assert200(Host + "/rockstars?View=Rockstars2&Template=SimpleLayout2", ViewRockstars2, Template_SimpleLayout2);
}
[Test]
public void Can_get_razor_content_pages()
{
Assert200(Host + "/TypedModelNoController",
ViewTypedModelNoController, Template_SimpleLayout, ViewRazorPartial, ViewMarkdownPartial, ViewRazorPartialModel);
Assert200(Host + "/nomodelnocontroller",
ViewNoModelNoController, Template_SimpleLayout, ViewRazorPartial, ViewMarkdownPartial);
Assert200(Host + "/pages/page1",
ViewPage1, Template_Pages_Layout, ViewRazorPartialModel, ViewMarkdownPartial);
Assert200(Host + "/pages/dir/Page2",
ViewPage2, Template_Pages_Dir_Layout, ViewRazorPartial, ViewMarkdownPartial);
Assert200(Host + "/pages/dir2/Page3",
ViewPage3, Template_Pages_Layout, ViewRazorPartial, ViewMarkdownPartial);
Assert200(Host + "/pages/dir2/Page4",
ViewPage4, Template_HtmlReport, ViewRazorPartial, ViewMarkdownPartial);
}
[Test]
public void Can_get_razor_content_pages_with_partials()
{
Assert200(Host + "/pages/dir2/Page4",
ViewPage4, Template_HtmlReport, ViewRazorPartial, ViewMarkdownPartial, ViewMPage3);
}
[Test]
public void Can_get_markdown_content_pages()
{
Assert200(Host + "/MRootPage",
ViewMarkdownRootPage, TemplateM_Layout);
Assert200(Host + "/pages/mpage1",
ViewMPage1, TemplateM_Pages_Layout);
Assert200(Host + "/pages/dir/mPage2",
ViewMPage2, TemplateM_Pages_Dir_Layout);
}
[Test]
public void Redirects_when_trying_to_get_razor_page_with_extension()
{
Assert200(Host + "/pages/dir2/Page4.cshtml",
ViewPage4, Template_HtmlReport, ViewRazorPartial, ViewMarkdownPartial, ViewMPage3);
}
[Test]
public void Redirects_when_trying_to_get_markdown_page_with_extension()
{
Assert200(Host + "/pages/mpage1.md",
ViewMPage1, TemplateM_Pages_Layout);
}
[Test]
public void Can_get_default_razor_pages()
{
Assert200(Host + "/",
View_Default, Template_SimpleLayout, ViewRazorPartial, ViewMarkdownPartial, ViewRazorPartialModel);
Assert200(Host + "/Pages/",
View_Pages_Default, Template_Pages_Layout, ViewRazorPartial, ViewMarkdownPartial, ViewRazorPartialModel);
Assert200(Host + "/Pages/Dir/",
View_Pages_Dir_Default, Template_SimpleLayout, ViewRazorPartial, ViewMarkdownPartial, ViewRazorPartialModel);
}
[Test]
public void Can_get_default_markdown_pages()
{
Assert200(Host + "/Pages/Dir2/",
ViewM_Pages_Dir2_Default, TemplateM_Pages_Layout);
}
[Test] //Good for testing adhoc compilation
public void Can_get_last_view_template_compiled()
{
Assert200(Host + "/rockstars?View=Rockstars3", ViewRockstars3, Template_SimpleLayout2);
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Threading;
using NLog.Common;
using NLog.Conditions;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class FilteringTargetWrapperTests : NLogTestBase
{
[Fact]
public void FilteringTargetWrapperSyncTest1()
{
var myMockCondition = new MyMockCondition(true);
var myTarget = new MyTarget();
var wrapper = new FilteringTargetWrapper
{
WrappedTarget = myTarget,
Condition = myMockCondition,
};
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
bool continuationHit = false;
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit = true;
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.Equal(1, myMockCondition.CallCount);
Assert.True(continuationHit);
Assert.Null(lastException);
Assert.Equal(1, myTarget.WriteCount);
continuationHit = false;
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit);
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
Assert.Equal(2, myMockCondition.CallCount);
}
[Fact]
public void FilteringTargetWrapperAsyncTest1()
{
var myMockCondition = new MyMockCondition(true);
var myTarget = new MyAsyncTarget();
var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition);
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(1, myTarget.WriteCount);
Assert.Equal(1, myMockCondition.CallCount);
continuationHit.Reset();
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
Assert.Equal(2, myMockCondition.CallCount);
}
[Fact]
public void FilteringTargetWrapperAsyncWithExceptionTest1()
{
var myMockCondition = new MyMockCondition(true);
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true,
};
var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition);
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotNull(lastException);
Assert.IsType<InvalidOperationException>(lastException);
Assert.Equal(1, myTarget.WriteCount);
Assert.Equal(1, myMockCondition.CallCount);
continuationHit.Reset();
lastException = null;
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotNull(lastException);
Assert.IsType<InvalidOperationException>(lastException);
Assert.Equal(2, myTarget.WriteCount);
Assert.Equal(2, myMockCondition.CallCount);
}
[Fact]
public void FilteringTargetWrapperSyncTest2()
{
var myMockCondition = new MyMockCondition(false);
var myTarget = new MyTarget();
var wrapper = new FilteringTargetWrapper
{
WrappedTarget = myTarget,
Condition = myMockCondition,
};
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
bool continuationHit = false;
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit = true;
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.Equal(1, myMockCondition.CallCount);
Assert.True(continuationHit);
Assert.Null(lastException);
Assert.Equal(0, myTarget.WriteCount);
Assert.Equal(1, myMockCondition.CallCount);
continuationHit = false;
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit);
Assert.Null(lastException);
Assert.Equal(0, myTarget.WriteCount);
Assert.Equal(2, myMockCondition.CallCount);
}
[Fact]
public void FilteringTargetWrapperAsyncTest2()
{
var myMockCondition = new MyMockCondition(false);
var myTarget = new MyAsyncTarget();
var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition);
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(0, myTarget.WriteCount);
Assert.Equal(1, myMockCondition.CallCount);
continuationHit.Reset();
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(0, myTarget.WriteCount);
Assert.Equal(2, myMockCondition.CallCount);
}
[Fact]
public void FilteringTargetWrapperAsyncWithExceptionTest2()
{
var myMockCondition = new MyMockCondition(false);
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true,
};
var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition);
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(0, myTarget.WriteCount);
Assert.Equal(1, myMockCondition.CallCount);
continuationHit.Reset();
lastException = null;
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(0, myTarget.WriteCount);
Assert.Equal(2, myMockCondition.CallCount);
}
class MyAsyncTarget : Target
{
public int WriteCount { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
throw new NotSupportedException();
}
protected override void Write(AsyncLogEventInfo logEvent)
{
this.WriteCount++;
ThreadPool.QueueUserWorkItem(
s =>
{
if (this.ThrowExceptions)
{
logEvent.Continuation(new InvalidOperationException("Some problem!"));
logEvent.Continuation(new InvalidOperationException("Some problem!"));
}
else
{
logEvent.Continuation(null);
logEvent.Continuation(null);
}
});
}
public bool ThrowExceptions { get; set; }
}
class MyTarget : Target
{
public int WriteCount { get; set; }
protected override void Write(LogEventInfo logEvent)
{
this.WriteCount++;
}
}
class MyMockCondition : ConditionExpression
{
private bool result;
public int CallCount { get; set; }
public MyMockCondition(bool result)
{
this.result = result;
}
protected override object EvaluateNode(LogEventInfo context)
{
this.CallCount++;
return this.result;
}
public override string ToString()
{
return "fake";
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation;
using Hyak.Common;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models;
using Newtonsoft.Json;
namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
/// <summary>
/// Retrieves Azure Site Recovery Recovery Plans.
/// </summary>
[Cmdlet(
VerbsCommon.Get,
"AzureRmRecoveryServicesAsrRecoveryPlan",
DefaultParameterSetName = ASRParameterSets.Default)]
[Alias(
"Get-ASRRP",
"Get-ASRRecoveryPlan")]
[OutputType(typeof(IEnumerable<ASRRecoveryPlan>))]
public class GetAzureRmRecoveryServicesAsrRecoveryPlan : SiteRecoveryCmdletBase
{
/// <summary>
/// Gets or sets name of the Recovery Plan.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.ByName,
Mandatory = true)]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
/// <summary>
/// Gets or sets friendly name of the Recovery Plan.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.ByFriendlyName,
Mandatory = true)]
[ValidateNotNullOrEmpty]
public string FriendlyName { get; set; }
/// <summary>
/// Gets or sets RP JSON FilePath.
/// </summary>
[Parameter(
ParameterSetName = ASRParameterSets.ByName,
Position = 1,
Mandatory = false)]
[Parameter(
ParameterSetName = ASRParameterSets.ByFriendlyName,
Position = 1,
Mandatory = false)]
public string Path { get; set; }
/// <summary>
/// ProcessRecord of the command.
/// </summary>
public override void ExecuteSiteRecoveryCmdlet()
{
base.ExecuteSiteRecoveryCmdlet();
switch (this.ParameterSetName)
{
case ASRParameterSets.ByFriendlyName:
this.GetByFriendlyName();
break;
case ASRParameterSets.ByName:
this.GetByName();
break;
case ASRParameterSets.Default:
this.GetAll();
break;
}
}
/// <summary>
/// Queries all / by default.
/// </summary>
private void GetAll()
{
var recoveryPlanListResponse = this.RecoveryServicesClient
.GetAzureSiteRecoveryRecoveryPlan();
this.WriteRecoveryPlans(recoveryPlanListResponse);
}
/// <summary>
/// Queries by Friendly name.
/// </summary>
private void GetByFriendlyName()
{
var recoveryPlanListResponse = this.RecoveryServicesClient
.GetAzureSiteRecoveryRecoveryPlan();
var found = false;
foreach (var recoveryPlan in recoveryPlanListResponse)
{
if (0 ==
string.Compare(
this.FriendlyName,
recoveryPlan.Properties.FriendlyName,
StringComparison.OrdinalIgnoreCase))
{
var rp = this.RecoveryServicesClient.GetAzureSiteRecoveryRecoveryPlan(
recoveryPlan.Name);
this.WriteRecoveryPlan(rp);
if (!string.IsNullOrEmpty(this.Path))
{
this.GetRecoveryPlanFile(rp);
}
found = true;
}
}
if (!found)
{
throw new InvalidOperationException(
string.Format(
Resources.RecoveryPlanNotFound,
this.FriendlyName,
PSRecoveryServicesClient.asrVaultCreds.ResourceName));
}
}
/// <summary>
/// Queries by Name.
/// </summary>
private void GetByName()
{
try
{
var recoveryPlanResponse = this.RecoveryServicesClient
.GetAzureSiteRecoveryRecoveryPlan(this.Name);
if (recoveryPlanResponse != null)
{
this.WriteRecoveryPlan(recoveryPlanResponse);
if (!string.IsNullOrEmpty(this.Path))
{
this.GetRecoveryPlanFile(recoveryPlanResponse);
}
}
}
catch (CloudException ex)
{
if (string.Compare(
ex.Error.Code,
"NotFound",
StringComparison.OrdinalIgnoreCase) ==
0)
{
throw new InvalidOperationException(
string.Format(
Resources.RecoveryPlanNotFound,
this.Name,
PSRecoveryServicesClient.asrVaultCreds.ResourceName));
}
throw;
}
}
private void GetRecoveryPlanFile(
RecoveryPlan recoveryPlan)
{
recoveryPlan =
this.RecoveryServicesClient.GetAzureSiteRecoveryRecoveryPlan(recoveryPlan.Name);
if (string.IsNullOrEmpty(this.Path) ||
!Directory.Exists(System.IO.Path.GetDirectoryName(this.Path)))
{
throw new DirectoryNotFoundException(
string.Format(
Resources.DirectoryNotFound,
System.IO.Path.GetDirectoryName(this.Path)));
}
var fullFileName = this.Path;
using (var file = new StreamWriter(
fullFileName,
false))
{
var json = JsonConvert.SerializeObject(
recoveryPlan,
Formatting.Indented);
file.WriteLine(json);
}
}
/// <summary>
/// Write Recovery Plan.
/// </summary>
/// <param name="recoveryPlan">Recovery Plan object</param>
private void WriteRecoveryPlan(
RecoveryPlan recoveryPlan)
{
var replicationProtectedItemListResponse = this.RecoveryServicesClient
.GetAzureSiteRecoveryReplicationProtectedItemInRP(recoveryPlan.Name);
this.WriteObject(
new ASRRecoveryPlan(
recoveryPlan,
replicationProtectedItemListResponse));
}
/// <summary>
/// Write Recovery Plans.
/// </summary>
/// <param name="recoveryPlanList">List of Recovery Plans</param>
private void WriteRecoveryPlans(
IList<RecoveryPlan> recoveryPlanList)
{
IList<ASRRecoveryPlan> asrRecoveryPlans = new List<ASRRecoveryPlan>();
foreach (var recoveryPlan in recoveryPlanList)
{
var replicationProtectedItemListResponse =
this.RecoveryServicesClient.GetAzureSiteRecoveryReplicationProtectedItemInRP(
recoveryPlan.Name);
asrRecoveryPlans.Add(
new ASRRecoveryPlan(
recoveryPlan,
replicationProtectedItemListResponse));
}
this.WriteObject(
asrRecoveryPlans,
true);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// ToInt16(System.Double)
/// </summary>
public class ConvertToInt16_5
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ToInt16(0<double<0.5)");
try
{
double d;
do
d = TestLibrary.Generator.GetDouble(-55);
while (d >= 0.5);
Int16 actual = Convert.ToInt16(d);
Int16 expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt16(1>double>=0.5)");
try
{
double d;
do
d = TestLibrary.Generator.GetDouble(-55);
while (d < 0.5);
Int16 actual = Convert.ToInt16(d);
Int16 expected = 1;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt16(0)");
try
{
double d = 0d;
Int16 actual = Convert.ToInt16(d);
Int16 expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt16(int16.max)");
try
{
double d = Int16.MaxValue;
Int16 actual = Convert.ToInt16(d);
Int16 expected = Int16.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt16(int16.min)");
try
{
double d = Int16.MinValue;
Int16 actual = Convert.ToInt16(d);
Int16 expected = Int16.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("005.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException is not thrown.");
try
{
double d = Int16.MaxValue + 1;
Int16 i = Convert.ToInt16(d);
TestLibrary.TestFramework.LogError("101.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: OverflowException is not thrown.");
try
{
double d = Int16.MinValue - 1;
Int16 i = Convert.ToInt16(d);
TestLibrary.TestFramework.LogError("102.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
public static int Main()
{
ConvertToInt16_5 test = new ConvertToInt16_5();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt16_5");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
//-----------------------------------------------------------------------------
// Verve
// Copyright (C) - Violent Tulip
//-----------------------------------------------------------------------------
function InitializeVerveEditor()
{
// Preferences.
exec( "./DefaultPrefs.cs" );
// GUI.
exec( "./GUI/GuiProfiles.cs" );
exec( "./GUI/VerveEditorGroupBuilder.gui" );
exec( "./GUI/VerveEditorImportPathNodes.gui" );
// Scripts.
exec( "./Scripts/Plugin.cs" );
exec( "./Scripts/Utility.cs" );
exec( "./Scripts/EditorControls.cs" );
exec( "./Scripts/EditorHistory.cs" );
exec( "./Scripts/EditorMenu.cs" );
exec( "./Scripts/EditorPreferences.cs" );
exec( "./Scripts/EditorWindow.cs" );
exec( "./Scripts/Persistence.cs" );
exec( "./Scripts/ScrollNotify.cs" );
exec( "./Scripts/VObject.cs" );
exec( "./Scripts/Inspector/main.cs" );
exec( "./Scripts/Controller/main.cs" );
exec( "./Scripts/Groups/main.cs" );
exec( "./Scripts/Tracks/main.cs" );
exec( "./Scripts/Events/main.cs" );
exec( "./Torque/main.cs" );
// Register Events.
VerveEditor::RegisterEvent( "VGroupObjectUpdate" );
}
function DestroyVerveEditor()
{
// Ensure the Editor has Shutdown.
if ( isObject( VerveEditorWindow ) )
{
// Prompt for Save.
VerveEditor::SavePrompt();
// Reset.
VerveEditor::Reset();
// Delete the Window.
VerveEditorWindow.delete();
}
}
function ToggleVerveEditor( %value )
{
if ( %value )
{
if ( !isObject( VerveEditorWindow ) )
{
VerveEditor::LaunchEditor();
}
else
{
VerveEditorWindow.onWindowClose();
}
}
}
function VerveEditor::LaunchEditor()
{
// Launch Window.
%mainScreen = VerveEditorWindow::Open();
if ( !isObject( VerveEditorGui ) )
{
// Load the GUI.
exec ( "./GUI/VerveEditor.gui" );
}
// Apply GUI.
%mainScreen.setContent( VerveEditorGUI );
// Clear History.
VerveEditor::ClearHistory();
// Update Window Title.
VerveEditorWindow.UpdateWindowTitle();
// Update Selection.
VerveEditor::OnSelectionUpdate();
// Update Sizes.
VerveEditor::UpdateSizes();
}
function VerveEditor::ResetController()
{
// Delete.
VerveEditor::DeleteController();
// Create.
return VerveEditor::CreateController();
}
function VerveEditor::DeleteController()
{
// Current Controller?
if ( isObject( $VerveEditor::Controller ) )
{
// Stop but do not Reset.
$VerveEditor::Controller.stop( false );
// Delete the Controller.
$VerveEditor::Controller.delete();
// Deleted?
return !isObject( $VerveEditor::Controller );
}
// No Deletion.
return false;
}
function VerveEditor::CreateController()
{
// Current Controller?
if ( !isObject( VerveEditorController ) )
{
// Create Controller.
$VerveEditor::Controller = new VController( VerveEditorController );
}
// Return ID.
return $VerveEditor::Controller;
}
function VerveEditor::Refresh()
{
if ( !isObject( $VerveEditor::Controller ) )
{
return;
}
// Clear Selection.
VerveEditor::ClearSelection();
// Delete Existing Controls.
VerveEditor::DeleteControls();
// Sort Groups & Tracks.
$VerveEditor::Controller.sortGroups();
$VerveEditor::Controller.sortTracks();
%groupSet = $VerveEditor::Controller;
%groupCount = %groupSet.getCount();
for ( %i = 0; %i < %groupCount; %i++ )
{
// Update Controls.
%groupSet.getObject( %i ).Refresh();
}
// Update Window Title.
VerveEditorWindow.UpdateWindowTitle();
// Update Duration.
VerveEditor::UpdateDuration();
// Update Sizes.
VerveEditor::UpdateSizes();
// Update Selection.
VerveEditor::OnSelectionUpdate();
}
function VerveEditor::UpdateSizes()
{
VerveEditorGroupNotify.UpdateSize();
VerveEditorTrackNotify.UpdateSize();
VerveEditorTimeNotify.UpdateSize();
}
function VerveEditor::UpdateDuration( %duration )
{
if ( %duration !$= "" )
{
// Update Duration.
$VerveEditor::Controller.setFieldValue( "Duration", %duration );
}
// Update Duration.
VerveEditorTimeLine.updateDuration();
VerveEditorTrackTimeLine.updateDuration();
// Update Sizes.
VerveEditorGroupNotify.UpdateSize();
VerveEditorTrackNotify.UpdateSize();
VerveEditorTimeNotify.UpdateSize();
}
package VerveEditorSaveIntercept
{
function EditorSaveMission()
{
// Reset.
VerveEditor::Reset();
// Perform the Save.
Parent::EditorSaveMission();
}
};
function VerveEditor::Reset()
{
// Valid Controller?
if ( isObject( $VerveEditor::Controller ) )
{
// Reset.
$VerveEditor::Controller.Reset();
// Stop.
$VerveEditor::Controller.Stop();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Xml;
namespace System.ServiceModel.Syndication
{
public delegate bool TryParseDateTimeCallback(XmlDateTimeData data, out DateTimeOffset dateTimeOffset);
public delegate bool TryParseUriCallback(XmlUriData data, out Uri uri);
[DataContract]
public abstract class SyndicationFeedFormatter
{
private SyndicationFeed _feed;
protected SyndicationFeedFormatter()
{
_feed = null;
DateTimeParser = GetDefaultDateTimeParser();
}
protected SyndicationFeedFormatter(SyndicationFeed feedToWrite)
{
_feed = feedToWrite ?? throw new ArgumentNullException(nameof(feedToWrite));
DateTimeParser = GetDefaultDateTimeParser();
}
public SyndicationFeed Feed => _feed;
public TryParseUriCallback UriParser { get; set; } = DefaultUriParser;
// Different DateTimeParsers are needed for Atom and Rss so can't set inline
public TryParseDateTimeCallback DateTimeParser { get; set; }
internal virtual TryParseDateTimeCallback GetDefaultDateTimeParser() => NotImplementedDateTimeParser;
private bool NotImplementedDateTimeParser(XmlDateTimeData XmlDateTimeData, out DateTimeOffset dateTimeOffset)
{
dateTimeOffset = default;
return false;
}
public abstract string Version { get; }
public abstract bool CanRead(XmlReader reader);
public abstract void ReadFrom(XmlReader reader);
public override string ToString() => $"{GetType()}, SyndicationVersion={Version}";
public abstract void WriteTo(XmlWriter writer);
internal static protected SyndicationCategory CreateCategory(SyndicationFeed feed)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
return GetNonNullValue(feed.CreateCategory(), SR.FeedCreatedNullCategory);
}
internal static protected SyndicationCategory CreateCategory(SyndicationItem item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
return GetNonNullValue(item.CreateCategory(), SR.ItemCreatedNullCategory);
}
internal static protected SyndicationItem CreateItem(SyndicationFeed feed)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
return GetNonNullValue(feed.CreateItem(), SR.FeedCreatedNullItem);
}
internal static protected SyndicationLink CreateLink(SyndicationFeed feed)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
return GetNonNullValue(feed.CreateLink(), SR.FeedCreatedNullPerson);
}
internal static protected SyndicationLink CreateLink(SyndicationItem item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
return GetNonNullValue(item.CreateLink(), SR.ItemCreatedNullPerson);
}
internal static protected SyndicationPerson CreatePerson(SyndicationFeed feed)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
return GetNonNullValue(feed.CreatePerson(), SR.FeedCreatedNullPerson);
}
internal static protected SyndicationPerson CreatePerson(SyndicationItem item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
return GetNonNullValue(item.CreatePerson(), SR.ItemCreatedNullPerson);
}
internal static protected void LoadElementExtensions(XmlReader reader, SyndicationFeed feed, int maxExtensionSize)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
feed.LoadElementExtensions(reader, maxExtensionSize);
}
internal static protected void LoadElementExtensions(XmlReader reader, SyndicationItem item, int maxExtensionSize)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
item.LoadElementExtensions(reader, maxExtensionSize);
}
internal static protected void LoadElementExtensions(XmlReader reader, SyndicationCategory category, int maxExtensionSize)
{
if (category == null)
{
throw new ArgumentNullException(nameof(category));
}
category.LoadElementExtensions(reader, maxExtensionSize);
}
internal static protected void LoadElementExtensions(XmlReader reader, SyndicationLink link, int maxExtensionSize)
{
if (link == null)
{
throw new ArgumentNullException(nameof(link));
}
link.LoadElementExtensions(reader, maxExtensionSize);
}
internal static protected void LoadElementExtensions(XmlReader reader, SyndicationPerson person, int maxExtensionSize)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
person.LoadElementExtensions(reader, maxExtensionSize);
}
internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationFeed feed, string version)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
if (FeedUtils.IsXmlns(name, ns))
{
return true;
}
return feed.TryParseAttribute(name, ns, value, version);
}
internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationItem item, string version)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
if (FeedUtils.IsXmlns(name, ns))
{
return true;
}
return item.TryParseAttribute(name, ns, value, version);
}
internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationCategory category, string version)
{
if (category == null)
{
throw new ArgumentNullException(nameof(category));
}
if (FeedUtils.IsXmlns(name, ns))
{
return true;
}
return category.TryParseAttribute(name, ns, value, version);
}
internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationLink link, string version)
{
if (link == null)
{
throw new ArgumentNullException(nameof(link));
}
if (FeedUtils.IsXmlns(name, ns))
{
return true;
}
return link.TryParseAttribute(name, ns, value, version);
}
internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationPerson person, string version)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
if (FeedUtils.IsXmlns(name, ns))
{
return true;
}
return person.TryParseAttribute(name, ns, value, version);
}
internal static protected bool TryParseContent(XmlReader reader, SyndicationItem item, string contentType, string version, out SyndicationContent content)
{
return item.TryParseContent(reader, contentType, version, out content);
}
internal static protected bool TryParseElement(XmlReader reader, SyndicationFeed feed, string version)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
return feed.TryParseElement(reader, version);
}
internal static protected bool TryParseElement(XmlReader reader, SyndicationItem item, string version)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
return item.TryParseElement(reader, version);
}
internal static protected bool TryParseElement(XmlReader reader, SyndicationCategory category, string version)
{
if (category == null)
{
throw new ArgumentNullException(nameof(category));
}
return category.TryParseElement(reader, version);
}
internal static protected bool TryParseElement(XmlReader reader, SyndicationLink link, string version)
{
if (link == null)
{
throw new ArgumentNullException(nameof(link));
}
return link.TryParseElement(reader, version);
}
internal static protected bool TryParseElement(XmlReader reader, SyndicationPerson person, string version)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
return person.TryParseElement(reader, version);
}
internal static protected void WriteAttributeExtensions(XmlWriter writer, SyndicationFeed feed, string version)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
feed.WriteAttributeExtensions(writer, version);
}
internal static protected void WriteAttributeExtensions(XmlWriter writer, SyndicationItem item, string version)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
item.WriteAttributeExtensions(writer, version);
}
internal static protected void WriteAttributeExtensions(XmlWriter writer, SyndicationCategory category, string version)
{
if (category == null)
{
throw new ArgumentNullException(nameof(category));
}
category.WriteAttributeExtensions(writer, version);
}
internal static protected void WriteAttributeExtensions(XmlWriter writer, SyndicationLink link, string version)
{
if (link == null)
{
throw new ArgumentNullException(nameof(link));
}
link.WriteAttributeExtensions(writer, version);
}
internal static protected void WriteAttributeExtensions(XmlWriter writer, SyndicationPerson person, string version)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
person.WriteAttributeExtensions(writer, version);
}
internal static protected void WriteElementExtensions(XmlWriter writer, SyndicationFeed feed, string version)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
feed.WriteElementExtensions(writer, version);
}
internal static protected void WriteElementExtensions(XmlWriter writer, SyndicationItem item, string version)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
item.WriteElementExtensions(writer, version);
}
internal static protected void WriteElementExtensions(XmlWriter writer, SyndicationCategory category, string version)
{
if (category == null)
{
throw new ArgumentNullException(nameof(category));
}
category.WriteElementExtensions(writer, version);
}
internal static protected void WriteElementExtensions(XmlWriter writer, SyndicationLink link, string version)
{
if (link == null)
{
throw new ArgumentNullException(nameof(link));
}
link.WriteElementExtensions(writer, version);
}
internal static protected void WriteElementExtensions(XmlWriter writer, SyndicationPerson person, string version)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
person.WriteElementExtensions(writer, version);
}
internal protected virtual void SetFeed(SyndicationFeed feed)
{
_feed = feed ?? throw new ArgumentNullException(nameof(feed));
}
internal Uri UriFromString(string uriString, UriKind uriKind, string localName, string namespaceURI, XmlReader reader)
{
return UriFromString(UriParser, uriString, uriKind, localName, namespaceURI, reader);
}
internal static Uri UriFromString(TryParseUriCallback uriParser, string uriString, UriKind uriKind, string localName, string namespaceURI, XmlReader reader)
{
Uri uri = null;
var elementQualifiedName = new XmlQualifiedName(localName, namespaceURI);
var xmlUriData = new XmlUriData(uriString, uriKind, elementQualifiedName);
object[] args = new object[] { xmlUriData, uri };
try
{
foreach (Delegate parser in uriParser.GetInvocationList())
{
if ((bool)parser.Method.Invoke(parser.Target, args))
{
uri = (Uri)args[args.Length - 1];
return uri;
}
}
}
catch (Exception e)
{
throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingUri), e);
}
DefaultUriParser(xmlUriData, out uri);
return uri;
}
internal DateTimeOffset DateFromString(string dateTimeString, XmlReader reader)
{
try
{
DateTimeOffset dateTimeOffset = default;
var elementQualifiedName = new XmlQualifiedName(reader.LocalName, reader.NamespaceURI);
var xmlDateTimeData = new XmlDateTimeData(dateTimeString, elementQualifiedName);
object[] args = new object[] { xmlDateTimeData, dateTimeOffset };
foreach (Delegate dateTimeParser in DateTimeParser.GetInvocationList())
{
if ((bool)dateTimeParser.Method.Invoke(dateTimeParser.Target, args))
{
dateTimeOffset = (DateTimeOffset)args[args.Length - 1];
return dateTimeOffset;
}
}
}
catch (Exception e)
{
throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDateTime), e);
}
throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDateTime));
}
internal static bool DefaultUriParser(XmlUriData XmlUriData, out Uri uri)
{
uri = new Uri(XmlUriData.UriString, XmlUriData.UriKind);
return true;
}
internal static void CloseBuffer(XmlBuffer buffer, XmlDictionaryWriter extWriter)
{
if (buffer == null)
{
return;
}
extWriter.WriteEndElement();
buffer.CloseSection();
buffer.Close();
}
internal static void CreateBufferIfRequiredAndWriteNode(ref XmlBuffer buffer, ref XmlDictionaryWriter extWriter, XmlReader reader, int maxExtensionSize)
{
if (buffer == null)
{
buffer = new XmlBuffer(maxExtensionSize);
extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
}
extWriter.WriteNode(reader, false);
}
internal static SyndicationFeed CreateFeedInstance(Type feedType)
{
if (feedType.Equals(typeof(SyndicationFeed)))
{
return new SyndicationFeed();
}
else
{
return (SyndicationFeed)Activator.CreateInstance(feedType);
}
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationFeed feed)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
CloseBuffer(buffer, writer);
feed.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationItem item)
{
Debug.Assert(item != null);
CloseBuffer(buffer, writer);
item.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationCategory category)
{
Debug.Assert(category != null);
CloseBuffer(buffer, writer);
category.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationLink link)
{
Debug.Assert(link != null);
CloseBuffer(buffer, writer);
link.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationPerson person)
{
Debug.Assert(person != null);
CloseBuffer(buffer, writer);
person.LoadElementExtensions(buffer);
}
internal static void MoveToStartElement(XmlReader reader)
{
Debug.Assert(reader != null, "reader != null");
if (!reader.IsStartElement())
{
XmlExceptionHelper.ThrowStartElementExpected(XmlDictionaryReader.CreateDictionaryReader(reader));
}
}
protected abstract SyndicationFeed CreateFeedInstance();
private static T GetNonNullValue<T>(T value, string errorMsg)
{
if (value == null)
{
throw new InvalidOperationException(errorMsg);
}
return value;
}
private static class XmlExceptionHelper
{
private static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1)
{
string s = SR.Format(res, arg1);
if (reader is IXmlLineInfo lineInfo && lineInfo.HasLineInfo())
{
s += " " + SR.Format(SR.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition);
}
throw new XmlException(s);
}
private static string GetName(string prefix, string localName)
{
if (prefix.Length == 0)
return localName;
else
return string.Concat(prefix, ":", localName);
}
private static string GetWhatWasFound(XmlDictionaryReader reader)
{
if (reader.EOF)
return SR.XmlFoundEndOfFile;
switch (reader.NodeType)
{
case XmlNodeType.Element:
return SR.Format(SR.XmlFoundElement, GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI);
case XmlNodeType.EndElement:
return SR.Format(SR.XmlFoundEndElement, GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI);
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return SR.Format(SR.XmlFoundText, reader.Value);
case XmlNodeType.Comment:
return SR.Format(SR.XmlFoundComment, reader.Value);
case XmlNodeType.CDATA:
return SR.Format(SR.XmlFoundCData, reader.Value);
}
return SR.Format(SR.XmlFoundNodeType, reader.NodeType);
}
static public void ThrowStartElementExpected(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlStartElementExpected, GetWhatWasFound(reader));
}
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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.
//
//
// Based on "libbzip2", Copyright (C) 1996-2007 Julian R Seward.
//
namespace DiscUtils.Compression
{
using System;
using System.IO;
/// <summary>
/// Implementation of a BZip2 decoder.
/// </summary>
public sealed class BZip2DecoderStream : Stream
{
private long _position;
private Stream _compressedStream;
private Ownership _ownsCompressed;
private BitStream _bitstream;
private BZip2RleStream _rleStream;
private BZip2BlockDecoder _blockDecoder;
private Crc32 _calcBlockCrc;
private byte[] _blockBuffer;
private uint _blockCrc;
private uint _compoundCrc;
private uint _calcCompoundCrc;
private bool _eof;
/// <summary>
/// Initializes a new instance of the BZip2DecoderStream class.
/// </summary>
/// <param name="stream">The compressed input stream.</param>
/// <param name="ownsStream">Whether ownership of stream passes to the new instance.</param>
public BZip2DecoderStream(Stream stream, Ownership ownsStream)
{
_compressedStream = stream;
_ownsCompressed = ownsStream;
_bitstream = new BigEndianBitStream(new BufferedStream(stream));
// The Magic BZh
byte[] magic = new byte[3];
magic[0] = (byte)_bitstream.Read(8);
magic[1] = (byte)_bitstream.Read(8);
magic[2] = (byte)_bitstream.Read(8);
if (magic[0] != 0x42 || magic[1] != 0x5A || magic[2] != 0x68)
{
throw new InvalidDataException("Bad magic at start of stream");
}
// The size of the decompression blocks in multiples of 100,000
int blockSize = (int)_bitstream.Read(8) - 0x30;
if (blockSize < 1 || blockSize > 9)
{
throw new InvalidDataException("Unexpected block size in header: " + blockSize);
}
blockSize *= 100000;
_rleStream = new BZip2RleStream();
_blockDecoder = new BZip2BlockDecoder(blockSize);
_blockBuffer = new byte[blockSize];
if (ReadBlock() == 0)
{
_eof = true;
}
}
/// <summary>
/// Gets an indication of whether read access is permitted.
/// </summary>
public override bool CanRead
{
get { return true; }
}
/// <summary>
/// Gets an indication of whether seeking is permitted.
/// </summary>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Gets an indication of whether write access is permitted.
/// </summary>
public override bool CanWrite
{
get { return false; }
}
/// <summary>
/// Gets the length of the stream (the capacity of the underlying buffer).
/// </summary>
public override long Length
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Gets and sets the current position within the stream.
/// </summary>
public override long Position
{
get { return _position; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Flushes all data to the underlying storage.
/// </summary>
public override void Flush()
{
throw new NotSupportedException();
}
/// <summary>
/// Reads a number of bytes from the stream.
/// </summary>
/// <param name="buffer">The destination buffer.</param>
/// <param name="offset">The start offset within the destination buffer.</param>
/// <param name="count">The number of bytes to read.</param>
/// <returns>The number of bytes read.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (buffer.Length < offset + count)
{
throw new ArgumentException("Buffer smaller than declared");
}
if (offset < 0)
{
throw new ArgumentException("Offset less than zero", "offset");
}
if (count < 0)
{
throw new ArgumentException("Count less than zero", "count");
}
if (_eof)
{
throw new IOException("Attempt to read beyond end of stream");
}
if (count == 0)
{
return 0;
}
int numRead = _rleStream.Read(buffer, offset, count);
if (numRead == 0)
{
// If there was an existing block, check it's crc.
if (_calcBlockCrc != null)
{
if (_blockCrc != _calcBlockCrc.Value)
{
throw new InvalidDataException("Decompression failed - block CRC mismatch");
}
_calcCompoundCrc = ((_calcCompoundCrc << 1) | (_calcCompoundCrc >> 31)) ^ _blockCrc;
}
// Read a new block (if any), if none - check the overall CRC before returning
if (ReadBlock() == 0)
{
_eof = true;
if (_calcCompoundCrc != _compoundCrc)
{
throw new InvalidDataException("Decompression failed - compound CRC");
}
return 0;
}
numRead = _rleStream.Read(buffer, offset, count);
}
_calcBlockCrc.Process(buffer, offset, numRead);
// Pre-read next block, so a client that knows the decompressed length will still
// have the overall CRC calculated.
if (_rleStream.AtEof)
{
// If there was an existing block, check it's crc.
if (_calcBlockCrc != null)
{
if (_blockCrc != _calcBlockCrc.Value)
{
throw new InvalidDataException("Decompression failed - block CRC mismatch");
}
}
_calcCompoundCrc = ((_calcCompoundCrc << 1) | (_calcCompoundCrc >> 31)) ^ _blockCrc;
if (ReadBlock() == 0)
{
_eof = true;
if (_calcCompoundCrc != _compoundCrc)
{
throw new InvalidDataException("Decompression failed - compound CRC mismatch");
}
return numRead;
}
}
_position += numRead;
return numRead;
}
/// <summary>
/// Changes the current stream position.
/// </summary>
/// <param name="offset">The origin-relative stream position.</param>
/// <param name="origin">The origin for the stream position.</param>
/// <returns>The new stream position.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Sets the length of the stream (the underlying buffer's capacity).
/// </summary>
/// <param name="value">The new length of the stream.</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Writes a buffer to the stream.
/// </summary>
/// <param name="buffer">The buffer to write.</param>
/// <param name="offset">The starting offset within buffer.</param>
/// <param name="count">The number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
/// <summary>
/// Releases underlying resources.
/// </summary>
/// <param name="disposing">Whether this method is called from Dispose.</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_compressedStream != null && _ownsCompressed == Ownership.Dispose)
{
_compressedStream.Dispose();
}
_compressedStream = null;
if (_rleStream != null)
{
_rleStream.Dispose();
_rleStream = null;
}
}
}
finally
{
base.Dispose(disposing);
}
}
private int ReadBlock()
{
ulong marker = ReadMarker();
if (marker == 0x314159265359)
{
int blockSize = _blockDecoder.Process(_bitstream, _blockBuffer, 0);
_rleStream.Reset(_blockBuffer, 0, blockSize);
_blockCrc = _blockDecoder.Crc;
_calcBlockCrc = new Crc32BigEndian(Crc32Algorithm.Common);
return blockSize;
}
else if (marker == 0x177245385090)
{
_compoundCrc = ReadUint();
return 0;
}
else
{
throw new InvalidDataException("Found invalid marker in stream");
}
}
private uint ReadUint()
{
uint val = 0;
for (int i = 0; i < 4; ++i)
{
val = (val << 8) | _bitstream.Read(8);
}
return val;
}
private ulong ReadMarker()
{
ulong marker = 0;
for (int i = 0; i < 6; ++i)
{
marker = (marker << 8) | _bitstream.Read(8);
}
return marker;
}
}
}
| |
using System.Collections.Concurrent;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Autofac;
using Autofac.Features.Metadata;
using Microsoft.Extensions.Hosting;
using Miningcore.Configuration;
using Miningcore.Extensions;
using Miningcore.Messaging;
using Miningcore.Mining;
using Miningcore.Notifications.Messages;
using Miningcore.Persistence;
using Miningcore.Persistence.Model;
using Miningcore.Persistence.Repositories;
using NLog;
using Contract = Miningcore.Contracts.Contract;
namespace Miningcore.Payments;
/// <summary>
/// Coin agnostic payment processor
/// </summary>
public class PayoutManager : BackgroundService
{
public PayoutManager(IComponentContext ctx,
IConnectionFactory cf,
IBlockRepository blockRepo,
IShareRepository shareRepo,
IBalanceRepository balanceRepo,
ClusterConfig clusterConfig,
IMessageBus messageBus)
{
Contract.RequiresNonNull(ctx, nameof(ctx));
Contract.RequiresNonNull(cf, nameof(cf));
Contract.RequiresNonNull(blockRepo, nameof(blockRepo));
Contract.RequiresNonNull(shareRepo, nameof(shareRepo));
Contract.RequiresNonNull(balanceRepo, nameof(balanceRepo));
Contract.RequiresNonNull(messageBus, nameof(messageBus));
this.ctx = ctx;
this.cf = cf;
this.blockRepo = blockRepo;
this.shareRepo = shareRepo;
this.balanceRepo = balanceRepo;
this.messageBus = messageBus;
this.clusterConfig = clusterConfig;
interval = TimeSpan.FromSeconds(clusterConfig.PaymentProcessing.Interval > 0 ?
clusterConfig.PaymentProcessing.Interval : 600);
}
private static readonly ILogger logger = LogManager.GetCurrentClassLogger();
private readonly IBalanceRepository balanceRepo;
private readonly IBlockRepository blockRepo;
private readonly IConnectionFactory cf;
private readonly IComponentContext ctx;
private readonly IShareRepository shareRepo;
private readonly IMessageBus messageBus;
private readonly TimeSpan interval;
private readonly ConcurrentDictionary<string, IMiningPool> pools = new();
private readonly ClusterConfig clusterConfig;
private readonly CompositeDisposable disposables = new();
#if !DEBUG
private static readonly TimeSpan initialRunDelay = TimeSpan.FromMinutes(1);
#else
private static readonly TimeSpan initialRunDelay = TimeSpan.FromSeconds(15);
#endif
private void AttachPool(IMiningPool pool)
{
pools.TryAdd(pool.Config.Id, pool);
}
private void OnPoolStatusNotification(PoolStatusNotification notification)
{
if(notification.Status == PoolStatus.Online)
AttachPool(notification.Pool);
}
private async Task ProcessPoolsAsync(CancellationToken ct)
{
foreach(var pool in pools.Values.ToArray().Where(x => x.Config.Enabled && x.Config.PaymentProcessing.Enabled))
{
var config = pool.Config;
logger.Info(() => $"Processing payments for pool {config.Id}");
try
{
var family = HandleFamilyOverride(config.Template.Family, config);
// resolve payout handler
var handlerImpl = ctx.Resolve<IEnumerable<Meta<Lazy<IPayoutHandler, CoinFamilyAttribute>>>>()
.First(x => x.Value.Metadata.SupportedFamilies.Contains(family)).Value;
var handler = handlerImpl.Value;
await handler.ConfigureAsync(clusterConfig, config, ct);
// resolve payout scheme
var scheme = ctx.ResolveKeyed<IPayoutScheme>(config.PaymentProcessing.PayoutScheme);
await UpdatePoolBalancesAsync(pool, config, handler, scheme, ct);
await PayoutPoolBalancesAsync(pool, config, handler, ct);
}
catch(InvalidOperationException ex)
{
logger.Error(ex.InnerException ?? ex, () => $"[{config.Id}] Payment processing failed");
}
catch(AggregateException ex)
{
switch(ex.InnerException)
{
case HttpRequestException httpEx:
logger.Error(() => $"[{config.Id}] Payment processing failed: {httpEx.Message}");
break;
default:
logger.Error(ex.InnerException, () => $"[{config.Id}] Payment processing failed");
break;
}
}
catch(Exception ex)
{
logger.Error(ex, () => $"[{config.Id}] Payment processing failed");
}
}
}
private static CoinFamily HandleFamilyOverride(CoinFamily family, PoolConfig pool)
{
switch(family)
{
case CoinFamily.Equihash:
var equihashTemplate = pool.Template.As<EquihashCoinTemplate>();
if(equihashTemplate.UseBitcoinPayoutHandler)
return CoinFamily.Bitcoin;
break;
}
return family;
}
private async Task UpdatePoolBalancesAsync(IMiningPool pool, PoolConfig config, IPayoutHandler handler, IPayoutScheme scheme, CancellationToken ct)
{
// get pending blockRepo for pool
var pendingBlocks = await cf.Run(con => blockRepo.GetPendingBlocksForPoolAsync(con, config.Id));
// classify
var updatedBlocks = await handler.ClassifyBlocksAsync(pool, pendingBlocks, ct);
if(updatedBlocks.Any())
{
foreach(var block in updatedBlocks.OrderBy(x => x.Created))
{
logger.Info(() => $"Processing payments for pool {config.Id}, block {block.BlockHeight}");
await cf.RunTx(async (con, tx) =>
{
if(!block.Effort.HasValue) // fill block effort if empty
await CalculateBlockEffortAsync(pool, config, block, handler, ct);
switch(block.Status)
{
case BlockStatus.Confirmed:
// blockchains that do not support block-reward payments via coinbase Tx
// must generate balance records for all reward recipients instead
var blockReward = await handler.UpdateBlockRewardBalancesAsync(con, tx, pool, block, ct);
await scheme.UpdateBalancesAsync(con, tx, pool, handler, block, blockReward, ct);
await blockRepo.UpdateBlockAsync(con, tx, block);
break;
case BlockStatus.Orphaned:
case BlockStatus.Pending:
await blockRepo.UpdateBlockAsync(con, tx, block);
break;
}
});
}
}
else
logger.Info(() => $"No updated blocks for pool {config.Id}");
}
private async Task PayoutPoolBalancesAsync(IMiningPool pool, PoolConfig config, IPayoutHandler handler, CancellationToken ct)
{
var poolBalancesOverMinimum = await cf.Run(con =>
balanceRepo.GetPoolBalancesOverThresholdAsync(con, config.Id, config.PaymentProcessing.MinimumPayment));
if(poolBalancesOverMinimum.Length > 0)
{
try
{
await handler.PayoutAsync(pool, poolBalancesOverMinimum, ct);
}
catch(Exception ex)
{
await NotifyPayoutFailureAsync(poolBalancesOverMinimum, config, ex);
throw;
}
}
else
logger.Info(() => $"No balances over configured minimum payout for pool {config.Id}");
}
private Task NotifyPayoutFailureAsync(Balance[] balances, PoolConfig pool, Exception ex)
{
messageBus.SendMessage(new PaymentNotification(pool.Id, ex.Message, balances.Sum(x => x.Amount), pool.Template.Symbol));
return Task.FromResult(true);
}
private async Task CalculateBlockEffortAsync(IMiningPool pool, PoolConfig config, Block block, IPayoutHandler handler, CancellationToken ct)
{
// get share date-range
var from = DateTime.MinValue;
var to = block.Created;
// get last block for pool
var lastBlock = await cf.Run(con => blockRepo.GetBlockBeforeAsync(con, config.Id, new[]
{
BlockStatus.Confirmed,
BlockStatus.Orphaned,
BlockStatus.Pending,
}, block.Created));
if(lastBlock != null)
from = lastBlock.Created;
// get combined diff of all shares for block
var accumulatedShareDiffForBlock = await cf.Run(con =>
shareRepo.GetAccumulatedShareDifficultyBetweenCreatedAsync(con, config.Id, from, to));
// handler has the final say
if(accumulatedShareDiffForBlock.HasValue)
await handler.CalculateBlockEffortAsync(pool, block, accumulatedShareDiffForBlock.Value, ct);
}
protected override async Task ExecuteAsync(CancellationToken ct)
{
try
{
// monitor pool lifetime
disposables.Add(messageBus.Listen<PoolStatusNotification>()
.ObserveOn(TaskPoolScheduler.Default)
.Subscribe(OnPoolStatusNotification));
logger.Info(() => "Online");
// Allow all pools to actually come up before the first payment processing run
await Task.Delay(initialRunDelay, ct);
while(!ct.IsCancellationRequested)
{
try
{
await ProcessPoolsAsync(ct);
}
catch(Exception ex)
{
logger.Error(ex);
}
await Task.Delay(interval, ct);
}
logger.Info(() => "Offline");
}
finally
{
disposables.Dispose();
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/storagetransfer/v1/transfer.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Storagetransfer.V1 {
/// <summary>Holder for reflection information generated from google/storagetransfer/v1/transfer.proto</summary>
public static partial class TransferReflection {
#region Descriptor
/// <summary>File descriptor for google/storagetransfer/v1/transfer.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TransferReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cihnb29nbGUvc3RvcmFnZXRyYW5zZmVyL3YxL3RyYW5zZmVyLnByb3RvEhln",
"b29nbGUuc3RvcmFnZXRyYW5zZmVyLnYxGhxnb29nbGUvYXBpL2Fubm90YXRp",
"b25zLnByb3RvGhtnb29nbGUvcHJvdG9idWYvZW1wdHkucHJvdG8aIGdvb2ds",
"ZS9wcm90b2J1Zi9maWVsZF9tYXNrLnByb3RvGi5nb29nbGUvc3RvcmFnZXRy",
"YW5zZmVyL3YxL3RyYW5zZmVyX3R5cGVzLnByb3RvIjQKHkdldEdvb2dsZVNl",
"cnZpY2VBY2NvdW50UmVxdWVzdBISCgpwcm9qZWN0X2lkGAEgASgJIlgKGENy",
"ZWF0ZVRyYW5zZmVySm9iUmVxdWVzdBI8Cgx0cmFuc2Zlcl9qb2IYASABKAsy",
"Ji5nb29nbGUuc3RvcmFnZXRyYW5zZmVyLnYxLlRyYW5zZmVySm9iIsIBChhV",
"cGRhdGVUcmFuc2ZlckpvYlJlcXVlc3QSEAoIam9iX25hbWUYASABKAkSEgoK",
"cHJvamVjdF9pZBgCIAEoCRI8Cgx0cmFuc2Zlcl9qb2IYAyABKAsyJi5nb29n",
"bGUuc3RvcmFnZXRyYW5zZmVyLnYxLlRyYW5zZmVySm9iEkIKHnVwZGF0ZV90",
"cmFuc2Zlcl9qb2JfZmllbGRfbWFzaxgEIAEoCzIaLmdvb2dsZS5wcm90b2J1",
"Zi5GaWVsZE1hc2siPQoVR2V0VHJhbnNmZXJKb2JSZXF1ZXN0EhAKCGpvYl9u",
"YW1lGAEgASgJEhIKCnByb2plY3RfaWQYAiABKAkiUAoXTGlzdFRyYW5zZmVy",
"Sm9ic1JlcXVlc3QSDgoGZmlsdGVyGAEgASgJEhEKCXBhZ2Vfc2l6ZRgEIAEo",
"BRISCgpwYWdlX3Rva2VuGAUgASgJInIKGExpc3RUcmFuc2ZlckpvYnNSZXNw",
"b25zZRI9Cg10cmFuc2Zlcl9qb2JzGAEgAygLMiYuZ29vZ2xlLnN0b3JhZ2V0",
"cmFuc2Zlci52MS5UcmFuc2ZlckpvYhIXCg9uZXh0X3BhZ2VfdG9rZW4YAiAB",
"KAkiLQodUGF1c2VUcmFuc2Zlck9wZXJhdGlvblJlcXVlc3QSDAoEbmFtZRgB",
"IAEoCSIuCh5SZXN1bWVUcmFuc2Zlck9wZXJhdGlvblJlcXVlc3QSDAoEbmFt",
"ZRgBIAEoCTL5CAoWU3RvcmFnZVRyYW5zZmVyU2VydmljZRK1AQoXR2V0R29v",
"Z2xlU2VydmljZUFjY291bnQSOS5nb29nbGUuc3RvcmFnZXRyYW5zZmVyLnYx",
"LkdldEdvb2dsZVNlcnZpY2VBY2NvdW50UmVxdWVzdBovLmdvb2dsZS5zdG9y",
"YWdldHJhbnNmZXIudjEuR29vZ2xlU2VydmljZUFjY291bnQiLoLT5JMCKBIm",
"L3YxL2dvb2dsZVNlcnZpY2VBY2NvdW50cy97cHJvamVjdF9pZH0SmAEKEUNy",
"ZWF0ZVRyYW5zZmVySm9iEjMuZ29vZ2xlLnN0b3JhZ2V0cmFuc2Zlci52MS5D",
"cmVhdGVUcmFuc2ZlckpvYlJlcXVlc3QaJi5nb29nbGUuc3RvcmFnZXRyYW5z",
"ZmVyLnYxLlRyYW5zZmVySm9iIiaC0+STAiAiEC92MS90cmFuc2ZlckpvYnM6",
"DHRyYW5zZmVyX2pvYhKbAQoRVXBkYXRlVHJhbnNmZXJKb2ISMy5nb29nbGUu",
"c3RvcmFnZXRyYW5zZmVyLnYxLlVwZGF0ZVRyYW5zZmVySm9iUmVxdWVzdBom",
"Lmdvb2dsZS5zdG9yYWdldHJhbnNmZXIudjEuVHJhbnNmZXJKb2IiKYLT5JMC",
"IzIeL3YxL3tqb2JfbmFtZT10cmFuc2ZlckpvYnMvKip9OgEqEpIBCg5HZXRU",
"cmFuc2ZlckpvYhIwLmdvb2dsZS5zdG9yYWdldHJhbnNmZXIudjEuR2V0VHJh",
"bnNmZXJKb2JSZXF1ZXN0GiYuZ29vZ2xlLnN0b3JhZ2V0cmFuc2Zlci52MS5U",
"cmFuc2ZlckpvYiImgtPkkwIgEh4vdjEve2pvYl9uYW1lPXRyYW5zZmVySm9i",
"cy8qKn0SlQEKEExpc3RUcmFuc2ZlckpvYnMSMi5nb29nbGUuc3RvcmFnZXRy",
"YW5zZmVyLnYxLkxpc3RUcmFuc2ZlckpvYnNSZXF1ZXN0GjMuZ29vZ2xlLnN0",
"b3JhZ2V0cmFuc2Zlci52MS5MaXN0VHJhbnNmZXJKb2JzUmVzcG9uc2UiGILT",
"5JMCEhIQL3YxL3RyYW5zZmVySm9icxKdAQoWUGF1c2VUcmFuc2Zlck9wZXJh",
"dGlvbhI4Lmdvb2dsZS5zdG9yYWdldHJhbnNmZXIudjEuUGF1c2VUcmFuc2Zl",
"ck9wZXJhdGlvblJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiMYLT",
"5JMCKyImL3YxL3tuYW1lPXRyYW5zZmVyT3BlcmF0aW9ucy8qKn06cGF1c2U6",
"ASoSoAEKF1Jlc3VtZVRyYW5zZmVyT3BlcmF0aW9uEjkuZ29vZ2xlLnN0b3Jh",
"Z2V0cmFuc2Zlci52MS5SZXN1bWVUcmFuc2Zlck9wZXJhdGlvblJlcXVlc3Qa",
"Fi5nb29nbGUucHJvdG9idWYuRW1wdHkiMoLT5JMCLCInL3YxL3tuYW1lPXRy",
"YW5zZmVyT3BlcmF0aW9ucy8qKn06cmVzdW1lOgEqQoEBCiNjb20uZ29vZ2xl",
"LnN0b3JhZ2V0cmFuc2Zlci52MS5wcm90b0INVHJhbnNmZXJQcm90b1pIZ29v",
"Z2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9zdG9yYWdldHJh",
"bnNmZXIvdjE7c3RvcmFnZXRyYW5zZmVy+AEBYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.FieldMaskReflection.Descriptor, global::Google.Storagetransfer.V1.TransferTypesReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Storagetransfer.V1.GetGoogleServiceAccountRequest), global::Google.Storagetransfer.V1.GetGoogleServiceAccountRequest.Parser, new[]{ "ProjectId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Storagetransfer.V1.CreateTransferJobRequest), global::Google.Storagetransfer.V1.CreateTransferJobRequest.Parser, new[]{ "TransferJob" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Storagetransfer.V1.UpdateTransferJobRequest), global::Google.Storagetransfer.V1.UpdateTransferJobRequest.Parser, new[]{ "JobName", "ProjectId", "TransferJob", "UpdateTransferJobFieldMask" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Storagetransfer.V1.GetTransferJobRequest), global::Google.Storagetransfer.V1.GetTransferJobRequest.Parser, new[]{ "JobName", "ProjectId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Storagetransfer.V1.ListTransferJobsRequest), global::Google.Storagetransfer.V1.ListTransferJobsRequest.Parser, new[]{ "Filter", "PageSize", "PageToken" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Storagetransfer.V1.ListTransferJobsResponse), global::Google.Storagetransfer.V1.ListTransferJobsResponse.Parser, new[]{ "TransferJobs", "NextPageToken" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Storagetransfer.V1.PauseTransferOperationRequest), global::Google.Storagetransfer.V1.PauseTransferOperationRequest.Parser, new[]{ "Name" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Storagetransfer.V1.ResumeTransferOperationRequest), global::Google.Storagetransfer.V1.ResumeTransferOperationRequest.Parser, new[]{ "Name" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Request passed to GetGoogleServiceAccount.
/// </summary>
public sealed partial class GetGoogleServiceAccountRequest : pb::IMessage<GetGoogleServiceAccountRequest> {
private static readonly pb::MessageParser<GetGoogleServiceAccountRequest> _parser = new pb::MessageParser<GetGoogleServiceAccountRequest>(() => new GetGoogleServiceAccountRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetGoogleServiceAccountRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Storagetransfer.V1.TransferReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetGoogleServiceAccountRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetGoogleServiceAccountRequest(GetGoogleServiceAccountRequest other) : this() {
projectId_ = other.projectId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetGoogleServiceAccountRequest Clone() {
return new GetGoogleServiceAccountRequest(this);
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 1;
private string projectId_ = "";
/// <summary>
/// The ID of the Google Cloud Platform Console project that the Google service
/// account is associated with.
/// Required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetGoogleServiceAccountRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetGoogleServiceAccountRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectId != other.ProjectId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ProjectId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ProjectId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetGoogleServiceAccountRequest other) {
if (other == null) {
return;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
ProjectId = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// Request passed to CreateTransferJob.
/// </summary>
public sealed partial class CreateTransferJobRequest : pb::IMessage<CreateTransferJobRequest> {
private static readonly pb::MessageParser<CreateTransferJobRequest> _parser = new pb::MessageParser<CreateTransferJobRequest>(() => new CreateTransferJobRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CreateTransferJobRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Storagetransfer.V1.TransferReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateTransferJobRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateTransferJobRequest(CreateTransferJobRequest other) : this() {
TransferJob = other.transferJob_ != null ? other.TransferJob.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateTransferJobRequest Clone() {
return new CreateTransferJobRequest(this);
}
/// <summary>Field number for the "transfer_job" field.</summary>
public const int TransferJobFieldNumber = 1;
private global::Google.Storagetransfer.V1.TransferJob transferJob_;
/// <summary>
/// The job to create.
/// Required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Storagetransfer.V1.TransferJob TransferJob {
get { return transferJob_; }
set {
transferJob_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CreateTransferJobRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CreateTransferJobRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(TransferJob, other.TransferJob)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (transferJob_ != null) hash ^= TransferJob.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (transferJob_ != null) {
output.WriteRawTag(10);
output.WriteMessage(TransferJob);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (transferJob_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(TransferJob);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CreateTransferJobRequest other) {
if (other == null) {
return;
}
if (other.transferJob_ != null) {
if (transferJob_ == null) {
transferJob_ = new global::Google.Storagetransfer.V1.TransferJob();
}
TransferJob.MergeFrom(other.TransferJob);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (transferJob_ == null) {
transferJob_ = new global::Google.Storagetransfer.V1.TransferJob();
}
input.ReadMessage(transferJob_);
break;
}
}
}
}
}
/// <summary>
/// Request passed to UpdateTransferJob.
/// </summary>
public sealed partial class UpdateTransferJobRequest : pb::IMessage<UpdateTransferJobRequest> {
private static readonly pb::MessageParser<UpdateTransferJobRequest> _parser = new pb::MessageParser<UpdateTransferJobRequest>(() => new UpdateTransferJobRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UpdateTransferJobRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Storagetransfer.V1.TransferReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateTransferJobRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateTransferJobRequest(UpdateTransferJobRequest other) : this() {
jobName_ = other.jobName_;
projectId_ = other.projectId_;
TransferJob = other.transferJob_ != null ? other.TransferJob.Clone() : null;
UpdateTransferJobFieldMask = other.updateTransferJobFieldMask_ != null ? other.UpdateTransferJobFieldMask.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateTransferJobRequest Clone() {
return new UpdateTransferJobRequest(this);
}
/// <summary>Field number for the "job_name" field.</summary>
public const int JobNameFieldNumber = 1;
private string jobName_ = "";
/// <summary>
/// The name of job to update.
/// Required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JobName {
get { return jobName_; }
set {
jobName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 2;
private string projectId_ = "";
/// <summary>
/// The ID of the Google Cloud Platform Console project that owns the job.
/// Required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "transfer_job" field.</summary>
public const int TransferJobFieldNumber = 3;
private global::Google.Storagetransfer.V1.TransferJob transferJob_;
/// <summary>
/// The job to update.
/// Required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Storagetransfer.V1.TransferJob TransferJob {
get { return transferJob_; }
set {
transferJob_ = value;
}
}
/// <summary>Field number for the "update_transfer_job_field_mask" field.</summary>
public const int UpdateTransferJobFieldMaskFieldNumber = 4;
private global::Google.Protobuf.WellKnownTypes.FieldMask updateTransferJobFieldMask_;
/// <summary>
/// The field mask of the fields in `transferJob` that are to be updated in
/// this request. Fields in `transferJob` that can be updated are:
/// `description`, `transferSpec`, and `status`. To update the `transferSpec`
/// of the job, a complete transfer specification has to be provided. An
/// incomplete specification which misses any required fields will be rejected
/// with the error `INVALID_ARGUMENT`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.FieldMask UpdateTransferJobFieldMask {
get { return updateTransferJobFieldMask_; }
set {
updateTransferJobFieldMask_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UpdateTransferJobRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UpdateTransferJobRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (JobName != other.JobName) return false;
if (ProjectId != other.ProjectId) return false;
if (!object.Equals(TransferJob, other.TransferJob)) return false;
if (!object.Equals(UpdateTransferJobFieldMask, other.UpdateTransferJobFieldMask)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (JobName.Length != 0) hash ^= JobName.GetHashCode();
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
if (transferJob_ != null) hash ^= TransferJob.GetHashCode();
if (updateTransferJobFieldMask_ != null) hash ^= UpdateTransferJobFieldMask.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (JobName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(JobName);
}
if (ProjectId.Length != 0) {
output.WriteRawTag(18);
output.WriteString(ProjectId);
}
if (transferJob_ != null) {
output.WriteRawTag(26);
output.WriteMessage(TransferJob);
}
if (updateTransferJobFieldMask_ != null) {
output.WriteRawTag(34);
output.WriteMessage(UpdateTransferJobFieldMask);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (JobName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JobName);
}
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
if (transferJob_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(TransferJob);
}
if (updateTransferJobFieldMask_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdateTransferJobFieldMask);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UpdateTransferJobRequest other) {
if (other == null) {
return;
}
if (other.JobName.Length != 0) {
JobName = other.JobName;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
if (other.transferJob_ != null) {
if (transferJob_ == null) {
transferJob_ = new global::Google.Storagetransfer.V1.TransferJob();
}
TransferJob.MergeFrom(other.TransferJob);
}
if (other.updateTransferJobFieldMask_ != null) {
if (updateTransferJobFieldMask_ == null) {
updateTransferJobFieldMask_ = new global::Google.Protobuf.WellKnownTypes.FieldMask();
}
UpdateTransferJobFieldMask.MergeFrom(other.UpdateTransferJobFieldMask);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
JobName = input.ReadString();
break;
}
case 18: {
ProjectId = input.ReadString();
break;
}
case 26: {
if (transferJob_ == null) {
transferJob_ = new global::Google.Storagetransfer.V1.TransferJob();
}
input.ReadMessage(transferJob_);
break;
}
case 34: {
if (updateTransferJobFieldMask_ == null) {
updateTransferJobFieldMask_ = new global::Google.Protobuf.WellKnownTypes.FieldMask();
}
input.ReadMessage(updateTransferJobFieldMask_);
break;
}
}
}
}
}
/// <summary>
/// Request passed to GetTransferJob.
/// </summary>
public sealed partial class GetTransferJobRequest : pb::IMessage<GetTransferJobRequest> {
private static readonly pb::MessageParser<GetTransferJobRequest> _parser = new pb::MessageParser<GetTransferJobRequest>(() => new GetTransferJobRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetTransferJobRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Storagetransfer.V1.TransferReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetTransferJobRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetTransferJobRequest(GetTransferJobRequest other) : this() {
jobName_ = other.jobName_;
projectId_ = other.projectId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetTransferJobRequest Clone() {
return new GetTransferJobRequest(this);
}
/// <summary>Field number for the "job_name" field.</summary>
public const int JobNameFieldNumber = 1;
private string jobName_ = "";
/// <summary>
/// The job to get.
/// Required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JobName {
get { return jobName_; }
set {
jobName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 2;
private string projectId_ = "";
/// <summary>
/// The ID of the Google Cloud Platform Console project that owns the job.
/// Required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetTransferJobRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetTransferJobRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (JobName != other.JobName) return false;
if (ProjectId != other.ProjectId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (JobName.Length != 0) hash ^= JobName.GetHashCode();
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (JobName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(JobName);
}
if (ProjectId.Length != 0) {
output.WriteRawTag(18);
output.WriteString(ProjectId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (JobName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JobName);
}
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetTransferJobRequest other) {
if (other == null) {
return;
}
if (other.JobName.Length != 0) {
JobName = other.JobName;
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
JobName = input.ReadString();
break;
}
case 18: {
ProjectId = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// `project_id`, `job_names`, and `job_statuses` are query parameters that can
/// be specified when listing transfer jobs.
/// </summary>
public sealed partial class ListTransferJobsRequest : pb::IMessage<ListTransferJobsRequest> {
private static readonly pb::MessageParser<ListTransferJobsRequest> _parser = new pb::MessageParser<ListTransferJobsRequest>(() => new ListTransferJobsRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListTransferJobsRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Storagetransfer.V1.TransferReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListTransferJobsRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListTransferJobsRequest(ListTransferJobsRequest other) : this() {
filter_ = other.filter_;
pageSize_ = other.pageSize_;
pageToken_ = other.pageToken_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListTransferJobsRequest Clone() {
return new ListTransferJobsRequest(this);
}
/// <summary>Field number for the "filter" field.</summary>
public const int FilterFieldNumber = 1;
private string filter_ = "";
/// <summary>
/// A list of query parameters specified as JSON text in the form of
/// {"project_id":"my_project_id",
/// "job_names":["jobid1","jobid2",...],
/// "job_statuses":["status1","status2",...]}.
/// Since `job_names` and `job_statuses` support multiple values, their values
/// must be specified with array notation. `project_id` is required. `job_names`
/// and `job_statuses` are optional. The valid values for `job_statuses` are
/// case-insensitive: `ENABLED`, `DISABLED`, and `DELETED`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Filter {
get { return filter_; }
set {
filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "page_size" field.</summary>
public const int PageSizeFieldNumber = 4;
private int pageSize_;
/// <summary>
/// The list page size. The max allowed value is 256.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int PageSize {
get { return pageSize_; }
set {
pageSize_ = value;
}
}
/// <summary>Field number for the "page_token" field.</summary>
public const int PageTokenFieldNumber = 5;
private string pageToken_ = "";
/// <summary>
/// The list page token.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string PageToken {
get { return pageToken_; }
set {
pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListTransferJobsRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListTransferJobsRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Filter != other.Filter) return false;
if (PageSize != other.PageSize) return false;
if (PageToken != other.PageToken) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Filter.Length != 0) hash ^= Filter.GetHashCode();
if (PageSize != 0) hash ^= PageSize.GetHashCode();
if (PageToken.Length != 0) hash ^= PageToken.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Filter.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Filter);
}
if (PageSize != 0) {
output.WriteRawTag(32);
output.WriteInt32(PageSize);
}
if (PageToken.Length != 0) {
output.WriteRawTag(42);
output.WriteString(PageToken);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Filter.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Filter);
}
if (PageSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize);
}
if (PageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListTransferJobsRequest other) {
if (other == null) {
return;
}
if (other.Filter.Length != 0) {
Filter = other.Filter;
}
if (other.PageSize != 0) {
PageSize = other.PageSize;
}
if (other.PageToken.Length != 0) {
PageToken = other.PageToken;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Filter = input.ReadString();
break;
}
case 32: {
PageSize = input.ReadInt32();
break;
}
case 42: {
PageToken = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// Response from ListTransferJobs.
/// </summary>
public sealed partial class ListTransferJobsResponse : pb::IMessage<ListTransferJobsResponse> {
private static readonly pb::MessageParser<ListTransferJobsResponse> _parser = new pb::MessageParser<ListTransferJobsResponse>(() => new ListTransferJobsResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListTransferJobsResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Storagetransfer.V1.TransferReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListTransferJobsResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListTransferJobsResponse(ListTransferJobsResponse other) : this() {
transferJobs_ = other.transferJobs_.Clone();
nextPageToken_ = other.nextPageToken_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListTransferJobsResponse Clone() {
return new ListTransferJobsResponse(this);
}
/// <summary>Field number for the "transfer_jobs" field.</summary>
public const int TransferJobsFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Storagetransfer.V1.TransferJob> _repeated_transferJobs_codec
= pb::FieldCodec.ForMessage(10, global::Google.Storagetransfer.V1.TransferJob.Parser);
private readonly pbc::RepeatedField<global::Google.Storagetransfer.V1.TransferJob> transferJobs_ = new pbc::RepeatedField<global::Google.Storagetransfer.V1.TransferJob>();
/// <summary>
/// A list of transfer jobs.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Storagetransfer.V1.TransferJob> TransferJobs {
get { return transferJobs_; }
}
/// <summary>Field number for the "next_page_token" field.</summary>
public const int NextPageTokenFieldNumber = 2;
private string nextPageToken_ = "";
/// <summary>
/// The list next page token.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string NextPageToken {
get { return nextPageToken_; }
set {
nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListTransferJobsResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListTransferJobsResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!transferJobs_.Equals(other.transferJobs_)) return false;
if (NextPageToken != other.NextPageToken) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= transferJobs_.GetHashCode();
if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
transferJobs_.WriteTo(output, _repeated_transferJobs_codec);
if (NextPageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(NextPageToken);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += transferJobs_.CalculateSize(_repeated_transferJobs_codec);
if (NextPageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListTransferJobsResponse other) {
if (other == null) {
return;
}
transferJobs_.Add(other.transferJobs_);
if (other.NextPageToken.Length != 0) {
NextPageToken = other.NextPageToken;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
transferJobs_.AddEntriesFrom(input, _repeated_transferJobs_codec);
break;
}
case 18: {
NextPageToken = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// Request passed to PauseTransferOperation.
/// </summary>
public sealed partial class PauseTransferOperationRequest : pb::IMessage<PauseTransferOperationRequest> {
private static readonly pb::MessageParser<PauseTransferOperationRequest> _parser = new pb::MessageParser<PauseTransferOperationRequest>(() => new PauseTransferOperationRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PauseTransferOperationRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Storagetransfer.V1.TransferReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PauseTransferOperationRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PauseTransferOperationRequest(PauseTransferOperationRequest other) : this() {
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PauseTransferOperationRequest Clone() {
return new PauseTransferOperationRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The name of the transfer operation.
/// Required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PauseTransferOperationRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PauseTransferOperationRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PauseTransferOperationRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// Request passed to ResumeTransferOperation.
/// </summary>
public sealed partial class ResumeTransferOperationRequest : pb::IMessage<ResumeTransferOperationRequest> {
private static readonly pb::MessageParser<ResumeTransferOperationRequest> _parser = new pb::MessageParser<ResumeTransferOperationRequest>(() => new ResumeTransferOperationRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ResumeTransferOperationRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Storagetransfer.V1.TransferReflection.Descriptor.MessageTypes[7]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResumeTransferOperationRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResumeTransferOperationRequest(ResumeTransferOperationRequest other) : this() {
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResumeTransferOperationRequest Clone() {
return new ResumeTransferOperationRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The name of the transfer operation.
/// Required.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ResumeTransferOperationRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ResumeTransferOperationRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ResumeTransferOperationRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/*
* Copyright (c) 2007, Second Life Reverse Engineering Team
* 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.
* - Neither the name of the Second Life Reverse Engineering Team 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 libsecondlife.Packets;
namespace libsecondlife
{
/// <summary>
/// Throttles the network traffic for various different traffic types.
/// Access this class through SecondLife.Throttle
/// </summary>
public class AgentThrottle
{
/// <summary>Maximum bytes per second for resending unacknowledged packets</summary>
public float Resend
{
get { return resend; }
set
{
if (value > 150000.0f) resend = 150000.0f;
else if (value < 10000.0f) resend = 10000.0f;
else resend = value;
}
}
/// <summary>Maximum bytes per second for LayerData terrain</summary>
public float Land
{
get { return land; }
set
{
if (value > 170000.0f) land = 170000.0f;
else if (value < 0.0f) land = 0.0f; // We don't have control of these so allow throttling to 0
else land = value;
}
}
/// <summary>Maximum bytes per second for LayerData wind data</summary>
public float Wind
{
get { return wind; }
set
{
if (value > 34000.0f) wind = 34000.0f;
else if (value < 0.0f) wind = 0.0f; // We don't have control of these so allow throttling to 0
else wind = value;
}
}
/// <summary>Maximum bytes per second for LayerData clouds</summary>
public float Cloud
{
get { return cloud; }
set
{
if (value > 34000.0f) cloud = 34000.0f;
else if (value < 0.0f) cloud = 0.0f; // We don't have control of these so allow throttling to 0
else cloud = value;
}
}
/// <summary>Unknown, includes object data</summary>
public float Task
{
get { return task; }
set
{
if (value > 446000.0f) task = 446000.0f;
else if (value < 4000.0f) task = 4000.0f;
else task = value;
}
}
/// <summary>Maximum bytes per second for textures</summary>
public float Texture
{
get { return texture; }
set
{
if (value > 446000.0f) texture = 446000.0f;
else if (value < 4000.0f) texture = 4000.0f;
else texture = value;
}
}
/// <summary>Maximum bytes per second for downloaded assets</summary>
public float Asset
{
get { return asset; }
set
{
if (value > 220000.0f) asset = 220000.0f;
else if (value < 10000.0f) asset = 10000.0f;
else asset = value;
}
}
/// <summary>Maximum bytes per second the entire connection, divided up
/// between invidiual streams using default multipliers</summary>
public float Total
{
get { return Resend + Land + Wind + Cloud + Task + Texture + Asset; }
set
{
// These sane initial values were pulled from the Second Life client
Resend = (value * 0.1f);
Land = (float)(value * 0.52f / 3f);
Wind = (float)(value * 0.05f);
Cloud = (float)(value * 0.05f);
Task = (float)(value * 0.704f / 3f);
Texture = (float)(value * 0.704f / 3f);
Asset = (float)(value * 0.484f / 3f);
}
}
private SecondLife Client;
private float resend;
private float land;
private float wind;
private float cloud;
private float task;
private float texture;
private float asset;
/// <summary>
/// Default constructor, uses a default high total of 1500 KBps (1536000)
/// </summary>
public AgentThrottle(SecondLife client)
{
Client = client;
Total = 1536000.0f;
}
/// <summary>
/// Constructor that decodes an existing AgentThrottle packet in to
/// individual values
/// </summary>
/// <param name="data">Reference to the throttle data in an AgentThrottle
/// packet</param>
/// <param name="pos">Offset position to start reading at in the
/// throttle data</param>
/// <remarks>This is generally not needed in libsecondlife clients as
/// the server will never send a throttle packet to the client</remarks>
public AgentThrottle(byte[] data, int pos)
{
int i;
if (!BitConverter.IsLittleEndian)
for (i = 0; i < 7; i++)
Array.Reverse(data, pos + i * 4, 4);
Resend = BitConverter.ToSingle(data, pos); pos += 4;
Land = BitConverter.ToSingle(data, pos); pos += 4;
Wind = BitConverter.ToSingle(data, pos); pos += 4;
Cloud = BitConverter.ToSingle(data, pos); pos += 4;
Task = BitConverter.ToSingle(data, pos); pos += 4;
Texture = BitConverter.ToSingle(data, pos); pos += 4;
Asset = BitConverter.ToSingle(data, pos);
}
/// <summary>
/// Send an AgentThrottle packet to the current server using the
/// current values
/// </summary>
public void Set()
{
Set(Client.Network.CurrentSim);
}
/// <summary>
/// Send an AgentThrottle packet to the specified server using the
/// current values
/// </summary>
public void Set(Simulator simulator)
{
AgentThrottlePacket throttle = new AgentThrottlePacket();
throttle.AgentData.AgentID = Client.Self.AgentID;
throttle.AgentData.SessionID = Client.Self.SessionID;
throttle.AgentData.CircuitCode = Client.Network.CircuitCode;
throttle.Throttle.GenCounter = 0;
throttle.Throttle.Throttles = this.ToBytes();
Client.Network.SendPacket(throttle, simulator);
}
/// <summary>
/// Convert the current throttle values to a byte array that can be put
/// in an AgentThrottle packet
/// </summary>
/// <returns>Byte array containing all the throttle values</returns>
public byte[] ToBytes()
{
byte[] data = new byte[7 * 4];
int i = 0;
BitConverter.GetBytes(Resend).CopyTo(data, i); i += 4;
BitConverter.GetBytes(Land).CopyTo(data, i); i += 4;
BitConverter.GetBytes(Wind).CopyTo(data, i); i += 4;
BitConverter.GetBytes(Cloud).CopyTo(data, i); i += 4;
BitConverter.GetBytes(Task).CopyTo(data, i); i += 4;
BitConverter.GetBytes(Texture).CopyTo(data, i); i += 4;
BitConverter.GetBytes(Asset).CopyTo(data, i); i += 4;
if (!BitConverter.IsLittleEndian)
for (i = 0; i < 7; i++)
Array.Reverse(data, i * 4, 4);
return data;
}
}
}
| |
// 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Internal.Resources
{
using Management;
using Internal;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Azure.Internal.Subscriptions.Models;
/// <summary>
/// TagsOperations operations.
/// </summary>
internal partial class TagsOperations : IServiceOperations<ResourceManagementClient>, ITagsOperations
{
/// <summary>
/// Initializes a new instance of the TagsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal TagsOperations(ResourceManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ResourceManagementClient
/// </summary>
public ResourceManagementClient Client { get; private set; }
/// <summary>
/// Deletes a tag value.
/// </summary>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
/// <param name='tagValue'>
/// The value of the tag to delete.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteValueWithHttpMessagesAsync(string tagName, string tagValue, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (tagName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "tagName");
}
if (tagValue == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "tagValue");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (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("tagName", tagName);
tracingParameters.Add("tagValue", tagValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "DeleteValue", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue}").ToString();
_url = _url.Replace("{tagName}", System.Uri.EscapeDataString(tagName));
_url = _url.Replace("{tagValue}", System.Uri.EscapeDataString(tagValue));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates a tag value. The name of the tag must already exist.
/// </summary>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
/// <param name='tagValue'>
/// The value of the tag to create.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<TagValue>> CreateOrUpdateValueWithHttpMessagesAsync(string tagName, string tagValue, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (tagName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "tagName");
}
if (tagValue == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "tagValue");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (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("tagName", tagName);
tracingParameters.Add("tagValue", tagValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdateValue", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue}").ToString();
_url = _url.Replace("{tagName}", System.Uri.EscapeDataString(tagName));
_url = _url.Replace("{tagValue}", System.Uri.EscapeDataString(tagValue));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<TagValue>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<TagValue>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<TagValue>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates a tag in the subscription.
/// </summary>
/// <remarks>
/// The tag name can have a maximum of 512 characters and is case insensitive.
/// Tag names created by Azure have prefixes of microsoft, azure, or windows.
/// You cannot create tags with one of these prefixes.
/// </remarks>
/// <param name='tagName'>
/// The name of the tag to create.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<TagDetails>> CreateOrUpdateWithHttpMessagesAsync(string tagName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (tagName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "tagName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (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("tagName", tagName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/tagNames/{tagName}").ToString();
_url = _url.Replace("{tagName}", System.Uri.EscapeDataString(tagName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<TagDetails>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<TagDetails>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<TagDetails>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a tag from the subscription.
/// </summary>
/// <remarks>
/// You must remove all values from a resource tag before you can delete it.
/// </remarks>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string tagName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (tagName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "tagName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (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("tagName", tagName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/tagNames/{tagName}").ToString();
_url = _url.Replace("{tagName}", System.Uri.EscapeDataString(tagName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the names and values of all resource tags that are defined in a
/// subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<TagDetails>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (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 = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/tagNames").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<TagDetails>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<TagDetails>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the names and values of all resource tags that are defined in a
/// subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<TagDetails>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<TagDetails>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<TagDetails>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A placeholder for a binary blob
/// First published in XenServer 5.0.
/// </summary>
public partial class Blob : XenObject<Blob>
{
#region Constructors
public Blob()
{
}
public Blob(string uuid,
string name_label,
string name_description,
long size,
bool pubblic,
DateTime last_updated,
string mime_type)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.size = size;
this.pubblic = pubblic;
this.last_updated = last_updated;
this.mime_type = mime_type;
}
/// <summary>
/// Creates a new Blob from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Blob(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Blob from a Proxy_Blob.
/// </summary>
/// <param name="proxy"></param>
public Blob(Proxy_Blob proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Blob.
/// </summary>
public override void UpdateFrom(Blob record)
{
uuid = record.uuid;
name_label = record.name_label;
name_description = record.name_description;
size = record.size;
pubblic = record.pubblic;
last_updated = record.last_updated;
mime_type = record.mime_type;
}
internal void UpdateFrom(Proxy_Blob proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
size = proxy.size == null ? 0 : long.Parse(proxy.size);
pubblic = (bool)proxy.pubblic;
last_updated = proxy.last_updated;
mime_type = proxy.mime_type == null ? null : proxy.mime_type;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Blob
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("size"))
size = Marshalling.ParseLong(table, "size");
if (table.ContainsKey("pubblic"))
pubblic = Marshalling.ParseBool(table, "pubblic");
if (table.ContainsKey("last_updated"))
last_updated = Marshalling.ParseDateTime(table, "last_updated");
if (table.ContainsKey("mime_type"))
mime_type = Marshalling.ParseString(table, "mime_type");
}
public Proxy_Blob ToProxy()
{
Proxy_Blob result_ = new Proxy_Blob();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.size = size.ToString();
result_.pubblic = pubblic;
result_.last_updated = last_updated;
result_.mime_type = mime_type ?? "";
return result_;
}
public bool DeepEquals(Blob other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._pubblic, other._pubblic) &&
Helper.AreEqual2(this._last_updated, other._last_updated) &&
Helper.AreEqual2(this._mime_type, other._mime_type);
}
public override string SaveChanges(Session session, string opaqueRef, Blob server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
Blob.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
Blob.set_name_description(session, opaqueRef, _name_description);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static Blob get_record(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_record(session.opaque_ref, _blob);
else
return new Blob(session.XmlRpcProxy.blob_get_record(session.opaque_ref, _blob ?? "").parse());
}
/// <summary>
/// Get a reference to the blob instance with the specified UUID.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Blob> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.blob_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the blob instances with the given label.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Blob>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.blob_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static string get_uuid(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_uuid(session.opaque_ref, _blob);
else
return session.XmlRpcProxy.blob_get_uuid(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static string get_name_label(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_name_label(session.opaque_ref, _blob);
else
return session.XmlRpcProxy.blob_get_name_label(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static string get_name_description(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_name_description(session.opaque_ref, _blob);
else
return session.XmlRpcProxy.blob_get_name_description(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the size field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static long get_size(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_size(session.opaque_ref, _blob);
else
return long.Parse(session.XmlRpcProxy.blob_get_size(session.opaque_ref, _blob ?? "").parse());
}
/// <summary>
/// Get the public field of the given blob.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static bool get_public(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_public(session.opaque_ref, _blob);
else
return (bool)session.XmlRpcProxy.blob_get_public(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the last_updated field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static DateTime get_last_updated(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_last_updated(session.opaque_ref, _blob);
else
return session.XmlRpcProxy.blob_get_last_updated(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the mime_type field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static string get_mime_type(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_mime_type(session.opaque_ref, _blob);
else
return session.XmlRpcProxy.blob_get_mime_type(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Set the name/label field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _blob, string _label)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.blob_set_name_label(session.opaque_ref, _blob, _label);
else
session.XmlRpcProxy.blob_set_name_label(session.opaque_ref, _blob ?? "", _label ?? "").parse();
}
/// <summary>
/// Set the name/description field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _blob, string _description)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.blob_set_name_description(session.opaque_ref, _blob, _description);
else
session.XmlRpcProxy.blob_set_name_description(session.opaque_ref, _blob ?? "", _description ?? "").parse();
}
/// <summary>
/// Set the public field of the given blob.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
/// <param name="_public">New value to set</param>
public static void set_public(Session session, string _blob, bool _public)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.blob_set_public(session.opaque_ref, _blob, _public);
else
session.XmlRpcProxy.blob_set_public(session.opaque_ref, _blob ?? "", _public).parse();
}
/// <summary>
/// Create a placeholder for a binary blob
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_mime_type">The mime-type of the blob. Defaults to 'application/octet-stream' if the empty string is supplied</param>
public static XenRef<Blob> create(Session session, string _mime_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_create(session.opaque_ref, _mime_type);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.blob_create(session.opaque_ref, _mime_type ?? "").parse());
}
/// <summary>
/// Create a placeholder for a binary blob
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_mime_type">The mime-type of the blob. Defaults to 'application/octet-stream' if the empty string is supplied</param>
/// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param>
public static XenRef<Blob> create(Session session, string _mime_type, bool _public)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_create(session.opaque_ref, _mime_type, _public);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.blob_create(session.opaque_ref, _mime_type ?? "", _public).parse());
}
/// <summary>
///
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static void destroy(Session session, string _blob)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.blob_destroy(session.opaque_ref, _blob);
else
session.XmlRpcProxy.blob_destroy(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Return a list of all the blobs known to the system.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Blob>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_all(session.opaque_ref);
else
return XenRef<Blob>.Create(session.XmlRpcProxy.blob_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the blob Records at once, in a single XML RPC call
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Blob>, Blob> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_all_records(session.opaque_ref);
else
return XenRef<Blob>.Create<Proxy_Blob>(session.XmlRpcProxy.blob_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Size of the binary data, in bytes
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
NotifyPropertyChanged("size");
}
}
}
private long _size;
/// <summary>
/// True if the blob is publicly accessible
/// First published in XenServer 6.1.
/// </summary>
public virtual bool pubblic
{
get { return _pubblic; }
set
{
if (!Helper.AreEqual(value, _pubblic))
{
_pubblic = value;
NotifyPropertyChanged("pubblic");
}
}
}
private bool _pubblic = false;
/// <summary>
/// Time at which the data in the blob was last updated
/// </summary>
[JsonConverter(typeof(XenDateTimeConverter))]
public virtual DateTime last_updated
{
get { return _last_updated; }
set
{
if (!Helper.AreEqual(value, _last_updated))
{
_last_updated = value;
NotifyPropertyChanged("last_updated");
}
}
}
private DateTime _last_updated;
/// <summary>
/// The mime type associated with this object. Defaults to 'application/octet-stream' if the empty string is supplied
/// </summary>
public virtual string mime_type
{
get { return _mime_type; }
set
{
if (!Helper.AreEqual(value, _mime_type))
{
_mime_type = value;
NotifyPropertyChanged("mime_type");
}
}
}
private string _mime_type = "";
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyInteger
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// IntModel operations.
/// </summary>
public partial interface IIntModel
{
/// <summary>
/// Get null Int value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<int?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get invalid Int value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<int?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get overflow Int32 value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<int?>> GetOverflowInt32WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get underflow Int32 value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<int?>> GetUnderflowInt32WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get overflow Int64 value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<long?>> GetOverflowInt64WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get underflow Int64 value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<long?>> GetUnderflowInt64WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put max int32 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> PutMax32WithHttpMessagesAsync(int intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put max int64 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> PutMax64WithHttpMessagesAsync(long intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put min int32 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> PutMin32WithHttpMessagesAsync(int intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put min int64 value
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> PutMin64WithHttpMessagesAsync(long intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get datetime encoded as Unix time value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<DateTime?>> GetUnixTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put datetime encoded as Unix time
/// </summary>
/// <param name='intBody'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> PutUnixTimeDateWithHttpMessagesAsync(DateTime intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get invalid Unix time value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<DateTime?>> GetInvalidUnixTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get null Unix time value
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<DateTime?>> GetNullUnixTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// 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.Xml.Schema;
using Xunit;
using Xunit.Abstractions;
namespace System.Xml.Tests
{
// ===================== ValidateText =====================
public class TCValidateText : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
private ExceptionVerifier _exVerifier;
public TCValidateText(ITestOutputHelper output): base(output)
{
_output = output;
_exVerifier = new ExceptionVerifier("System.Xml", _output);
}
[Fact]
public void PassNull()
{
XmlSchemaValidator val = CreateValidator(new XmlSchemaSet());
val.Initialize();
try
{
val.ValidateText((XmlValueGetter)null);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
[Fact]
public void TopLevelText()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
CValidationEventHolder holder = new CValidationEventHolder();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateText(StringGetter("foo"));
val.EndValidation();
Assert.True(!holder.IsCalledA);
return;
}
[Theory]
[InlineData("single")]
[InlineData("multiple")]
public void SanityTestForSimpleType_MultipleCallInOneContext(string param)
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
CValidationEventHolder holder = new CValidationEventHolder();
XmlSchemaInfo info = new XmlSchemaInfo();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("PatternElement", "", info);
val.ValidateEndOfAttributes(null);
if (param == "single")
val.ValidateText(StringGetter("foo123bar"));
else
{
val.ValidateText(StringGetter("foo"));
val.ValidateText(StringGetter("123"));
val.ValidateText(StringGetter("bar"));
}
val.ValidateEndElement(info);
val.EndValidation();
Assert.True(!holder.IsCalledA);
Assert.Equal(XmlSchemaValidity.Valid, info.Validity);
Assert.Equal(XmlSchemaContentType.TextOnly, info.ContentType);
return;
}
[Fact]
public void MixedContent()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
CValidationEventHolder holder = new CValidationEventHolder();
XmlSchemaInfo info = new XmlSchemaInfo();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("MixedElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateText(StringGetter("some text"));
val.ValidateElement("child", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
val.ValidateText(StringGetter("some other text"));
val.ValidateEndElement(info);
val.EndValidation();
Assert.True(!holder.IsCalledA);
Assert.Equal(XmlSchemaValidity.Valid, info.Validity);
Assert.Equal(XmlSchemaContentType.Mixed, info.ContentType);
return;
}
[Fact]
public void ElementOnlyContent()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("ElementOnlyElement", "", info);
val.ValidateEndOfAttributes(null);
try
{
val.ValidateText(StringGetter("some text"));
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, new object[] { "Sch_InvalidTextInElementExpecting",
new object[] { "Sch_ElementName", "ElementOnlyElement" },
new object[] { "Sch_ElementName", "child" } });
return;
}
Assert.True(false);
}
[Fact]
public void EmptyContent()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("EmptyElement", "", info);
val.ValidateEndOfAttributes(null);
try
{
val.ValidateText(StringGetter("some text"));
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_InvalidTextInEmpty");
return;
}
Assert.True(false);
}
}
// ===================== ValidateWhitespace =====================
public class TCValidateWhitespace : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
private ExceptionVerifier _exVerifier;
public TCValidateWhitespace(ITestOutputHelper output): base(output)
{
_output = output;
_exVerifier = new ExceptionVerifier("System.Xml", _output);
}
[Fact]
public void PassNull()
{
XmlSchemaValidator val = CreateValidator(new XmlSchemaSet());
val.Initialize();
try
{
val.ValidateWhitespace((XmlValueGetter)null);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
[Fact]
public void TopLevelWhitespace()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
CValidationEventHolder holder = new CValidationEventHolder();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateWhitespace(StringGetter(" \t" + Environment.NewLine));
val.EndValidation();
Assert.True(!holder.IsCalledA);
return;
}
[Fact]
public void WhitespaceInsideElement_Single()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
CValidationEventHolder holder = new CValidationEventHolder();
XmlSchemaInfo info = new XmlSchemaInfo();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("ElementOnlyElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateWhitespace(StringGetter(" \t"+ Environment.NewLine));
val.ValidateElement("child", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
val.ValidateWhitespace(StringGetter(" \t" + Environment.NewLine));
val.ValidateEndElement(info);
val.EndValidation();
Assert.True(!holder.IsCalledA);
Assert.Equal(XmlSchemaValidity.Valid, info.Validity);
Assert.Equal(XmlSchemaContentType.ElementOnly, info.ContentType);
return;
}
[Fact]
public void WhitespaceInEmptyContent__Invalid()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("EmptyElement", "", info);
val.ValidateEndOfAttributes(null);
try
{
val.ValidateWhitespace(StringGetter(" " + Environment.NewLine + "\t"));
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_InvalidWhitespaceInEmpty");
return;
}
Assert.True(false);
}
[Fact]
public void PassNonWhitespaceContent()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_TEXT);
val.Initialize();
val.ValidateElement("ElementOnlyElement", "", null);
val.ValidateEndOfAttributes(null);
try
{
val.ValidateWhitespace(StringGetter("this is not whitespace"));
}
catch (Exception) // Replace with concrete exception type
{
// Verify exception ????
Assert.True(false);
}
return;
}
}
// ===================== ValidateEndElement =====================
public class TCValidateEndElement : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
private ExceptionVerifier _exVerifier;
public TCValidateEndElement(ITestOutputHelper output): base(output)
{
_output = output;
_exVerifier = new ExceptionVerifier("System.Xml", _output);
}
[Fact]
public void PassNull()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("BasicElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(null);
return;
}
// BUG 305258
[Fact]
public void SanityTestForComplexTypes()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("ComplexElement", "", info);
val.ValidateEndOfAttributes(null);
foreach (string name in new string[] { "e1", "e2", "e2", "e3" })
{
val.ValidateElement(name, "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
Assert.Equal(XmlSchemaValidity.Valid, info.Validity);
Assert.Equal(XmlSchemaContentType.TextOnly, info.ContentType);
}
val.ValidateEndElement(info);
Assert.Equal(XmlSchemaValidity.Valid, info.Validity);
Assert.Equal(XmlSchemaContentType.ElementOnly, info.ContentType);
val.EndValidation();
return;
}
[Fact]
public void IncompleteContet__Valid()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("ComplexElement", "", info);
val.ValidateEndOfAttributes(null);
foreach (string name in new string[] { "e1", "e2", "e2" })
{
val.ValidateElement(name, "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
}
val.ValidateEndElement(info);
Assert.Equal(XmlSchemaValidity.Valid, info.Validity);
Assert.Equal(XmlSchemaContentType.ElementOnly, info.ContentType);
val.EndValidation();
return;
}
[Fact]
public void IncompleteContent__Invalid()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
CValidationEventHolder holder = new CValidationEventHolder();
val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA);
val.Initialize();
val.ValidateElement("ComplexElement", "", info);
val.ValidateEndOfAttributes(null);
foreach (string name in new string[] { "e1", "e2" })
{
val.ValidateElement(name, "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
}
val.ValidateEndElement(info);
Assert.True(holder.IsCalledA);
Assert.Equal(XmlSeverityType.Error, holder.lastSeverity);
Assert.Equal(XmlSchemaValidity.Invalid, info.Validity);
return;
}
[Fact]
public void TextNodeWithoutValidateTextCall()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("BasicElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
val.EndValidation();
Assert.Equal(XmlSchemaValidity.Valid, info.Validity);
Assert.Equal(XmlSchemaContentType.TextOnly, info.ContentType);
return;
}
// 2nd overload
[Fact]
public void Typed_NullXmlSchemaInfo()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("NumberElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(null, "123");
return;
}
[Fact]
public void Typed_NullTypedValue()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("NumberElement", "", info);
val.ValidateEndOfAttributes(null);
try
{
val.ValidateEndElement(info, null);
}
catch (ArgumentNullException)
{
return;
}
Assert.True(false);
}
[Fact]
public void CallValidateTextThenValidateEndElementWithTypedValue()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("NumberElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateText(StringGetter("1"));
try
{
val.ValidateEndElement(info, "23");
}
catch (InvalidOperationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_InvalidEndElementCall");
return;
}
Assert.True(false);
}
[Fact]
public void CheckSchemaInfoAfterCallingValidateEndElementWithTypedValue()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("NumberElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info, "123");
val.EndValidation();
Assert.Equal(XmlSchemaValidity.Valid, info.Validity);
Assert.Equal(XmlSchemaContentType.TextOnly, info.ContentType);
Assert.False(info.IsDefault);
Assert.False(info.IsNil);
Assert.Equal(XmlTypeCode.Int, info.SchemaType.TypeCode);
return;
}
//bug #305258
[Fact]
public void SanityTestForEmptyTypes()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("EmptyElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
Assert.Equal(XmlSchemaValidity.Valid, info.Validity);
Assert.Equal(XmlSchemaContentType.Empty, info.ContentType);
val.EndValidation();
return;
}
[Theory]
[InlineData("valid")]
[InlineData("duplicate")]
[InlineData("missing")]
[InlineData("ignore")]
public void TestForIdentityConstraints_Valid_InvalidDuplicateKey_InvalidKeyRefMissing_InvalidIdentitiConstraintIsSet(string constrType)
{
XmlSchemaValidator val;
XmlSchemaInfo info = new XmlSchemaInfo();
string[] keys = new string[] { };
string[] keyrefs = new string[] { };
bool secondPass;
switch (constrType)
{
case "valid":
keys = new string[] { "1", "2" };
keyrefs = new string[] { "1", "1", "2" };
break;
case "duplicate":
keys = new string[] { "1", "1" };
keyrefs = new string[] { "1", "1", "2" };
break;
case "missing":
keys = new string[] { "1", "2" };
keyrefs = new string[] { "1", "1", "3" };
break;
case "ignore":
keys = new string[] { "1", "1" };
keyrefs = new string[] { "2", "2" };
break;
default:
Assert.True(false);
break;
}
if (constrType == "ignore")
val = CreateValidator(XSDFILE_IDENTITY_CONSTRAINS, "", XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessInlineSchema);
else
val = CreateValidator(XSDFILE_IDENTITY_CONSTRAINS);
val.Initialize();
val.ValidateElement("root", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateElement("desc", "", info);
val.ValidateEndOfAttributes(null);
foreach (string str in keyrefs)
{
val.ValidateElement("elemDesc", "", info);
val.ValidateAttribute("number", "", StringGetter(str), info);
val.ValidateEndOfAttributes(null);
val.ValidateText(StringGetter("foo"));
val.ValidateEndElement(info);
}
val.ValidateEndElement(info);
secondPass = false;
foreach (string str in keys)
{
val.ValidateElement("elem", "", info);
val.ValidateAttribute("number", "", StringGetter(str), info);
val.ValidateEndOfAttributes(null);
val.ValidateElement("bar", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
if (constrType == "duplicate" && secondPass)
{
try
{
val.ValidateEndElement(info);
Assert.True(false);
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_DuplicateKey", new string[] { "1", "numberKey" });
return;
}
}
else
val.ValidateEndElement(info);
secondPass = true;
}
if (constrType == "missing")
{
try
{
val.ValidateEndElement(info);
Assert.True(false);
}
catch (XmlSchemaValidationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_UnresolvedKeyref", new string[] { "3", "numberKey" });
return;
}
}
else
{
val.ValidateEndElement(info);
val.EndValidation();
}
return;
}
//Bug #305376
[Fact]
public void AllXmlSchemaInfoArgsCanBeNull()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
val.Initialize();
val.ValidateElement("WithAttributesElement", "", null);
val.ValidateAttribute("attr1", "", StringGetter("foo"), null);
val.ValidateAttribute("attr2", "", StringGetter("foo"), null);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(null);
val.ValidateElement("foo", "", null, "EmptyType", null, null, null);
val.SkipToEndElement(null);
val.ValidateElement("NumberElement", "", null);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(null, "123");
return;
}
[Theory]
[InlineData("first")]
[InlineData("second")] //(BUG #307549)
public void TestXmlSchemaInfoValuesAfterUnionValidation_Without_With_ValidationEndElementOverload(string overload)
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("UnionElement", "", null);
val.ValidateEndOfAttributes(null);
if (overload == "first")
{
val.ValidateText(StringGetter("false"));
val.ValidateEndElement(info);
}
else
val.ValidateEndElement(info, "false");
Assert.Equal(XmlTypeCode.Boolean, info.MemberType.TypeCode);
return;
}
//BUG #308578
[Fact]
public void CallValidateEndElementWithTypedValueForComplexContent()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("ComplexElement", "", info);
val.ValidateEndOfAttributes(null);
foreach (string name in new string[] { "e1", "e2", "e2" })
{
val.ValidateElement(name, "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
}
try
{
val.ValidateEndElement(info, "23");
}
catch (InvalidOperationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_InvalidEndElementCallTyped");
return;
}
Assert.True(false);
}
}
// ===================== SkipToEndElement =====================
public class TCSkipToEndElement : CXmlSchemaValidatorTestCase
{
private ITestOutputHelper _output;
private ExceptionVerifier _exVerifier;
public TCSkipToEndElement(ITestOutputHelper output): base(output)
{
_output = output;
_exVerifier = new ExceptionVerifier("System.Xml", _output);
}
[Fact]
public void PassNull()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("BasicElement", "", info);
val.ValidateEndOfAttributes(null);
val.SkipToEndElement(null);
return;
}
//bug #306869
[Theory]
[InlineData("valid")]
[InlineData("invalid")]
public void SkipAfterValidating_ValidContent_IncompleteContent(string validity)
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
bool valid = (validity == "valid");
val.Initialize();
val.ValidateElement("ComplexElement", "", info);
val.ValidateEndOfAttributes(null);
string[] tmp;
if (valid) tmp = new string[] { "e1", "e2", "e2" };
else tmp = new string[] { "e1", "e2" };
foreach (string name in tmp)
{
val.ValidateElement(name, "", info);
val.ValidateEndOfAttributes(null);
val.ValidateEndElement(info);
}
val.SkipToEndElement(info);
val.EndValidation();
Assert.Equal(XmlSchemaValidity.NotKnown, info.Validity);
return;
}
//bug #306869
[Fact]
public void ValidateTextAndSkip()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("BasicElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateText(StringGetter("foo"));
val.SkipToEndElement(info);
Assert.Equal(XmlSchemaValidity.NotKnown, info.Validity);
return;
}
//bug #306869
[Fact]
public void ValidateAttributesAndSkip()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("WithAttributesElement", "", info);
val.ValidateAttribute("attr1", "", StringGetter("foo"), info);
val.SkipToEndElement(info);
Assert.Equal(XmlSchemaValidity.NotKnown, info.Validity);
return;
}
[Fact]
public void CheckThatSkipToEndElementJumpsIntoRightContext()
{
XmlSchemaValidator val = CreateValidator(XSDFILE_VALIDATE_END_ELEMENT);
XmlSchemaInfo info = new XmlSchemaInfo();
val.Initialize();
val.ValidateElement("NestedElement", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateElement("foo", "", info);
val.ValidateEndOfAttributes(null);
val.ValidateElement("bar", "", info);
val.ValidateEndOfAttributes(null);
val.SkipToEndElement(info);
val.SkipToEndElement(info);
val.SkipToEndElement(info);
try
{
val.SkipToEndElement(info);
}
catch (InvalidOperationException e)
{
_exVerifier.IsExceptionOk(e, "Sch_InvalidEndElementMultiple", new string[] { "SkipToEndElement" });
return;
}
Assert.True(false);
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
//TODO: We've alraedy moved most of this logic to Core.Strings - need to review this as it has slightly more functionality but should be moved to core and obsoleted!
namespace umbraco.cms.businesslogic.utilities {
/// <summary>
/// This Class implements the Difference Algorithm published in
/// "An O(ND) Difference Algorithm and its Variations" by Eugene Myers
/// Algorithmica Vol. 1 No. 2, 1986, p 251.
///
/// There are many C, Java, Lisp implementations public available but they all seem to come
/// from the same source (diffutils) that is under the (unfree) GNU public License
/// and cannot be reused as a sourcecode for a commercial application.
/// There are very old C implementations that use other (worse) algorithms.
/// Microsoft also published sourcecode of a diff-tool (windiff) that uses some tree data.
/// Also, a direct transfer from a C source to C# is not easy because there is a lot of pointer
/// arithmetic in the typical C solutions and i need a managed solution.
/// These are the reasons why I implemented the original published algorithm from the scratch and
/// make it avaliable without the GNU license limitations.
/// I do not need a high performance diff tool because it is used only sometimes.
/// I will do some performace tweaking when needed.
///
/// The algorithm itself is comparing 2 arrays of numbers so when comparing 2 text documents
/// each line is converted into a (hash) number. See DiffText().
///
/// Some chages to the original algorithm:
/// The original algorithm was described using a recursive approach and comparing zero indexed arrays.
/// Extracting sub-arrays and rejoining them is very performance and memory intensive so the same
/// (readonly) data arrays are passed arround together with their lower and upper bounds.
/// This circumstance makes the LCS and SMS functions more complicate.
/// I added some code to the LCS function to get a fast response on sub-arrays that are identical,
/// completely deleted or inserted.
///
/// The result from a comparisation is stored in 2 arrays that flag for modified (deleted or inserted)
/// lines in the 2 data arrays. These bits are then analysed to produce a array of Item objects.
///
/// Further possible optimizations:
/// (first rule: don't do it; second: don't do it yet)
/// The arrays DataA and DataB are passed as parameters, but are never changed after the creation
/// so they can be members of the class to avoid the paramter overhead.
/// In SMS is a lot of boundary arithmetic in the for-D and for-k loops that can be done by increment
/// and decrement of local variables.
/// The DownVector and UpVector arrays are alywas created and destroyed each time the SMS gets called.
/// It is possible to reuse tehm when transfering them to members of the class.
/// See TODO: hints.
///
/// diff.cs: A port of the algorythm to C#
/// Copyright (c) by Matthias Hertel, http://www.mathertel.de
/// This work is licensed under a BSD style license. See http://www.mathertel.de/License.aspx
///
/// Changes:
/// 2002.09.20 There was a "hang" in some situations.
/// Now I undestand a little bit more of the SMS algorithm.
/// There have been overlapping boxes; that where analyzed partial differently.
/// One return-point is enough.
/// A assertion was added in CreateDiffs when in debug-mode, that counts the number of equal (no modified) lines in both arrays.
/// They must be identical.
///
/// 2003.02.07 Out of bounds error in the Up/Down vector arrays in some situations.
/// The two vetors are now accessed using different offsets that are adjusted using the start k-Line.
/// A test case is added.
///
/// 2006.03.05 Some documentation and a direct Diff entry point.
///
/// 2006.03.08 Refactored the API to static methods on the Diff class to make usage simpler.
/// 2006.03.10 using the standard Debug class for self-test now.
/// compile with: csc /target:exe /out:diffTest.exe /d:DEBUG /d:TRACE /d:SELFTEST Diff.cs
/// 2007.01.06 license agreement changed to a BSD style license.
/// 2007.06.03 added the Optimize method.
/// 2007.09.23 UpVector and DownVector optimization by Jan Stoklasa ().
/// </summary>
public class Diff {
/// <summary>details of one difference.</summary>
public struct Item {
/// <summary>Start Line number in Data A.</summary>
public int StartA;
/// <summary>Start Line number in Data B.</summary>
public int StartB;
/// <summary>Number of changes in Data A.</summary>
public int deletedA;
/// <summary>Number of changes in Data B.</summary>
public int insertedB;
} // Item
/// <summary>
/// Shortest Middle Snake Return Data
/// </summary>
private struct SMSRD {
internal int x, y;
// internal int u, v; // 2002.09.20: no need for 2 points
}
#region self-Test
#if (SELFTEST)
/// <summary>
/// start a self- / box-test for some diff cases and report to the debug output.
/// </summary>
/// <param name="args">not used</param>
/// <returns>always 0</returns>
public static int Main(string[] args) {
StringBuilder ret = new StringBuilder();
string a, b;
System.Diagnostics.ConsoleTraceListener ctl = new System.Diagnostics.ConsoleTraceListener(false);
System.Diagnostics.Debug.Listeners.Add(ctl);
System.Console.WriteLine("Diff Self Test...");
// test all changes
a = "a,b,c,d,e,f,g,h,i,j,k,l".Replace(',', '\n');
b = "0,1,2,3,4,5,6,7,8,9".Replace(',', '\n');
System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
== "12.10.0.0*",
"all-changes test failed.");
System.Diagnostics.Debug.WriteLine("all-changes test passed.");
// test all same
a = "a,b,c,d,e,f,g,h,i,j,k,l".Replace(',', '\n');
b = a;
System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
== "",
"all-same test failed.");
System.Diagnostics.Debug.WriteLine("all-same test passed.");
// test snake
a = "a,b,c,d,e,f".Replace(',', '\n');
b = "b,c,d,e,f,x".Replace(',', '\n');
System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
== "1.0.0.0*0.1.6.5*",
"snake test failed.");
System.Diagnostics.Debug.WriteLine("snake test passed.");
// 2002.09.20 - repro
a = "c1,a,c2,b,c,d,e,g,h,i,j,c3,k,l".Replace(',', '\n');
b = "C1,a,C2,b,c,d,e,I1,e,g,h,i,j,C3,k,I2,l".Replace(',', '\n');
System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
== "1.1.0.0*1.1.2.2*0.2.7.7*1.1.11.13*0.1.13.15*",
"repro20020920 test failed.");
System.Diagnostics.Debug.WriteLine("repro20020920 test passed.");
// 2003.02.07 - repro
a = "F".Replace(',', '\n');
b = "0,F,1,2,3,4,5,6,7".Replace(',', '\n');
System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
== "0.1.0.0*0.7.1.2*",
"repro20030207 test failed.");
System.Diagnostics.Debug.WriteLine("repro20030207 test passed.");
// Muegel - repro
a = "HELLO\nWORLD";
b = "\n\nhello\n\n\n\nworld\n";
System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
== "2.8.0.0*",
"repro20030409 test failed.");
System.Diagnostics.Debug.WriteLine("repro20030409 test passed.");
// test some differences
a = "a,b,-,c,d,e,f,f".Replace(',', '\n');
b = "a,b,x,c,e,f".Replace(',', '\n');
System.Diagnostics.Debug.Assert(TestHelper(Diff.DiffText(a, b, false, false, false))
== "1.1.2.2*1.0.4.4*1.0.6.5*",
"some-changes test failed.");
System.Diagnostics.Debug.WriteLine("some-changes test passed.");
System.Diagnostics.Debug.WriteLine("End.");
System.Diagnostics.Debug.Flush();
return (0);
}
public static string TestHelper(Item []f) {
StringBuilder ret = new StringBuilder();
for (int n = 0; n < f.Length; n++) {
ret.Append(f[n].deletedA.ToString() + "." + f[n].insertedB.ToString() + "." + f[n].StartA.ToString() + "." + f[n].StartB.ToString() + "*");
}
// Debug.Write(5, "TestHelper", ret.ToString());
return (ret.ToString());
}
#endif
#endregion
/// <summary>
/// Find the difference in 2 texts, comparing by textlines, returns the result as Html.
/// If content has been removed, it will be marked up with a <del> html element.
/// If content has been added, it will be marked up with a <ins> html element
/// </summary>
/// <param name="a_line">The old version of the string.</param>
/// <param name="b_line">The new version of the string.</param>
/// <returns></returns>
public static string Diff2Html(string a_line, string b_line) {
int[] a_codes = DiffCharCodes(a_line, false);
int[] b_codes = DiffCharCodes(b_line, false);
string result = "";
Diff.Item[] diffs = Diff.DiffInt(a_codes, b_codes);
int pos = 0;
for (int n = 0; n < diffs.Length; n++) {
Diff.Item it = diffs[n];
// write unchanged chars
while ((pos < it.StartB) && (pos < b_line.Length)) {
result += b_line[pos];
pos++;
} // while
// write deleted chars
if (it.deletedA > 0) {
result += "<del>";
for (int m = 0; m < it.deletedA; m++) {
result += a_line[it.StartA + m];
} // for
result += "</del>";
}
// write inserted chars
if (pos < it.StartB + it.insertedB) {
result += "<ins>";
while (pos < it.StartB + it.insertedB) {
result += b_line[pos];
pos++;
} // while
result += "</ins>";
} // if
} // while
// write rest of unchanged chars
while (pos < b_line.Length) {
result += b_line[pos];
pos++;
}
return result;
}
private static int[] DiffCharCodes(string aText, bool ignoreCase) {
int[] Codes;
if (ignoreCase)
aText = aText.ToUpperInvariant();
Codes = new int[aText.Length];
for (int n = 0; n < aText.Length; n++)
Codes[n] = (int)aText[n];
return (Codes);
}
/// <summary>
/// Find the difference in 2 texts, comparing by textlines.
/// </summary>
/// <param name="TextA">A-version of the text (usualy the old one)</param>
/// <param name="TextB">B-version of the text (usualy the new one)</param>
/// <returns>Returns a array of Items that describe the differences.</returns>
public Item[] DiffText(string TextA, string TextB) {
return (DiffText(TextA, TextB, false, false, false));
} // DiffText
/// <summary>
/// Find the difference in 2 text documents, comparing by textlines.
/// The algorithm itself is comparing 2 arrays of numbers so when comparing 2 text documents
/// each line is converted into a (hash) number. This hash-value is computed by storing all
/// textlines into a common hashtable so i can find dublicates in there, and generating a
/// new number each time a new textline is inserted.
/// </summary>
/// <param name="TextA">A-version of the text (usualy the old one)</param>
/// <param name="TextB">B-version of the text (usualy the new one)</param>
/// <param name="trimSpace">When set to true, all leading and trailing whitespace characters are stripped out before the comparation is done.</param>
/// <param name="ignoreSpace">When set to true, all whitespace characters are converted to a single space character before the comparation is done.</param>
/// <param name="ignoreCase">When set to true, all characters are converted to their lowercase equivivalence before the comparation is done.</param>
/// <returns>Returns a array of Items that describe the differences.</returns>
public static Item[] DiffText(string TextA, string TextB, bool trimSpace, bool ignoreSpace, bool ignoreCase) {
// prepare the input-text and convert to comparable numbers.
Hashtable h = new Hashtable(TextA.Length + TextB.Length);
// The A-Version of the data (original data) to be compared.
DiffData DataA = new DiffData(DiffCodes(TextA, h, trimSpace, ignoreSpace, ignoreCase));
// The B-Version of the data (modified data) to be compared.
DiffData DataB = new DiffData(DiffCodes(TextB, h, trimSpace, ignoreSpace, ignoreCase));
h = null; // free up hashtable memory (maybe)
int MAX = DataA.Length + DataB.Length + 1;
/// vector for the (0,0) to (x,y) search
int[] DownVector = new int[2 * MAX + 2];
/// vector for the (u,v) to (N,M) search
int[] UpVector = new int[2 * MAX + 2];
LCS(DataA, 0, DataA.Length, DataB, 0, DataB.Length, DownVector, UpVector);
Optimize(DataA);
Optimize(DataB);
return CreateDiffs(DataA, DataB);
} // DiffText
/// <summary>
/// If a sequence of modified lines starts with a line that contains the same content
/// as the line that appends the changes, the difference sequence is modified so that the
/// appended line and not the starting line is marked as modified.
/// This leads to more readable diff sequences when comparing text files.
/// </summary>
/// <param name="Data">A Diff data buffer containing the identified changes.</param>
private static void Optimize(DiffData Data) {
int StartPos, EndPos;
StartPos = 0;
while (StartPos < Data.Length) {
while ((StartPos < Data.Length) && (Data.modified[StartPos] == false))
StartPos++;
EndPos = StartPos;
while ((EndPos < Data.Length) && (Data.modified[EndPos] == true))
EndPos++;
if ((EndPos < Data.Length) && (Data.data[StartPos] == Data.data[EndPos])) {
Data.modified[StartPos] = false;
Data.modified[EndPos] = true;
} else {
StartPos = EndPos;
} // if
} // while
} // Optimize
/// <summary>
/// Find the difference in 2 arrays of integers.
/// </summary>
/// <param name="ArrayA">A-version of the numbers (usualy the old one)</param>
/// <param name="ArrayB">B-version of the numbers (usualy the new one)</param>
/// <returns>Returns a array of Items that describe the differences.</returns>
public static Item[] DiffInt(int[] ArrayA, int[] ArrayB) {
// The A-Version of the data (original data) to be compared.
DiffData DataA = new DiffData(ArrayA);
// The B-Version of the data (modified data) to be compared.
DiffData DataB = new DiffData(ArrayB);
int MAX = DataA.Length + DataB.Length + 1;
/// vector for the (0,0) to (x,y) search
int[] DownVector = new int[2 * MAX + 2];
/// vector for the (u,v) to (N,M) search
int[] UpVector = new int[2 * MAX + 2];
LCS(DataA, 0, DataA.Length, DataB, 0, DataB.Length, DownVector, UpVector);
return CreateDiffs(DataA, DataB);
} // Diff
/// <summary>
/// This function converts all textlines of the text into unique numbers for every unique textline
/// so further work can work only with simple numbers.
/// </summary>
/// <param name="aText">the input text</param>
/// <param name="h">This extern initialized hashtable is used for storing all ever used textlines.</param>
/// <param name="trimSpace">ignore leading and trailing space characters</param>
/// <returns>a array of integers.</returns>
private static int[] DiffCodes(string aText, Hashtable h, bool trimSpace, bool ignoreSpace, bool ignoreCase) {
// get all codes of the text
string[] Lines;
int[] Codes;
int lastUsedCode = h.Count;
object aCode;
string s;
// strip off all cr, only use lf as textline separator.
aText = aText.Replace("\r", "");
Lines = aText.Split('\n');
Codes = new int[Lines.Length];
for (int i = 0; i < Lines.Length; ++i) {
s = Lines[i];
if (trimSpace)
s = s.Trim();
if (ignoreSpace) {
s = Regex.Replace(s, "\\s+", " "); // TODO: optimization: faster blank removal.
}
if (ignoreCase)
s = s.ToLower();
aCode = h[s];
if (aCode == null) {
lastUsedCode++;
h[s] = lastUsedCode;
Codes[i] = lastUsedCode;
} else {
Codes[i] = (int)aCode;
} // if
} // for
return (Codes);
} // DiffCodes
/// <summary>
/// This is the algorithm to find the Shortest Middle Snake (SMS).
/// </summary>
/// <param name="DataA">sequence A</param>
/// <param name="LowerA">lower bound of the actual range in DataA</param>
/// <param name="UpperA">upper bound of the actual range in DataA (exclusive)</param>
/// <param name="DataB">sequence B</param>
/// <param name="LowerB">lower bound of the actual range in DataB</param>
/// <param name="UpperB">upper bound of the actual range in DataB (exclusive)</param>
/// <param name="DownVector">a vector for the (0,0) to (x,y) search. Passed as a parameter for speed reasons.</param>
/// <param name="UpVector">a vector for the (u,v) to (N,M) search. Passed as a parameter for speed reasons.</param>
/// <returns>a MiddleSnakeData record containing x,y and u,v</returns>
private static SMSRD SMS(DiffData DataA, int LowerA, int UpperA, DiffData DataB, int LowerB, int UpperB,
int[] DownVector, int[] UpVector) {
SMSRD ret;
int MAX = DataA.Length + DataB.Length + 1;
int DownK = LowerA - LowerB; // the k-line to start the forward search
int UpK = UpperA - UpperB; // the k-line to start the reverse search
int Delta = (UpperA - LowerA) - (UpperB - LowerB);
bool oddDelta = (Delta & 1) != 0;
// The vectors in the publication accepts negative indexes. the vectors implemented here are 0-based
// and are access using a specific offset: UpOffset UpVector and DownOffset for DownVektor
int DownOffset = MAX - DownK;
int UpOffset = MAX - UpK;
int MaxD = ((UpperA - LowerA + UpperB - LowerB) / 2) + 1;
// Debug.Write(2, "SMS", String.Format("Search the box: A[{0}-{1}] to B[{2}-{3}]", LowerA, UpperA, LowerB, UpperB));
// init vectors
DownVector[DownOffset + DownK + 1] = LowerA;
UpVector[UpOffset + UpK - 1] = UpperA;
for (int D = 0; D <= MaxD; D++) {
// Extend the forward path.
for (int k = DownK - D; k <= DownK + D; k += 2) {
// Debug.Write(0, "SMS", "extend forward path " + k.ToString());
// find the only or better starting point
int x, y;
if (k == DownK - D) {
x = DownVector[DownOffset + k + 1]; // down
} else {
x = DownVector[DownOffset + k - 1] + 1; // a step to the right
if ((k < DownK + D) && (DownVector[DownOffset + k + 1] >= x))
x = DownVector[DownOffset + k + 1]; // down
}
y = x - k;
// find the end of the furthest reaching forward D-path in diagonal k.
while ((x < UpperA) && (y < UpperB) && (DataA.data[x] == DataB.data[y])) {
x++; y++;
}
DownVector[DownOffset + k] = x;
// overlap ?
if (oddDelta && (UpK - D < k) && (k < UpK + D)) {
if (UpVector[UpOffset + k] <= DownVector[DownOffset + k]) {
ret.x = DownVector[DownOffset + k];
ret.y = DownVector[DownOffset + k] - k;
// ret.u = UpVector[UpOffset + k]; // 2002.09.20: no need for 2 points
// ret.v = UpVector[UpOffset + k] - k;
return (ret);
} // if
} // if
} // for k
// Extend the reverse path.
for (int k = UpK - D; k <= UpK + D; k += 2) {
// Debug.Write(0, "SMS", "extend reverse path " + k.ToString());
// find the only or better starting point
int x, y;
if (k == UpK + D) {
x = UpVector[UpOffset + k - 1]; // up
} else {
x = UpVector[UpOffset + k + 1] - 1; // left
if ((k > UpK - D) && (UpVector[UpOffset + k - 1] < x))
x = UpVector[UpOffset + k - 1]; // up
} // if
y = x - k;
while ((x > LowerA) && (y > LowerB) && (DataA.data[x - 1] == DataB.data[y - 1])) {
x--; y--; // diagonal
}
UpVector[UpOffset + k] = x;
// overlap ?
if (!oddDelta && (DownK - D <= k) && (k <= DownK + D)) {
if (UpVector[UpOffset + k] <= DownVector[DownOffset + k]) {
ret.x = DownVector[DownOffset + k];
ret.y = DownVector[DownOffset + k] - k;
// ret.u = UpVector[UpOffset + k]; // 2002.09.20: no need for 2 points
// ret.v = UpVector[UpOffset + k] - k;
return (ret);
} // if
} // if
} // for k
} // for D
throw new ApplicationException("the algorithm should never come here.");
} // SMS
/// <summary>
/// This is the divide-and-conquer implementation of the longes common-subsequence (LCS)
/// algorithm.
/// The published algorithm passes recursively parts of the A and B sequences.
/// To avoid copying these arrays the lower and upper bounds are passed while the sequences stay constant.
/// </summary>
/// <param name="DataA">sequence A</param>
/// <param name="LowerA">lower bound of the actual range in DataA</param>
/// <param name="UpperA">upper bound of the actual range in DataA (exclusive)</param>
/// <param name="DataB">sequence B</param>
/// <param name="LowerB">lower bound of the actual range in DataB</param>
/// <param name="UpperB">upper bound of the actual range in DataB (exclusive)</param>
/// <param name="DownVector">a vector for the (0,0) to (x,y) search. Passed as a parameter for speed reasons.</param>
/// <param name="UpVector">a vector for the (u,v) to (N,M) search. Passed as a parameter for speed reasons.</param>
private static void LCS(DiffData DataA, int LowerA, int UpperA, DiffData DataB, int LowerB, int UpperB, int[] DownVector, int[] UpVector) {
// Debug.Write(2, "LCS", String.Format("Analyse the box: A[{0}-{1}] to B[{2}-{3}]", LowerA, UpperA, LowerB, UpperB));
// Fast walkthrough equal lines at the start
while (LowerA < UpperA && LowerB < UpperB && DataA.data[LowerA] == DataB.data[LowerB]) {
LowerA++; LowerB++;
}
// Fast walkthrough equal lines at the end
while (LowerA < UpperA && LowerB < UpperB && DataA.data[UpperA - 1] == DataB.data[UpperB - 1]) {
--UpperA; --UpperB;
}
if (LowerA == UpperA) {
// mark as inserted lines.
while (LowerB < UpperB)
DataB.modified[LowerB++] = true;
} else if (LowerB == UpperB) {
// mark as deleted lines.
while (LowerA < UpperA)
DataA.modified[LowerA++] = true;
} else {
// Find the middle snakea and length of an optimal path for A and B
SMSRD smsrd = SMS(DataA, LowerA, UpperA, DataB, LowerB, UpperB, DownVector, UpVector);
// Debug.Write(2, "MiddleSnakeData", String.Format("{0},{1}", smsrd.x, smsrd.y));
// The path is from LowerX to (x,y) and (x,y) to UpperX
LCS(DataA, LowerA, smsrd.x, DataB, LowerB, smsrd.y, DownVector, UpVector);
LCS(DataA, smsrd.x, UpperA, DataB, smsrd.y, UpperB, DownVector, UpVector); // 2002.09.20: no need for 2 points
}
} // LCS()
/// <summary>Scan the tables of which lines are inserted and deleted,
/// producing an edit script in forward order.
/// </summary>
/// dynamic array
private static Item[] CreateDiffs(DiffData DataA, DiffData DataB) {
ArrayList a = new ArrayList();
Item aItem;
Item[] result;
int StartA, StartB;
int LineA, LineB;
LineA = 0;
LineB = 0;
while (LineA < DataA.Length || LineB < DataB.Length) {
if ((LineA < DataA.Length) && (!DataA.modified[LineA])
&& (LineB < DataB.Length) && (!DataB.modified[LineB])) {
// equal lines
LineA++;
LineB++;
} else {
// maybe deleted and/or inserted lines
StartA = LineA;
StartB = LineB;
while (LineA < DataA.Length && (LineB >= DataB.Length || DataA.modified[LineA]))
// while (LineA < DataA.Length && DataA.modified[LineA])
LineA++;
while (LineB < DataB.Length && (LineA >= DataA.Length || DataB.modified[LineB]))
// while (LineB < DataB.Length && DataB.modified[LineB])
LineB++;
if ((StartA < LineA) || (StartB < LineB)) {
// store a new difference-item
aItem = new Item();
aItem.StartA = StartA;
aItem.StartB = StartB;
aItem.deletedA = LineA - StartA;
aItem.insertedB = LineB - StartB;
a.Add(aItem);
} // if
} // if
} // while
result = new Item[a.Count];
a.CopyTo(result);
return (result);
}
} // class Diff
/// <summary>Data on one input file being compared.
/// </summary>
internal class DiffData {
/// <summary>Number of elements (lines).</summary>
internal int Length;
/// <summary>Buffer of numbers that will be compared.</summary>
internal int[] data;
/// <summary>
/// Array of booleans that flag for modified data.
/// This is the result of the diff.
/// This means deletedA in the first Data or inserted in the second Data.
/// </summary>
internal bool[] modified;
/// <summary>
/// Initialize the Diff-Data buffer.
/// </summary>
/// <param name="data">reference to the buffer</param>
internal DiffData(int[] initData) {
data = initData;
Length = initData.Length;
modified = new bool[Length + 2];
} // DiffData
} // class DiffData
}
| |
//
// AsnEncodedData.cs - System.Security.Cryptography.AsnEncodedData
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Mono.Security;
using Mono.Security.Cryptography;
namespace System.Security.Cryptography {
internal enum AsnDecodeStatus {
NotDecoded = -1,
Ok = 0,
BadAsn = 1,
BadTag = 2,
BadLength = 3,
InformationNotAvailable = 4
}
public class AsnEncodedData {
internal Oid _oid;
internal byte[] _raw;
// constructors
protected AsnEncodedData ()
{
}
public AsnEncodedData (string oid, byte[] rawData)
{
_oid = new Oid (oid);
RawData = rawData;
}
public AsnEncodedData (Oid oid, byte[] rawData)
{
Oid = oid;
RawData = rawData;
// yes, here oid == null is legal (by design),
// but no, it would not be legal for an oid string
// see MSDN FDBK11479
}
public AsnEncodedData (AsnEncodedData asnEncodedData)
{
if (asnEncodedData == null)
throw new ArgumentNullException ("asnEncodedData");
Oid = new Oid (asnEncodedData._oid);
RawData = asnEncodedData._raw;
}
public AsnEncodedData (byte[] rawData)
{
RawData = rawData;
}
// properties
public Oid Oid {
get { return _oid; }
set {
if (value == null)
_oid = null;
else
_oid = new Oid (value);
}
}
public byte[] RawData {
get { return _raw; }
set {
if (value == null)
throw new ArgumentNullException ("RawData");
_raw = (byte[])value.Clone ();
}
}
// methods
public virtual void CopyFrom (AsnEncodedData asnEncodedData)
{
if (asnEncodedData == null)
throw new ArgumentNullException ("asnEncodedData");
if (asnEncodedData._oid == null)
Oid = null;
else
Oid = new Oid (asnEncodedData._oid);
RawData = asnEncodedData._raw;
}
public virtual string Format (bool multiLine)
{
if (_raw == null)
return String.Empty;
if (_oid == null)
return Default (multiLine);
return ToString (multiLine);
}
// internal decoding/formatting methods
internal virtual string ToString (bool multiLine)
{
switch (_oid.Value) {
// fx supported objects
case X509BasicConstraintsExtension.oid:
return BasicConstraintsExtension (multiLine);
case X509EnhancedKeyUsageExtension.oid:
return EnhancedKeyUsageExtension (multiLine);
case X509KeyUsageExtension.oid:
return KeyUsageExtension (multiLine);
case X509SubjectKeyIdentifierExtension.oid:
return SubjectKeyIdentifierExtension (multiLine);
// other known objects (i.e. supported structure) -
// but without any corresponding framework class
case Oid.oidSubjectAltName:
return SubjectAltName (multiLine);
case Oid.oidNetscapeCertType:
return NetscapeCertType (multiLine);
default:
return Default (multiLine);
}
}
internal string Default (bool multiLine)
{
StringBuilder sb = new StringBuilder ();
for (int i=0; i < _raw.Length; i++) {
sb.Append (_raw [i].ToString ("x2"));
if (i != _raw.Length - 1)
sb.Append (" ");
}
return sb.ToString ();
}
// Indirectly (undocumented but) supported extensions
internal string BasicConstraintsExtension (bool multiLine)
{
try {
X509BasicConstraintsExtension bc = new X509BasicConstraintsExtension (this, false);
return bc.ToString (multiLine);
}
catch {
return String.Empty;
}
}
internal string EnhancedKeyUsageExtension (bool multiLine)
{
try {
X509EnhancedKeyUsageExtension eku = new X509EnhancedKeyUsageExtension (this, false);
return eku.ToString (multiLine);
}
catch {
return String.Empty;
}
}
internal string KeyUsageExtension (bool multiLine)
{
try {
X509KeyUsageExtension ku = new X509KeyUsageExtension (this, false);
return ku.ToString (multiLine);
}
catch {
return String.Empty;
}
}
internal string SubjectKeyIdentifierExtension (bool multiLine)
{
try {
X509SubjectKeyIdentifierExtension ski = new X509SubjectKeyIdentifierExtension (this, false);
return ski.ToString (multiLine);
}
catch {
return String.Empty;
}
}
// Indirectly (undocumented but) supported extensions
internal string SubjectAltName (bool multiLine)
{
if (_raw.Length < 5)
return "Information Not Available";
try {
ASN1 ex = new ASN1 (_raw);
StringBuilder sb = new StringBuilder ();
for (int i=0; i < ex.Count; i++) {
ASN1 el = ex [i];
string type = null;
string name = null;
switch (el.Tag) {
case 0x81:
type = "RFC822 Name=";
name = Encoding.ASCII.GetString (el.Value);
break;
case 0x82:
type = "DNS Name=";
name = Encoding.ASCII.GetString (el.Value);
break;
default:
type = String.Format ("Unknown ({0})=", el.Tag);
name = CryptoConvert.ToHex (el.Value);
break;
}
sb.Append (type);
sb.Append (name);
if (multiLine) {
sb.Append (Environment.NewLine);
} else if (i < ex.Count - 1) {
sb.Append (", ");
}
}
return sb.ToString ();
}
catch {
return String.Empty;
}
}
internal string NetscapeCertType (bool multiLine)
{
// 4 byte long, BITSTRING (0x03), Value length of 2
if ((_raw.Length < 4) || (_raw [0] != 0x03) || (_raw [1] != 0x02))
return "Information Not Available";
// first value byte is the number of unused bits
int value = (_raw [3] >> _raw [2]) << _raw [2];
StringBuilder sb = new StringBuilder ();
if ((value & 0x80) == 0x80) {
sb.Append ("SSL Client Authentication");
}
if ((value & 0x40) == 0x40) {
if (sb.Length > 0)
sb.Append (", ");
sb.Append ("SSL Server Authentication");
}
if ((value & 0x20) == 0x20) {
if (sb.Length > 0)
sb.Append (", ");
sb.Append ("SMIME");
}
if ((value & 0x10) == 0x10) {
if (sb.Length > 0)
sb.Append (", ");
sb.Append ("Signature"); // a.k.a. Object Signing / Code Signing
}
if ((value & 0x08) == 0x08) {
if (sb.Length > 0)
sb.Append (", ");
sb.Append ("Unknown cert type");
}
if ((value & 0x04) == 0x04) {
if (sb.Length > 0)
sb.Append (", ");
sb.Append ("SSL CA"); // CA == Certificate Authority
}
if ((value & 0x02) == 0x02) {
if (sb.Length > 0)
sb.Append (", ");
sb.Append ("SMIME CA");
}
if ((value & 0x01) == 0x01) {
if (sb.Length > 0)
sb.Append (", ");
sb.Append ("Signature CA");
}
sb.AppendFormat (" ({0})", value.ToString ("x2"));
return sb.ToString ();
}
}
}
#endif
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Android.App;
using Android.OS;
using Android.Widget;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
namespace ArcGISRuntime.Samples.ConvexHull
{
[Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Convex hull",
category: "Geometry",
description: "Create a convex hull for a given set of points. The convex hull is a polygon with shortest perimeter that encloses a set of points. As a visual analogy, consider a set of points as nails in a board. The convex hull of the points would be like a rubber band stretched around the outermost nails.",
instructions: "Tap on the map to add points. Tap the \"Create Convex Hull\" button to generate the convex hull of those points. Tap the \"Reset\" button to start over.",
tags: new[] { "convex hull", "geometry", "spatial analysis" })]
public class ConvexHull : Activity
{
// Hold a reference to the map view.
private MapView _myMapView;
// Graphics overlay to display the hull.
private GraphicsOverlay _graphicsOverlay;
// List of geometry values (MapPoints in this case) that will be used by the GeometryEngine.ConvexHull operation.
private PointCollection _inputPointCollection = new PointCollection(SpatialReferences.WebMercator);
// Create a Button to create a convex hull.
private Button _convexHullButton;
// Create a Button to create a convex hull.
private Button _resetButton;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Convex hull";
// Create the UI, setup the control references and execute initialization.
CreateLayout();
Initialize();
}
private void Initialize()
{
// Create a map with a topographic basemap.
Map theMap = new Map(BasemapStyle.ArcGISTopographic);
// Assign the map to the MapView.
_myMapView.Map = theMap;
// Create an overlay to hold the lines of the hull.
_graphicsOverlay = new GraphicsOverlay();
// Add the created graphics overlay to the MapView.
_myMapView.GraphicsOverlays.Add(_graphicsOverlay);
// Wire up the MapView's GeoViewTapped event handler.
_myMapView.GeoViewTapped += MyMapView_GeoViewTapped;
}
private void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
{
try
{
// Normalize the tapped point.
var centralizedPoint = (MapPoint)GeometryEngine.NormalizeCentralMeridian(e.Location);
// Add the map point to the list that will be used by the GeometryEngine.ConvexHull operation.
_inputPointCollection.Add(centralizedPoint);
// Check if there are at least three points.
if (_inputPointCollection.Count > 2)
{
// Enable the button for creating hulls.
_convexHullButton.Enabled = true;
}
// Create a simple marker symbol to display where the user tapped/clicked on the map. The marker symbol
// will be a solid, red circle.
SimpleMarkerSymbol userTappedSimpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Red, 10);
// Create a new graphic for the spot where the user clicked on the map using the simple marker symbol.
Graphic userTappedGraphic = new Graphic(e.Location, new Dictionary<string, object>() { { "Type", "Point" } }, userTappedSimpleMarkerSymbol) { ZIndex = 0 };
// Set the Z index for the user tapped graphic so that it appears above the convex hull graphic(s) added later.
userTappedGraphic.ZIndex = 1;
// Add the user tapped/clicked map point graphic to the graphic overlay.
_graphicsOverlay.Graphics.Add(userTappedGraphic);
}
catch (System.Exception ex)
{
// Display an error message if there is a problem adding user tapped graphics.
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.SetTitle("Can't add user tapped graphic");
alertBuilder.SetMessage(ex.ToString());
alertBuilder.Show();
}
}
private void ConvexHullButton_Click(object sender, EventArgs e)
{
try
{
// Create a multi-point geometry from the user tapped input map points.
Multipoint inputMultipoint = new Multipoint(_inputPointCollection);
// Get the returned result from the convex hull operation.
Geometry convexHullGeometry = GeometryEngine.ConvexHull(inputMultipoint);
// Create a simple line symbol for the outline of the convex hull graphic(s).
SimpleLineSymbol convexHullSimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 4);
// Create the simple fill symbol for the convex hull graphic(s) - comprised of a fill style, fill
// color and outline. It will be a hollow (i.e.. see-through) polygon graphic with a thick red outline.
SimpleFillSymbol convexHullSimpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Null, System.Drawing.Color.Red,
convexHullSimpleLineSymbol);
// Create the graphic for the convex hull - comprised of a polygon shape and fill symbol.
Graphic convexHullGraphic = new Graphic(convexHullGeometry, new Dictionary<string, object>() { { "Type", "Hull" } }, convexHullSimpleFillSymbol) { ZIndex = 1 };
// Remove any existing convex hull graphics from the overlay.
foreach (Graphic g in new List<Graphic>(_graphicsOverlay.Graphics))
{
if ((string)g.Attributes["Type"] == "Hull")
{
_graphicsOverlay.Graphics.Remove(g);
}
}
// Add the convex hull graphic to the graphics overlay.
_graphicsOverlay.Graphics.Add(convexHullGraphic);
// Disable the button after has been used.
_convexHullButton.Enabled = false;
}
catch (System.Exception ex)
{
// Display an error message if there is a problem generating convex hull operation.
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.SetTitle("There was a problem generating the convex hull.");
alertBuilder.SetMessage(ex.ToString());
alertBuilder.Show();
}
}
private void ResetButton_Click(object sender, EventArgs e)
{
// Clear the existing points and graphics.
_inputPointCollection.Clear();
_graphicsOverlay.Graphics.Clear();
// Disable the convex hull button.
_convexHullButton.Enabled = false;
}
private void CreateLayout()
{
// Create a new vertical layout for the app.
LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical };
// Create a TextView for instructions.
TextView sampleInstructionsTextView = new TextView(this)
{
Text = "Tap on the map to create three or more points, then tap the 'Make Convex Hull' button."
};
layout.AddView(sampleInstructionsTextView);
// Create a Button to create the convex hull.
_convexHullButton = new Button(this)
{
Text = "Make Convex Hull"
};
_convexHullButton.Click += ConvexHullButton_Click;
_convexHullButton.Enabled = false;
layout.AddView(_convexHullButton);
// Create a Button to reset the convex hull.
_resetButton = new Button(this)
{
Text = "Reset"
};
_resetButton.Click += ResetButton_Click;
layout.AddView(_resetButton);
// Add the map view to the layout.
_myMapView = new MapView(this);
layout.AddView(_myMapView);
// Show the layout in the app.
SetContentView(layout);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.